BitcodeReader.cpp 297 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/Bitcode/BitcodeReader.h"
  9. #include "MetadataLoader.h"
  10. #include "ValueList.h"
  11. #include "llvm/ADT/APFloat.h"
  12. #include "llvm/ADT/APInt.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallString.h"
  17. #include "llvm/ADT/SmallVector.h"
  18. #include "llvm/ADT/StringRef.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/ADT/Twine.h"
  21. #include "llvm/Bitcode/BitcodeCommon.h"
  22. #include "llvm/Bitcode/LLVMBitCodes.h"
  23. #include "llvm/Bitstream/BitstreamReader.h"
  24. #include "llvm/Config/llvm-config.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/Comdat.h"
  31. #include "llvm/IR/Constant.h"
  32. #include "llvm/IR/Constants.h"
  33. #include "llvm/IR/DataLayout.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/Function.h"
  39. #include "llvm/IR/GVMaterializer.h"
  40. #include "llvm/IR/GetElementPtrTypeIterator.h"
  41. #include "llvm/IR/GlobalAlias.h"
  42. #include "llvm/IR/GlobalIFunc.h"
  43. #include "llvm/IR/GlobalObject.h"
  44. #include "llvm/IR/GlobalValue.h"
  45. #include "llvm/IR/GlobalVariable.h"
  46. #include "llvm/IR/InlineAsm.h"
  47. #include "llvm/IR/InstIterator.h"
  48. #include "llvm/IR/InstrTypes.h"
  49. #include "llvm/IR/Instruction.h"
  50. #include "llvm/IR/Instructions.h"
  51. #include "llvm/IR/Intrinsics.h"
  52. #include "llvm/IR/IntrinsicsAArch64.h"
  53. #include "llvm/IR/IntrinsicsARM.h"
  54. #include "llvm/IR/LLVMContext.h"
  55. #include "llvm/IR/Metadata.h"
  56. #include "llvm/IR/Module.h"
  57. #include "llvm/IR/ModuleSummaryIndex.h"
  58. #include "llvm/IR/Operator.h"
  59. #include "llvm/IR/Type.h"
  60. #include "llvm/IR/Value.h"
  61. #include "llvm/IR/Verifier.h"
  62. #include "llvm/Support/AtomicOrdering.h"
  63. #include "llvm/Support/Casting.h"
  64. #include "llvm/Support/CommandLine.h"
  65. #include "llvm/Support/Compiler.h"
  66. #include "llvm/Support/Debug.h"
  67. #include "llvm/Support/Error.h"
  68. #include "llvm/Support/ErrorHandling.h"
  69. #include "llvm/Support/ErrorOr.h"
  70. #include "llvm/Support/MathExtras.h"
  71. #include "llvm/Support/MemoryBuffer.h"
  72. #include "llvm/Support/ModRef.h"
  73. #include "llvm/Support/raw_ostream.h"
  74. #include <algorithm>
  75. #include <cassert>
  76. #include <cstddef>
  77. #include <cstdint>
  78. #include <deque>
  79. #include <map>
  80. #include <memory>
  81. #include <optional>
  82. #include <set>
  83. #include <string>
  84. #include <system_error>
  85. #include <tuple>
  86. #include <utility>
  87. #include <vector>
  88. using namespace llvm;
  89. static cl::opt<bool> PrintSummaryGUIDs(
  90. "print-summary-global-ids", cl::init(false), cl::Hidden,
  91. cl::desc(
  92. "Print the global id for each value when reading the module summary"));
  93. static cl::opt<bool> ExpandConstantExprs(
  94. "expand-constant-exprs", cl::Hidden,
  95. cl::desc(
  96. "Expand constant expressions to instructions for testing purposes"));
  97. namespace {
  98. enum {
  99. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  100. };
  101. } // end anonymous namespace
  102. static Error error(const Twine &Message) {
  103. return make_error<StringError>(
  104. Message, make_error_code(BitcodeError::CorruptedBitcode));
  105. }
  106. static Error hasInvalidBitcodeHeader(BitstreamCursor &Stream) {
  107. if (!Stream.canSkipToPos(4))
  108. return createStringError(std::errc::illegal_byte_sequence,
  109. "file too small to contain bitcode header");
  110. for (unsigned C : {'B', 'C'})
  111. if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
  112. if (Res.get() != C)
  113. return createStringError(std::errc::illegal_byte_sequence,
  114. "file doesn't start with bitcode header");
  115. } else
  116. return Res.takeError();
  117. for (unsigned C : {0x0, 0xC, 0xE, 0xD})
  118. if (Expected<SimpleBitstreamCursor::word_t> Res = Stream.Read(4)) {
  119. if (Res.get() != C)
  120. return createStringError(std::errc::illegal_byte_sequence,
  121. "file doesn't start with bitcode header");
  122. } else
  123. return Res.takeError();
  124. return Error::success();
  125. }
  126. static Expected<BitstreamCursor> initStream(MemoryBufferRef Buffer) {
  127. const unsigned char *BufPtr = (const unsigned char *)Buffer.getBufferStart();
  128. const unsigned char *BufEnd = BufPtr + Buffer.getBufferSize();
  129. if (Buffer.getBufferSize() & 3)
  130. return error("Invalid bitcode signature");
  131. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  132. // The magic number is 0x0B17C0DE stored in little endian.
  133. if (isBitcodeWrapper(BufPtr, BufEnd))
  134. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  135. return error("Invalid bitcode wrapper header");
  136. BitstreamCursor Stream(ArrayRef<uint8_t>(BufPtr, BufEnd));
  137. if (Error Err = hasInvalidBitcodeHeader(Stream))
  138. return std::move(Err);
  139. return std::move(Stream);
  140. }
  141. /// Convert a string from a record into an std::string, return true on failure.
  142. template <typename StrTy>
  143. static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  144. StrTy &Result) {
  145. if (Idx > Record.size())
  146. return true;
  147. Result.append(Record.begin() + Idx, Record.end());
  148. return false;
  149. }
  150. // Strip all the TBAA attachment for the module.
  151. static void stripTBAA(Module *M) {
  152. for (auto &F : *M) {
  153. if (F.isMaterializable())
  154. continue;
  155. for (auto &I : instructions(F))
  156. I.setMetadata(LLVMContext::MD_tbaa, nullptr);
  157. }
  158. }
  159. /// Read the "IDENTIFICATION_BLOCK_ID" block, do some basic enforcement on the
  160. /// "epoch" encoded in the bitcode, and return the producer name if any.
  161. static Expected<std::string> readIdentificationBlock(BitstreamCursor &Stream) {
  162. if (Error Err = Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
  163. return std::move(Err);
  164. // Read all the records.
  165. SmallVector<uint64_t, 64> Record;
  166. std::string ProducerIdentification;
  167. while (true) {
  168. BitstreamEntry Entry;
  169. if (Error E = Stream.advance().moveInto(Entry))
  170. return std::move(E);
  171. switch (Entry.Kind) {
  172. default:
  173. case BitstreamEntry::Error:
  174. return error("Malformed block");
  175. case BitstreamEntry::EndBlock:
  176. return ProducerIdentification;
  177. case BitstreamEntry::Record:
  178. // The interesting case.
  179. break;
  180. }
  181. // Read a record.
  182. Record.clear();
  183. Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
  184. if (!MaybeBitCode)
  185. return MaybeBitCode.takeError();
  186. switch (MaybeBitCode.get()) {
  187. default: // Default behavior: reject
  188. return error("Invalid value");
  189. case bitc::IDENTIFICATION_CODE_STRING: // IDENTIFICATION: [strchr x N]
  190. convertToString(Record, 0, ProducerIdentification);
  191. break;
  192. case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
  193. unsigned epoch = (unsigned)Record[0];
  194. if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
  195. return error(
  196. Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
  197. "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
  198. }
  199. }
  200. }
  201. }
  202. }
  203. static Expected<std::string> readIdentificationCode(BitstreamCursor &Stream) {
  204. // We expect a number of well-defined blocks, though we don't necessarily
  205. // need to understand them all.
  206. while (true) {
  207. if (Stream.AtEndOfStream())
  208. return "";
  209. BitstreamEntry Entry;
  210. if (Error E = Stream.advance().moveInto(Entry))
  211. return std::move(E);
  212. switch (Entry.Kind) {
  213. case BitstreamEntry::EndBlock:
  214. case BitstreamEntry::Error:
  215. return error("Malformed block");
  216. case BitstreamEntry::SubBlock:
  217. if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID)
  218. return readIdentificationBlock(Stream);
  219. // Ignore other sub-blocks.
  220. if (Error Err = Stream.SkipBlock())
  221. return std::move(Err);
  222. continue;
  223. case BitstreamEntry::Record:
  224. if (Error E = Stream.skipRecord(Entry.ID).takeError())
  225. return std::move(E);
  226. continue;
  227. }
  228. }
  229. }
  230. static Expected<bool> hasObjCCategoryInModule(BitstreamCursor &Stream) {
  231. if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  232. return std::move(Err);
  233. SmallVector<uint64_t, 64> Record;
  234. // Read all the records for this module.
  235. while (true) {
  236. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  237. if (!MaybeEntry)
  238. return MaybeEntry.takeError();
  239. BitstreamEntry Entry = MaybeEntry.get();
  240. switch (Entry.Kind) {
  241. case BitstreamEntry::SubBlock: // Handled for us already.
  242. case BitstreamEntry::Error:
  243. return error("Malformed block");
  244. case BitstreamEntry::EndBlock:
  245. return false;
  246. case BitstreamEntry::Record:
  247. // The interesting case.
  248. break;
  249. }
  250. // Read a record.
  251. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  252. if (!MaybeRecord)
  253. return MaybeRecord.takeError();
  254. switch (MaybeRecord.get()) {
  255. default:
  256. break; // Default behavior, ignore unknown content.
  257. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  258. std::string S;
  259. if (convertToString(Record, 0, S))
  260. return error("Invalid section name record");
  261. // Check for the i386 and other (x86_64, ARM) conventions
  262. if (S.find("__DATA,__objc_catlist") != std::string::npos ||
  263. S.find("__OBJC,__category") != std::string::npos)
  264. return true;
  265. break;
  266. }
  267. }
  268. Record.clear();
  269. }
  270. llvm_unreachable("Exit infinite loop");
  271. }
  272. static Expected<bool> hasObjCCategory(BitstreamCursor &Stream) {
  273. // We expect a number of well-defined blocks, though we don't necessarily
  274. // need to understand them all.
  275. while (true) {
  276. BitstreamEntry Entry;
  277. if (Error E = Stream.advance().moveInto(Entry))
  278. return std::move(E);
  279. switch (Entry.Kind) {
  280. case BitstreamEntry::Error:
  281. return error("Malformed block");
  282. case BitstreamEntry::EndBlock:
  283. return false;
  284. case BitstreamEntry::SubBlock:
  285. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  286. return hasObjCCategoryInModule(Stream);
  287. // Ignore other sub-blocks.
  288. if (Error Err = Stream.SkipBlock())
  289. return std::move(Err);
  290. continue;
  291. case BitstreamEntry::Record:
  292. if (Error E = Stream.skipRecord(Entry.ID).takeError())
  293. return std::move(E);
  294. continue;
  295. }
  296. }
  297. }
  298. static Expected<std::string> readModuleTriple(BitstreamCursor &Stream) {
  299. if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  300. return std::move(Err);
  301. SmallVector<uint64_t, 64> Record;
  302. std::string Triple;
  303. // Read all the records for this module.
  304. while (true) {
  305. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  306. if (!MaybeEntry)
  307. return MaybeEntry.takeError();
  308. BitstreamEntry Entry = MaybeEntry.get();
  309. switch (Entry.Kind) {
  310. case BitstreamEntry::SubBlock: // Handled for us already.
  311. case BitstreamEntry::Error:
  312. return error("Malformed block");
  313. case BitstreamEntry::EndBlock:
  314. return Triple;
  315. case BitstreamEntry::Record:
  316. // The interesting case.
  317. break;
  318. }
  319. // Read a record.
  320. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  321. if (!MaybeRecord)
  322. return MaybeRecord.takeError();
  323. switch (MaybeRecord.get()) {
  324. default: break; // Default behavior, ignore unknown content.
  325. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  326. std::string S;
  327. if (convertToString(Record, 0, S))
  328. return error("Invalid triple record");
  329. Triple = S;
  330. break;
  331. }
  332. }
  333. Record.clear();
  334. }
  335. llvm_unreachable("Exit infinite loop");
  336. }
  337. static Expected<std::string> readTriple(BitstreamCursor &Stream) {
  338. // We expect a number of well-defined blocks, though we don't necessarily
  339. // need to understand them all.
  340. while (true) {
  341. Expected<BitstreamEntry> MaybeEntry = Stream.advance();
  342. if (!MaybeEntry)
  343. return MaybeEntry.takeError();
  344. BitstreamEntry Entry = MaybeEntry.get();
  345. switch (Entry.Kind) {
  346. case BitstreamEntry::Error:
  347. return error("Malformed block");
  348. case BitstreamEntry::EndBlock:
  349. return "";
  350. case BitstreamEntry::SubBlock:
  351. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  352. return readModuleTriple(Stream);
  353. // Ignore other sub-blocks.
  354. if (Error Err = Stream.SkipBlock())
  355. return std::move(Err);
  356. continue;
  357. case BitstreamEntry::Record:
  358. if (llvm::Expected<unsigned> Skipped = Stream.skipRecord(Entry.ID))
  359. continue;
  360. else
  361. return Skipped.takeError();
  362. }
  363. }
  364. }
  365. namespace {
  366. class BitcodeReaderBase {
  367. protected:
  368. BitcodeReaderBase(BitstreamCursor Stream, StringRef Strtab)
  369. : Stream(std::move(Stream)), Strtab(Strtab) {
  370. this->Stream.setBlockInfo(&BlockInfo);
  371. }
  372. BitstreamBlockInfo BlockInfo;
  373. BitstreamCursor Stream;
  374. StringRef Strtab;
  375. /// In version 2 of the bitcode we store names of global values and comdats in
  376. /// a string table rather than in the VST.
  377. bool UseStrtab = false;
  378. Expected<unsigned> parseVersionRecord(ArrayRef<uint64_t> Record);
  379. /// If this module uses a string table, pop the reference to the string table
  380. /// and return the referenced string and the rest of the record. Otherwise
  381. /// just return the record itself.
  382. std::pair<StringRef, ArrayRef<uint64_t>>
  383. readNameFromStrtab(ArrayRef<uint64_t> Record);
  384. Error readBlockInfo();
  385. // Contains an arbitrary and optional string identifying the bitcode producer
  386. std::string ProducerIdentification;
  387. Error error(const Twine &Message);
  388. };
  389. } // end anonymous namespace
  390. Error BitcodeReaderBase::error(const Twine &Message) {
  391. std::string FullMsg = Message.str();
  392. if (!ProducerIdentification.empty())
  393. FullMsg += " (Producer: '" + ProducerIdentification + "' Reader: 'LLVM " +
  394. LLVM_VERSION_STRING "')";
  395. return ::error(FullMsg);
  396. }
  397. Expected<unsigned>
  398. BitcodeReaderBase::parseVersionRecord(ArrayRef<uint64_t> Record) {
  399. if (Record.empty())
  400. return error("Invalid version record");
  401. unsigned ModuleVersion = Record[0];
  402. if (ModuleVersion > 2)
  403. return error("Invalid value");
  404. UseStrtab = ModuleVersion >= 2;
  405. return ModuleVersion;
  406. }
  407. std::pair<StringRef, ArrayRef<uint64_t>>
  408. BitcodeReaderBase::readNameFromStrtab(ArrayRef<uint64_t> Record) {
  409. if (!UseStrtab)
  410. return {"", Record};
  411. // Invalid reference. Let the caller complain about the record being empty.
  412. if (Record[0] + Record[1] > Strtab.size())
  413. return {"", {}};
  414. return {StringRef(Strtab.data() + Record[0], Record[1]), Record.slice(2)};
  415. }
  416. namespace {
  417. /// This represents a constant expression or constant aggregate using a custom
  418. /// structure internal to the bitcode reader. Later, this structure will be
  419. /// expanded by materializeValue() either into a constant expression/aggregate,
  420. /// or into an instruction sequence at the point of use. This allows us to
  421. /// upgrade bitcode using constant expressions even if this kind of constant
  422. /// expression is no longer supported.
  423. class BitcodeConstant final : public Value,
  424. TrailingObjects<BitcodeConstant, unsigned> {
  425. friend TrailingObjects;
  426. // Value subclass ID: Pick largest possible value to avoid any clashes.
  427. static constexpr uint8_t SubclassID = 255;
  428. public:
  429. // Opcodes used for non-expressions. This includes constant aggregates
  430. // (struct, array, vector) that might need expansion, as well as non-leaf
  431. // constants that don't need expansion (no_cfi, dso_local, blockaddress),
  432. // but still go through BitcodeConstant to avoid different uselist orders
  433. // between the two cases.
  434. static constexpr uint8_t ConstantStructOpcode = 255;
  435. static constexpr uint8_t ConstantArrayOpcode = 254;
  436. static constexpr uint8_t ConstantVectorOpcode = 253;
  437. static constexpr uint8_t NoCFIOpcode = 252;
  438. static constexpr uint8_t DSOLocalEquivalentOpcode = 251;
  439. static constexpr uint8_t BlockAddressOpcode = 250;
  440. static constexpr uint8_t FirstSpecialOpcode = BlockAddressOpcode;
  441. // Separate struct to make passing different number of parameters to
  442. // BitcodeConstant::create() more convenient.
  443. struct ExtraInfo {
  444. uint8_t Opcode;
  445. uint8_t Flags;
  446. unsigned Extra;
  447. Type *SrcElemTy;
  448. ExtraInfo(uint8_t Opcode, uint8_t Flags = 0, unsigned Extra = 0,
  449. Type *SrcElemTy = nullptr)
  450. : Opcode(Opcode), Flags(Flags), Extra(Extra), SrcElemTy(SrcElemTy) {}
  451. };
  452. uint8_t Opcode;
  453. uint8_t Flags;
  454. unsigned NumOperands;
  455. unsigned Extra; // GEP inrange index or blockaddress BB id.
  456. Type *SrcElemTy; // GEP source element type.
  457. private:
  458. BitcodeConstant(Type *Ty, const ExtraInfo &Info, ArrayRef<unsigned> OpIDs)
  459. : Value(Ty, SubclassID), Opcode(Info.Opcode), Flags(Info.Flags),
  460. NumOperands(OpIDs.size()), Extra(Info.Extra),
  461. SrcElemTy(Info.SrcElemTy) {
  462. std::uninitialized_copy(OpIDs.begin(), OpIDs.end(),
  463. getTrailingObjects<unsigned>());
  464. }
  465. BitcodeConstant &operator=(const BitcodeConstant &) = delete;
  466. public:
  467. static BitcodeConstant *create(BumpPtrAllocator &A, Type *Ty,
  468. const ExtraInfo &Info,
  469. ArrayRef<unsigned> OpIDs) {
  470. void *Mem = A.Allocate(totalSizeToAlloc<unsigned>(OpIDs.size()),
  471. alignof(BitcodeConstant));
  472. return new (Mem) BitcodeConstant(Ty, Info, OpIDs);
  473. }
  474. static bool classof(const Value *V) { return V->getValueID() == SubclassID; }
  475. ArrayRef<unsigned> getOperandIDs() const {
  476. return ArrayRef(getTrailingObjects<unsigned>(), NumOperands);
  477. }
  478. std::optional<unsigned> getInRangeIndex() const {
  479. assert(Opcode == Instruction::GetElementPtr);
  480. if (Extra == (unsigned)-1)
  481. return std::nullopt;
  482. return Extra;
  483. }
  484. const char *getOpcodeName() const {
  485. return Instruction::getOpcodeName(Opcode);
  486. }
  487. };
  488. class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
  489. LLVMContext &Context;
  490. Module *TheModule = nullptr;
  491. // Next offset to start scanning for lazy parsing of function bodies.
  492. uint64_t NextUnreadBit = 0;
  493. // Last function offset found in the VST.
  494. uint64_t LastFunctionBlockBit = 0;
  495. bool SeenValueSymbolTable = false;
  496. uint64_t VSTOffset = 0;
  497. std::vector<std::string> SectionTable;
  498. std::vector<std::string> GCTable;
  499. std::vector<Type *> TypeList;
  500. /// Track type IDs of contained types. Order is the same as the contained
  501. /// types of a Type*. This is used during upgrades of typed pointer IR in
  502. /// opaque pointer mode.
  503. DenseMap<unsigned, SmallVector<unsigned, 1>> ContainedTypeIDs;
  504. /// In some cases, we need to create a type ID for a type that was not
  505. /// explicitly encoded in the bitcode, or we don't know about at the current
  506. /// point. For example, a global may explicitly encode the value type ID, but
  507. /// not have a type ID for the pointer to value type, for which we create a
  508. /// virtual type ID instead. This map stores the new type ID that was created
  509. /// for the given pair of Type and contained type ID.
  510. DenseMap<std::pair<Type *, unsigned>, unsigned> VirtualTypeIDs;
  511. DenseMap<Function *, unsigned> FunctionTypeIDs;
  512. /// Allocator for BitcodeConstants. This should come before ValueList,
  513. /// because the ValueList might hold ValueHandles to these constants, so
  514. /// ValueList must be destroyed before Alloc.
  515. BumpPtrAllocator Alloc;
  516. BitcodeReaderValueList ValueList;
  517. std::optional<MetadataLoader> MDLoader;
  518. std::vector<Comdat *> ComdatList;
  519. DenseSet<GlobalObject *> ImplicitComdatObjects;
  520. SmallVector<Instruction *, 64> InstructionList;
  521. std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInits;
  522. std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInits;
  523. struct FunctionOperandInfo {
  524. Function *F;
  525. unsigned PersonalityFn;
  526. unsigned Prefix;
  527. unsigned Prologue;
  528. };
  529. std::vector<FunctionOperandInfo> FunctionOperands;
  530. /// The set of attributes by index. Index zero in the file is for null, and
  531. /// is thus not represented here. As such all indices are off by one.
  532. std::vector<AttributeList> MAttributes;
  533. /// The set of attribute groups.
  534. std::map<unsigned, AttributeList> MAttributeGroups;
  535. /// While parsing a function body, this is a list of the basic blocks for the
  536. /// function.
  537. std::vector<BasicBlock*> FunctionBBs;
  538. // When reading the module header, this list is populated with functions that
  539. // have bodies later in the file.
  540. std::vector<Function*> FunctionsWithBodies;
  541. // When intrinsic functions are encountered which require upgrading they are
  542. // stored here with their replacement function.
  543. using UpdatedIntrinsicMap = DenseMap<Function *, Function *>;
  544. UpdatedIntrinsicMap UpgradedIntrinsics;
  545. // Several operations happen after the module header has been read, but
  546. // before function bodies are processed. This keeps track of whether
  547. // we've done this yet.
  548. bool SeenFirstFunctionBody = false;
  549. /// When function bodies are initially scanned, this map contains info about
  550. /// where to find deferred function body in the stream.
  551. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  552. /// When Metadata block is initially scanned when parsing the module, we may
  553. /// choose to defer parsing of the metadata. This vector contains info about
  554. /// which Metadata blocks are deferred.
  555. std::vector<uint64_t> DeferredMetadataInfo;
  556. /// These are basic blocks forward-referenced by block addresses. They are
  557. /// inserted lazily into functions when they're loaded. The basic block ID is
  558. /// its index into the vector.
  559. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  560. std::deque<Function *> BasicBlockFwdRefQueue;
  561. /// These are Functions that contain BlockAddresses which refer a different
  562. /// Function. When parsing the different Function, queue Functions that refer
  563. /// to the different Function. Those Functions must be materialized in order
  564. /// to resolve their BlockAddress constants before the different Function
  565. /// gets moved into another Module.
  566. std::vector<Function *> BackwardRefFunctions;
  567. /// Indicates that we are using a new encoding for instruction operands where
  568. /// most operands in the current FUNCTION_BLOCK are encoded relative to the
  569. /// instruction number, for a more compact encoding. Some instruction
  570. /// operands are not relative to the instruction ID: basic block numbers, and
  571. /// types. Once the old style function blocks have been phased out, we would
  572. /// not need this flag.
  573. bool UseRelativeIDs = false;
  574. /// True if all functions will be materialized, negating the need to process
  575. /// (e.g.) blockaddress forward references.
  576. bool WillMaterializeAllForwardRefs = false;
  577. bool StripDebugInfo = false;
  578. TBAAVerifier TBAAVerifyHelper;
  579. std::vector<std::string> BundleTags;
  580. SmallVector<SyncScope::ID, 8> SSIDs;
  581. std::optional<ValueTypeCallbackTy> ValueTypeCallback;
  582. public:
  583. BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
  584. StringRef ProducerIdentification, LLVMContext &Context);
  585. Error materializeForwardReferencedFunctions();
  586. Error materialize(GlobalValue *GV) override;
  587. Error materializeModule() override;
  588. std::vector<StructType *> getIdentifiedStructTypes() const override;
  589. /// Main interface to parsing a bitcode buffer.
  590. /// \returns true if an error occurred.
  591. Error parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
  592. bool IsImporting, ParserCallbacks Callbacks = {});
  593. static uint64_t decodeSignRotatedValue(uint64_t V);
  594. /// Materialize any deferred Metadata block.
  595. Error materializeMetadata() override;
  596. void setStripDebugInfo() override;
  597. private:
  598. std::vector<StructType *> IdentifiedStructTypes;
  599. StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
  600. StructType *createIdentifiedStructType(LLVMContext &Context);
  601. static constexpr unsigned InvalidTypeID = ~0u;
  602. Type *getTypeByID(unsigned ID);
  603. Type *getPtrElementTypeByID(unsigned ID);
  604. unsigned getContainedTypeID(unsigned ID, unsigned Idx = 0);
  605. unsigned getVirtualTypeID(Type *Ty, ArrayRef<unsigned> ContainedTypeIDs = {});
  606. void callValueTypeCallback(Value *F, unsigned TypeID);
  607. Expected<Value *> materializeValue(unsigned ValID, BasicBlock *InsertBB);
  608. Expected<Constant *> getValueForInitializer(unsigned ID);
  609. Value *getFnValueByID(unsigned ID, Type *Ty, unsigned TyID,
  610. BasicBlock *ConstExprInsertBB) {
  611. if (Ty && Ty->isMetadataTy())
  612. return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
  613. return ValueList.getValueFwdRef(ID, Ty, TyID, ConstExprInsertBB);
  614. }
  615. Metadata *getFnMetadataByID(unsigned ID) {
  616. return MDLoader->getMetadataFwdRefOrLoad(ID);
  617. }
  618. BasicBlock *getBasicBlock(unsigned ID) const {
  619. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  620. return FunctionBBs[ID];
  621. }
  622. AttributeList getAttributes(unsigned i) const {
  623. if (i-1 < MAttributes.size())
  624. return MAttributes[i-1];
  625. return AttributeList();
  626. }
  627. /// Read a value/type pair out of the specified record from slot 'Slot'.
  628. /// Increment Slot past the number of slots used in the record. Return true on
  629. /// failure.
  630. bool getValueTypePair(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  631. unsigned InstNum, Value *&ResVal, unsigned &TypeID,
  632. BasicBlock *ConstExprInsertBB) {
  633. if (Slot == Record.size()) return true;
  634. unsigned ValNo = (unsigned)Record[Slot++];
  635. // Adjust the ValNo, if it was encoded relative to the InstNum.
  636. if (UseRelativeIDs)
  637. ValNo = InstNum - ValNo;
  638. if (ValNo < InstNum) {
  639. // If this is not a forward reference, just return the value we already
  640. // have.
  641. TypeID = ValueList.getTypeID(ValNo);
  642. ResVal = getFnValueByID(ValNo, nullptr, TypeID, ConstExprInsertBB);
  643. assert((!ResVal || ResVal->getType() == getTypeByID(TypeID)) &&
  644. "Incorrect type ID stored for value");
  645. return ResVal == nullptr;
  646. }
  647. if (Slot == Record.size())
  648. return true;
  649. TypeID = (unsigned)Record[Slot++];
  650. ResVal = getFnValueByID(ValNo, getTypeByID(TypeID), TypeID,
  651. ConstExprInsertBB);
  652. return ResVal == nullptr;
  653. }
  654. /// Read a value out of the specified record from slot 'Slot'. Increment Slot
  655. /// past the number of slots used by the value in the record. Return true if
  656. /// there is an error.
  657. bool popValue(const SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  658. unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
  659. BasicBlock *ConstExprInsertBB) {
  660. if (getValue(Record, Slot, InstNum, Ty, TyID, ResVal, ConstExprInsertBB))
  661. return true;
  662. // All values currently take a single record slot.
  663. ++Slot;
  664. return false;
  665. }
  666. /// Like popValue, but does not increment the Slot number.
  667. bool getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  668. unsigned InstNum, Type *Ty, unsigned TyID, Value *&ResVal,
  669. BasicBlock *ConstExprInsertBB) {
  670. ResVal = getValue(Record, Slot, InstNum, Ty, TyID, ConstExprInsertBB);
  671. return ResVal == nullptr;
  672. }
  673. /// Version of getValue that returns ResVal directly, or 0 if there is an
  674. /// error.
  675. Value *getValue(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  676. unsigned InstNum, Type *Ty, unsigned TyID,
  677. BasicBlock *ConstExprInsertBB) {
  678. if (Slot == Record.size()) return nullptr;
  679. unsigned ValNo = (unsigned)Record[Slot];
  680. // Adjust the ValNo, if it was encoded relative to the InstNum.
  681. if (UseRelativeIDs)
  682. ValNo = InstNum - ValNo;
  683. return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
  684. }
  685. /// Like getValue, but decodes signed VBRs.
  686. Value *getValueSigned(const SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  687. unsigned InstNum, Type *Ty, unsigned TyID,
  688. BasicBlock *ConstExprInsertBB) {
  689. if (Slot == Record.size()) return nullptr;
  690. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  691. // Adjust the ValNo, if it was encoded relative to the InstNum.
  692. if (UseRelativeIDs)
  693. ValNo = InstNum - ValNo;
  694. return getFnValueByID(ValNo, Ty, TyID, ConstExprInsertBB);
  695. }
  696. /// Upgrades old-style typeless byval/sret/inalloca attributes by adding the
  697. /// corresponding argument's pointee type. Also upgrades intrinsics that now
  698. /// require an elementtype attribute.
  699. Error propagateAttributeTypes(CallBase *CB, ArrayRef<unsigned> ArgsTys);
  700. /// Converts alignment exponent (i.e. power of two (or zero)) to the
  701. /// corresponding alignment to use. If alignment is too large, returns
  702. /// a corresponding error code.
  703. Error parseAlignmentValue(uint64_t Exponent, MaybeAlign &Alignment);
  704. Error parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  705. Error parseModule(uint64_t ResumeBit, bool ShouldLazyLoadMetadata = false,
  706. ParserCallbacks Callbacks = {});
  707. Error parseComdatRecord(ArrayRef<uint64_t> Record);
  708. Error parseGlobalVarRecord(ArrayRef<uint64_t> Record);
  709. Error parseFunctionRecord(ArrayRef<uint64_t> Record);
  710. Error parseGlobalIndirectSymbolRecord(unsigned BitCode,
  711. ArrayRef<uint64_t> Record);
  712. Error parseAttributeBlock();
  713. Error parseAttributeGroupBlock();
  714. Error parseTypeTable();
  715. Error parseTypeTableBody();
  716. Error parseOperandBundleTags();
  717. Error parseSyncScopeNames();
  718. Expected<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
  719. unsigned NameIndex, Triple &TT);
  720. void setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta, Function *F,
  721. ArrayRef<uint64_t> Record);
  722. Error parseValueSymbolTable(uint64_t Offset = 0);
  723. Error parseGlobalValueSymbolTable();
  724. Error parseConstants();
  725. Error rememberAndSkipFunctionBodies();
  726. Error rememberAndSkipFunctionBody();
  727. /// Save the positions of the Metadata blocks and skip parsing the blocks.
  728. Error rememberAndSkipMetadata();
  729. Error typeCheckLoadStoreInst(Type *ValType, Type *PtrType);
  730. Error parseFunctionBody(Function *F);
  731. Error globalCleanup();
  732. Error resolveGlobalAndIndirectSymbolInits();
  733. Error parseUseLists();
  734. Error findFunctionInStream(
  735. Function *F,
  736. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  737. SyncScope::ID getDecodedSyncScopeID(unsigned Val);
  738. };
  739. /// Class to manage reading and parsing function summary index bitcode
  740. /// files/sections.
  741. class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
  742. /// The module index built during parsing.
  743. ModuleSummaryIndex &TheIndex;
  744. /// Indicates whether we have encountered a global value summary section
  745. /// yet during parsing.
  746. bool SeenGlobalValSummary = false;
  747. /// Indicates whether we have already parsed the VST, used for error checking.
  748. bool SeenValueSymbolTable = false;
  749. /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
  750. /// Used to enable on-demand parsing of the VST.
  751. uint64_t VSTOffset = 0;
  752. // Map to save ValueId to ValueInfo association that was recorded in the
  753. // ValueSymbolTable. It is used after the VST is parsed to convert
  754. // call graph edges read from the function summary from referencing
  755. // callees by their ValueId to using the ValueInfo instead, which is how
  756. // they are recorded in the summary index being built.
  757. // We save a GUID which refers to the same global as the ValueInfo, but
  758. // ignoring the linkage, i.e. for values other than local linkage they are
  759. // identical (this is the second tuple member).
  760. // The third tuple member is the real GUID of the ValueInfo.
  761. DenseMap<unsigned,
  762. std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>>
  763. ValueIdToValueInfoMap;
  764. /// Map populated during module path string table parsing, from the
  765. /// module ID to a string reference owned by the index's module
  766. /// path string table, used to correlate with combined index
  767. /// summary records.
  768. DenseMap<uint64_t, StringRef> ModuleIdMap;
  769. /// Original source file name recorded in a bitcode record.
  770. std::string SourceFileName;
  771. /// The string identifier given to this module by the client, normally the
  772. /// path to the bitcode file.
  773. StringRef ModulePath;
  774. /// For per-module summary indexes, the unique numerical identifier given to
  775. /// this module by the client.
  776. unsigned ModuleId;
  777. /// Callback to ask whether a symbol is the prevailing copy when invoked
  778. /// during combined index building.
  779. std::function<bool(GlobalValue::GUID)> IsPrevailing;
  780. /// Saves the stack ids from the STACK_IDS record to consult when adding stack
  781. /// ids from the lists in the callsite and alloc entries to the index.
  782. std::vector<uint64_t> StackIds;
  783. public:
  784. ModuleSummaryIndexBitcodeReader(
  785. BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
  786. StringRef ModulePath, unsigned ModuleId,
  787. std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
  788. Error parseModule();
  789. private:
  790. void setValueGUID(uint64_t ValueID, StringRef ValueName,
  791. GlobalValue::LinkageTypes Linkage,
  792. StringRef SourceFileName);
  793. Error parseValueSymbolTable(
  794. uint64_t Offset,
  795. DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
  796. std::vector<ValueInfo> makeRefList(ArrayRef<uint64_t> Record);
  797. std::vector<FunctionSummary::EdgeTy> makeCallList(ArrayRef<uint64_t> Record,
  798. bool IsOldProfileFormat,
  799. bool HasProfile,
  800. bool HasRelBF);
  801. Error parseEntireSummary(unsigned ID);
  802. Error parseModuleStringTable();
  803. void parseTypeIdCompatibleVtableSummaryRecord(ArrayRef<uint64_t> Record);
  804. void parseTypeIdCompatibleVtableInfo(ArrayRef<uint64_t> Record, size_t &Slot,
  805. TypeIdCompatibleVtableInfo &TypeId);
  806. std::vector<FunctionSummary::ParamAccess>
  807. parseParamAccesses(ArrayRef<uint64_t> Record);
  808. template <bool AllowNullValueInfo = false>
  809. std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
  810. getValueInfoFromValueId(unsigned ValueId);
  811. void addThisModule();
  812. ModuleSummaryIndex::ModuleInfo *getThisModule();
  813. };
  814. } // end anonymous namespace
  815. std::error_code llvm::errorToErrorCodeAndEmitErrors(LLVMContext &Ctx,
  816. Error Err) {
  817. if (Err) {
  818. std::error_code EC;
  819. handleAllErrors(std::move(Err), [&](ErrorInfoBase &EIB) {
  820. EC = EIB.convertToErrorCode();
  821. Ctx.emitError(EIB.message());
  822. });
  823. return EC;
  824. }
  825. return std::error_code();
  826. }
  827. BitcodeReader::BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
  828. StringRef ProducerIdentification,
  829. LLVMContext &Context)
  830. : BitcodeReaderBase(std::move(Stream), Strtab), Context(Context),
  831. ValueList(this->Stream.SizeInBytes(),
  832. [this](unsigned ValID, BasicBlock *InsertBB) {
  833. return materializeValue(ValID, InsertBB);
  834. }) {
  835. this->ProducerIdentification = std::string(ProducerIdentification);
  836. }
  837. Error BitcodeReader::materializeForwardReferencedFunctions() {
  838. if (WillMaterializeAllForwardRefs)
  839. return Error::success();
  840. // Prevent recursion.
  841. WillMaterializeAllForwardRefs = true;
  842. while (!BasicBlockFwdRefQueue.empty()) {
  843. Function *F = BasicBlockFwdRefQueue.front();
  844. BasicBlockFwdRefQueue.pop_front();
  845. assert(F && "Expected valid function");
  846. if (!BasicBlockFwdRefs.count(F))
  847. // Already materialized.
  848. continue;
  849. // Check for a function that isn't materializable to prevent an infinite
  850. // loop. When parsing a blockaddress stored in a global variable, there
  851. // isn't a trivial way to check if a function will have a body without a
  852. // linear search through FunctionsWithBodies, so just check it here.
  853. if (!F->isMaterializable())
  854. return error("Never resolved function from blockaddress");
  855. // Try to materialize F.
  856. if (Error Err = materialize(F))
  857. return Err;
  858. }
  859. assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
  860. for (Function *F : BackwardRefFunctions)
  861. if (Error Err = materialize(F))
  862. return Err;
  863. BackwardRefFunctions.clear();
  864. // Reset state.
  865. WillMaterializeAllForwardRefs = false;
  866. return Error::success();
  867. }
  868. //===----------------------------------------------------------------------===//
  869. // Helper functions to implement forward reference resolution, etc.
  870. //===----------------------------------------------------------------------===//
  871. static bool hasImplicitComdat(size_t Val) {
  872. switch (Val) {
  873. default:
  874. return false;
  875. case 1: // Old WeakAnyLinkage
  876. case 4: // Old LinkOnceAnyLinkage
  877. case 10: // Old WeakODRLinkage
  878. case 11: // Old LinkOnceODRLinkage
  879. return true;
  880. }
  881. }
  882. static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
  883. switch (Val) {
  884. default: // Map unknown/new linkages to external
  885. case 0:
  886. return GlobalValue::ExternalLinkage;
  887. case 2:
  888. return GlobalValue::AppendingLinkage;
  889. case 3:
  890. return GlobalValue::InternalLinkage;
  891. case 5:
  892. return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
  893. case 6:
  894. return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
  895. case 7:
  896. return GlobalValue::ExternalWeakLinkage;
  897. case 8:
  898. return GlobalValue::CommonLinkage;
  899. case 9:
  900. return GlobalValue::PrivateLinkage;
  901. case 12:
  902. return GlobalValue::AvailableExternallyLinkage;
  903. case 13:
  904. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
  905. case 14:
  906. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
  907. case 15:
  908. return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
  909. case 1: // Old value with implicit comdat.
  910. case 16:
  911. return GlobalValue::WeakAnyLinkage;
  912. case 10: // Old value with implicit comdat.
  913. case 17:
  914. return GlobalValue::WeakODRLinkage;
  915. case 4: // Old value with implicit comdat.
  916. case 18:
  917. return GlobalValue::LinkOnceAnyLinkage;
  918. case 11: // Old value with implicit comdat.
  919. case 19:
  920. return GlobalValue::LinkOnceODRLinkage;
  921. }
  922. }
  923. static FunctionSummary::FFlags getDecodedFFlags(uint64_t RawFlags) {
  924. FunctionSummary::FFlags Flags;
  925. Flags.ReadNone = RawFlags & 0x1;
  926. Flags.ReadOnly = (RawFlags >> 1) & 0x1;
  927. Flags.NoRecurse = (RawFlags >> 2) & 0x1;
  928. Flags.ReturnDoesNotAlias = (RawFlags >> 3) & 0x1;
  929. Flags.NoInline = (RawFlags >> 4) & 0x1;
  930. Flags.AlwaysInline = (RawFlags >> 5) & 0x1;
  931. Flags.NoUnwind = (RawFlags >> 6) & 0x1;
  932. Flags.MayThrow = (RawFlags >> 7) & 0x1;
  933. Flags.HasUnknownCall = (RawFlags >> 8) & 0x1;
  934. Flags.MustBeUnreachable = (RawFlags >> 9) & 0x1;
  935. return Flags;
  936. }
  937. // Decode the flags for GlobalValue in the summary. The bits for each attribute:
  938. //
  939. // linkage: [0,4), notEligibleToImport: 4, live: 5, local: 6, canAutoHide: 7,
  940. // visibility: [8, 10).
  941. static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
  942. uint64_t Version) {
  943. // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
  944. // like getDecodedLinkage() above. Any future change to the linkage enum and
  945. // to getDecodedLinkage() will need to be taken into account here as above.
  946. auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
  947. auto Visibility = GlobalValue::VisibilityTypes((RawFlags >> 8) & 3); // 2 bits
  948. RawFlags = RawFlags >> 4;
  949. bool NotEligibleToImport = (RawFlags & 0x1) || Version < 3;
  950. // The Live flag wasn't introduced until version 3. For dead stripping
  951. // to work correctly on earlier versions, we must conservatively treat all
  952. // values as live.
  953. bool Live = (RawFlags & 0x2) || Version < 3;
  954. bool Local = (RawFlags & 0x4);
  955. bool AutoHide = (RawFlags & 0x8);
  956. return GlobalValueSummary::GVFlags(Linkage, Visibility, NotEligibleToImport,
  957. Live, Local, AutoHide);
  958. }
  959. // Decode the flags for GlobalVariable in the summary
  960. static GlobalVarSummary::GVarFlags getDecodedGVarFlags(uint64_t RawFlags) {
  961. return GlobalVarSummary::GVarFlags(
  962. (RawFlags & 0x1) ? true : false, (RawFlags & 0x2) ? true : false,
  963. (RawFlags & 0x4) ? true : false,
  964. (GlobalObject::VCallVisibility)(RawFlags >> 3));
  965. }
  966. static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
  967. switch (Val) {
  968. default: // Map unknown visibilities to default.
  969. case 0: return GlobalValue::DefaultVisibility;
  970. case 1: return GlobalValue::HiddenVisibility;
  971. case 2: return GlobalValue::ProtectedVisibility;
  972. }
  973. }
  974. static GlobalValue::DLLStorageClassTypes
  975. getDecodedDLLStorageClass(unsigned Val) {
  976. switch (Val) {
  977. default: // Map unknown values to default.
  978. case 0: return GlobalValue::DefaultStorageClass;
  979. case 1: return GlobalValue::DLLImportStorageClass;
  980. case 2: return GlobalValue::DLLExportStorageClass;
  981. }
  982. }
  983. static bool getDecodedDSOLocal(unsigned Val) {
  984. switch(Val) {
  985. default: // Map unknown values to preemptable.
  986. case 0: return false;
  987. case 1: return true;
  988. }
  989. }
  990. static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
  991. switch (Val) {
  992. case 0: return GlobalVariable::NotThreadLocal;
  993. default: // Map unknown non-zero value to general dynamic.
  994. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  995. case 2: return GlobalVariable::LocalDynamicTLSModel;
  996. case 3: return GlobalVariable::InitialExecTLSModel;
  997. case 4: return GlobalVariable::LocalExecTLSModel;
  998. }
  999. }
  1000. static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
  1001. switch (Val) {
  1002. default: // Map unknown to UnnamedAddr::None.
  1003. case 0: return GlobalVariable::UnnamedAddr::None;
  1004. case 1: return GlobalVariable::UnnamedAddr::Global;
  1005. case 2: return GlobalVariable::UnnamedAddr::Local;
  1006. }
  1007. }
  1008. static int getDecodedCastOpcode(unsigned Val) {
  1009. switch (Val) {
  1010. default: return -1;
  1011. case bitc::CAST_TRUNC : return Instruction::Trunc;
  1012. case bitc::CAST_ZEXT : return Instruction::ZExt;
  1013. case bitc::CAST_SEXT : return Instruction::SExt;
  1014. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  1015. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  1016. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  1017. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  1018. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  1019. case bitc::CAST_FPEXT : return Instruction::FPExt;
  1020. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  1021. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  1022. case bitc::CAST_BITCAST : return Instruction::BitCast;
  1023. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  1024. }
  1025. }
  1026. static int getDecodedUnaryOpcode(unsigned Val, Type *Ty) {
  1027. bool IsFP = Ty->isFPOrFPVectorTy();
  1028. // UnOps are only valid for int/fp or vector of int/fp types
  1029. if (!IsFP && !Ty->isIntOrIntVectorTy())
  1030. return -1;
  1031. switch (Val) {
  1032. default:
  1033. return -1;
  1034. case bitc::UNOP_FNEG:
  1035. return IsFP ? Instruction::FNeg : -1;
  1036. }
  1037. }
  1038. static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  1039. bool IsFP = Ty->isFPOrFPVectorTy();
  1040. // BinOps are only valid for int/fp or vector of int/fp types
  1041. if (!IsFP && !Ty->isIntOrIntVectorTy())
  1042. return -1;
  1043. switch (Val) {
  1044. default:
  1045. return -1;
  1046. case bitc::BINOP_ADD:
  1047. return IsFP ? Instruction::FAdd : Instruction::Add;
  1048. case bitc::BINOP_SUB:
  1049. return IsFP ? Instruction::FSub : Instruction::Sub;
  1050. case bitc::BINOP_MUL:
  1051. return IsFP ? Instruction::FMul : Instruction::Mul;
  1052. case bitc::BINOP_UDIV:
  1053. return IsFP ? -1 : Instruction::UDiv;
  1054. case bitc::BINOP_SDIV:
  1055. return IsFP ? Instruction::FDiv : Instruction::SDiv;
  1056. case bitc::BINOP_UREM:
  1057. return IsFP ? -1 : Instruction::URem;
  1058. case bitc::BINOP_SREM:
  1059. return IsFP ? Instruction::FRem : Instruction::SRem;
  1060. case bitc::BINOP_SHL:
  1061. return IsFP ? -1 : Instruction::Shl;
  1062. case bitc::BINOP_LSHR:
  1063. return IsFP ? -1 : Instruction::LShr;
  1064. case bitc::BINOP_ASHR:
  1065. return IsFP ? -1 : Instruction::AShr;
  1066. case bitc::BINOP_AND:
  1067. return IsFP ? -1 : Instruction::And;
  1068. case bitc::BINOP_OR:
  1069. return IsFP ? -1 : Instruction::Or;
  1070. case bitc::BINOP_XOR:
  1071. return IsFP ? -1 : Instruction::Xor;
  1072. }
  1073. }
  1074. static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
  1075. switch (Val) {
  1076. default: return AtomicRMWInst::BAD_BINOP;
  1077. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  1078. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  1079. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  1080. case bitc::RMW_AND: return AtomicRMWInst::And;
  1081. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  1082. case bitc::RMW_OR: return AtomicRMWInst::Or;
  1083. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  1084. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  1085. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  1086. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  1087. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  1088. case bitc::RMW_FADD: return AtomicRMWInst::FAdd;
  1089. case bitc::RMW_FSUB: return AtomicRMWInst::FSub;
  1090. case bitc::RMW_FMAX: return AtomicRMWInst::FMax;
  1091. case bitc::RMW_FMIN: return AtomicRMWInst::FMin;
  1092. case bitc::RMW_UINC_WRAP:
  1093. return AtomicRMWInst::UIncWrap;
  1094. case bitc::RMW_UDEC_WRAP:
  1095. return AtomicRMWInst::UDecWrap;
  1096. }
  1097. }
  1098. static AtomicOrdering getDecodedOrdering(unsigned Val) {
  1099. switch (Val) {
  1100. case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
  1101. case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
  1102. case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
  1103. case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
  1104. case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
  1105. case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
  1106. default: // Map unknown orderings to sequentially-consistent.
  1107. case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
  1108. }
  1109. }
  1110. static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
  1111. switch (Val) {
  1112. default: // Map unknown selection kinds to any.
  1113. case bitc::COMDAT_SELECTION_KIND_ANY:
  1114. return Comdat::Any;
  1115. case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
  1116. return Comdat::ExactMatch;
  1117. case bitc::COMDAT_SELECTION_KIND_LARGEST:
  1118. return Comdat::Largest;
  1119. case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
  1120. return Comdat::NoDeduplicate;
  1121. case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
  1122. return Comdat::SameSize;
  1123. }
  1124. }
  1125. static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
  1126. FastMathFlags FMF;
  1127. if (0 != (Val & bitc::UnsafeAlgebra))
  1128. FMF.setFast();
  1129. if (0 != (Val & bitc::AllowReassoc))
  1130. FMF.setAllowReassoc();
  1131. if (0 != (Val & bitc::NoNaNs))
  1132. FMF.setNoNaNs();
  1133. if (0 != (Val & bitc::NoInfs))
  1134. FMF.setNoInfs();
  1135. if (0 != (Val & bitc::NoSignedZeros))
  1136. FMF.setNoSignedZeros();
  1137. if (0 != (Val & bitc::AllowReciprocal))
  1138. FMF.setAllowReciprocal();
  1139. if (0 != (Val & bitc::AllowContract))
  1140. FMF.setAllowContract(true);
  1141. if (0 != (Val & bitc::ApproxFunc))
  1142. FMF.setApproxFunc();
  1143. return FMF;
  1144. }
  1145. static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
  1146. // A GlobalValue with local linkage cannot have a DLL storage class.
  1147. if (GV->hasLocalLinkage())
  1148. return;
  1149. switch (Val) {
  1150. case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
  1151. case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
  1152. }
  1153. }
  1154. Type *BitcodeReader::getTypeByID(unsigned ID) {
  1155. // The type table size is always specified correctly.
  1156. if (ID >= TypeList.size())
  1157. return nullptr;
  1158. if (Type *Ty = TypeList[ID])
  1159. return Ty;
  1160. // If we have a forward reference, the only possible case is when it is to a
  1161. // named struct. Just create a placeholder for now.
  1162. return TypeList[ID] = createIdentifiedStructType(Context);
  1163. }
  1164. unsigned BitcodeReader::getContainedTypeID(unsigned ID, unsigned Idx) {
  1165. auto It = ContainedTypeIDs.find(ID);
  1166. if (It == ContainedTypeIDs.end())
  1167. return InvalidTypeID;
  1168. if (Idx >= It->second.size())
  1169. return InvalidTypeID;
  1170. return It->second[Idx];
  1171. }
  1172. Type *BitcodeReader::getPtrElementTypeByID(unsigned ID) {
  1173. if (ID >= TypeList.size())
  1174. return nullptr;
  1175. Type *Ty = TypeList[ID];
  1176. if (!Ty->isPointerTy())
  1177. return nullptr;
  1178. Type *ElemTy = getTypeByID(getContainedTypeID(ID, 0));
  1179. if (!ElemTy)
  1180. return nullptr;
  1181. assert(cast<PointerType>(Ty)->isOpaqueOrPointeeTypeMatches(ElemTy) &&
  1182. "Incorrect element type");
  1183. return ElemTy;
  1184. }
  1185. unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
  1186. ArrayRef<unsigned> ChildTypeIDs) {
  1187. unsigned ChildTypeID = ChildTypeIDs.empty() ? InvalidTypeID : ChildTypeIDs[0];
  1188. auto CacheKey = std::make_pair(Ty, ChildTypeID);
  1189. auto It = VirtualTypeIDs.find(CacheKey);
  1190. if (It != VirtualTypeIDs.end()) {
  1191. // The cmpxchg return value is the only place we need more than one
  1192. // contained type ID, however the second one will always be the same (i1),
  1193. // so we don't need to include it in the cache key. This asserts that the
  1194. // contained types are indeed as expected and there are no collisions.
  1195. assert((ChildTypeIDs.empty() ||
  1196. ContainedTypeIDs[It->second] == ChildTypeIDs) &&
  1197. "Incorrect cached contained type IDs");
  1198. return It->second;
  1199. }
  1200. #ifndef NDEBUG
  1201. if (!Ty->isOpaquePointerTy()) {
  1202. assert(Ty->getNumContainedTypes() == ChildTypeIDs.size() &&
  1203. "Wrong number of contained types");
  1204. for (auto Pair : zip(Ty->subtypes(), ChildTypeIDs)) {
  1205. assert(std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) &&
  1206. "Incorrect contained type ID");
  1207. }
  1208. }
  1209. #endif
  1210. unsigned TypeID = TypeList.size();
  1211. TypeList.push_back(Ty);
  1212. if (!ChildTypeIDs.empty())
  1213. append_range(ContainedTypeIDs[TypeID], ChildTypeIDs);
  1214. VirtualTypeIDs.insert({CacheKey, TypeID});
  1215. return TypeID;
  1216. }
  1217. static bool isConstExprSupported(uint8_t Opcode) {
  1218. // These are not real constant expressions, always consider them supported.
  1219. if (Opcode >= BitcodeConstant::FirstSpecialOpcode)
  1220. return true;
  1221. // If -expand-constant-exprs is set, we want to consider all expressions
  1222. // as unsupported.
  1223. if (ExpandConstantExprs)
  1224. return false;
  1225. if (Instruction::isBinaryOp(Opcode))
  1226. return ConstantExpr::isSupportedBinOp(Opcode);
  1227. return Opcode != Instruction::FNeg;
  1228. }
  1229. Expected<Value *> BitcodeReader::materializeValue(unsigned StartValID,
  1230. BasicBlock *InsertBB) {
  1231. // Quickly handle the case where there is no BitcodeConstant to resolve.
  1232. if (StartValID < ValueList.size() && ValueList[StartValID] &&
  1233. !isa<BitcodeConstant>(ValueList[StartValID]))
  1234. return ValueList[StartValID];
  1235. SmallDenseMap<unsigned, Value *> MaterializedValues;
  1236. SmallVector<unsigned> Worklist;
  1237. Worklist.push_back(StartValID);
  1238. while (!Worklist.empty()) {
  1239. unsigned ValID = Worklist.back();
  1240. if (MaterializedValues.count(ValID)) {
  1241. // Duplicate expression that was already handled.
  1242. Worklist.pop_back();
  1243. continue;
  1244. }
  1245. if (ValID >= ValueList.size() || !ValueList[ValID])
  1246. return error("Invalid value ID");
  1247. Value *V = ValueList[ValID];
  1248. auto *BC = dyn_cast<BitcodeConstant>(V);
  1249. if (!BC) {
  1250. MaterializedValues.insert({ValID, V});
  1251. Worklist.pop_back();
  1252. continue;
  1253. }
  1254. // Iterate in reverse, so values will get popped from the worklist in
  1255. // expected order.
  1256. SmallVector<Value *> Ops;
  1257. for (unsigned OpID : reverse(BC->getOperandIDs())) {
  1258. auto It = MaterializedValues.find(OpID);
  1259. if (It != MaterializedValues.end())
  1260. Ops.push_back(It->second);
  1261. else
  1262. Worklist.push_back(OpID);
  1263. }
  1264. // Some expressions have not been resolved yet, handle them first and then
  1265. // revisit this one.
  1266. if (Ops.size() != BC->getOperandIDs().size())
  1267. continue;
  1268. std::reverse(Ops.begin(), Ops.end());
  1269. SmallVector<Constant *> ConstOps;
  1270. for (Value *Op : Ops)
  1271. if (auto *C = dyn_cast<Constant>(Op))
  1272. ConstOps.push_back(C);
  1273. // Materialize as constant expression if possible.
  1274. if (isConstExprSupported(BC->Opcode) && ConstOps.size() == Ops.size()) {
  1275. Constant *C;
  1276. if (Instruction::isCast(BC->Opcode)) {
  1277. C = UpgradeBitCastExpr(BC->Opcode, ConstOps[0], BC->getType());
  1278. if (!C)
  1279. C = ConstantExpr::getCast(BC->Opcode, ConstOps[0], BC->getType());
  1280. } else if (Instruction::isBinaryOp(BC->Opcode)) {
  1281. C = ConstantExpr::get(BC->Opcode, ConstOps[0], ConstOps[1], BC->Flags);
  1282. } else {
  1283. switch (BC->Opcode) {
  1284. case BitcodeConstant::NoCFIOpcode: {
  1285. auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
  1286. if (!GV)
  1287. return error("no_cfi operand must be GlobalValue");
  1288. C = NoCFIValue::get(GV);
  1289. break;
  1290. }
  1291. case BitcodeConstant::DSOLocalEquivalentOpcode: {
  1292. auto *GV = dyn_cast<GlobalValue>(ConstOps[0]);
  1293. if (!GV)
  1294. return error("dso_local operand must be GlobalValue");
  1295. C = DSOLocalEquivalent::get(GV);
  1296. break;
  1297. }
  1298. case BitcodeConstant::BlockAddressOpcode: {
  1299. Function *Fn = dyn_cast<Function>(ConstOps[0]);
  1300. if (!Fn)
  1301. return error("blockaddress operand must be a function");
  1302. // If the function is already parsed we can insert the block address
  1303. // right away.
  1304. BasicBlock *BB;
  1305. unsigned BBID = BC->Extra;
  1306. if (!BBID)
  1307. // Invalid reference to entry block.
  1308. return error("Invalid ID");
  1309. if (!Fn->empty()) {
  1310. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  1311. for (size_t I = 0, E = BBID; I != E; ++I) {
  1312. if (BBI == BBE)
  1313. return error("Invalid ID");
  1314. ++BBI;
  1315. }
  1316. BB = &*BBI;
  1317. } else {
  1318. // Otherwise insert a placeholder and remember it so it can be
  1319. // inserted when the function is parsed.
  1320. auto &FwdBBs = BasicBlockFwdRefs[Fn];
  1321. if (FwdBBs.empty())
  1322. BasicBlockFwdRefQueue.push_back(Fn);
  1323. if (FwdBBs.size() < BBID + 1)
  1324. FwdBBs.resize(BBID + 1);
  1325. if (!FwdBBs[BBID])
  1326. FwdBBs[BBID] = BasicBlock::Create(Context);
  1327. BB = FwdBBs[BBID];
  1328. }
  1329. C = BlockAddress::get(Fn, BB);
  1330. break;
  1331. }
  1332. case BitcodeConstant::ConstantStructOpcode:
  1333. C = ConstantStruct::get(cast<StructType>(BC->getType()), ConstOps);
  1334. break;
  1335. case BitcodeConstant::ConstantArrayOpcode:
  1336. C = ConstantArray::get(cast<ArrayType>(BC->getType()), ConstOps);
  1337. break;
  1338. case BitcodeConstant::ConstantVectorOpcode:
  1339. C = ConstantVector::get(ConstOps);
  1340. break;
  1341. case Instruction::ICmp:
  1342. case Instruction::FCmp:
  1343. C = ConstantExpr::getCompare(BC->Flags, ConstOps[0], ConstOps[1]);
  1344. break;
  1345. case Instruction::GetElementPtr:
  1346. C = ConstantExpr::getGetElementPtr(BC->SrcElemTy, ConstOps[0],
  1347. ArrayRef(ConstOps).drop_front(),
  1348. BC->Flags, BC->getInRangeIndex());
  1349. break;
  1350. case Instruction::Select:
  1351. C = ConstantExpr::getSelect(ConstOps[0], ConstOps[1], ConstOps[2]);
  1352. break;
  1353. case Instruction::ExtractElement:
  1354. C = ConstantExpr::getExtractElement(ConstOps[0], ConstOps[1]);
  1355. break;
  1356. case Instruction::InsertElement:
  1357. C = ConstantExpr::getInsertElement(ConstOps[0], ConstOps[1],
  1358. ConstOps[2]);
  1359. break;
  1360. case Instruction::ShuffleVector: {
  1361. SmallVector<int, 16> Mask;
  1362. ShuffleVectorInst::getShuffleMask(ConstOps[2], Mask);
  1363. C = ConstantExpr::getShuffleVector(ConstOps[0], ConstOps[1], Mask);
  1364. break;
  1365. }
  1366. default:
  1367. llvm_unreachable("Unhandled bitcode constant");
  1368. }
  1369. }
  1370. // Cache resolved constant.
  1371. ValueList.replaceValueWithoutRAUW(ValID, C);
  1372. MaterializedValues.insert({ValID, C});
  1373. Worklist.pop_back();
  1374. continue;
  1375. }
  1376. if (!InsertBB)
  1377. return error(Twine("Value referenced by initializer is an unsupported "
  1378. "constant expression of type ") +
  1379. BC->getOpcodeName());
  1380. // Materialize as instructions if necessary.
  1381. Instruction *I;
  1382. if (Instruction::isCast(BC->Opcode)) {
  1383. I = CastInst::Create((Instruction::CastOps)BC->Opcode, Ops[0],
  1384. BC->getType(), "constexpr", InsertBB);
  1385. } else if (Instruction::isUnaryOp(BC->Opcode)) {
  1386. I = UnaryOperator::Create((Instruction::UnaryOps)BC->Opcode, Ops[0],
  1387. "constexpr", InsertBB);
  1388. } else if (Instruction::isBinaryOp(BC->Opcode)) {
  1389. I = BinaryOperator::Create((Instruction::BinaryOps)BC->Opcode, Ops[0],
  1390. Ops[1], "constexpr", InsertBB);
  1391. if (isa<OverflowingBinaryOperator>(I)) {
  1392. if (BC->Flags & OverflowingBinaryOperator::NoSignedWrap)
  1393. I->setHasNoSignedWrap();
  1394. if (BC->Flags & OverflowingBinaryOperator::NoUnsignedWrap)
  1395. I->setHasNoUnsignedWrap();
  1396. }
  1397. if (isa<PossiblyExactOperator>(I) &&
  1398. (BC->Flags & PossiblyExactOperator::IsExact))
  1399. I->setIsExact();
  1400. } else {
  1401. switch (BC->Opcode) {
  1402. case BitcodeConstant::ConstantVectorOpcode: {
  1403. Type *IdxTy = Type::getInt32Ty(BC->getContext());
  1404. Value *V = PoisonValue::get(BC->getType());
  1405. for (auto Pair : enumerate(Ops)) {
  1406. Value *Idx = ConstantInt::get(IdxTy, Pair.index());
  1407. V = InsertElementInst::Create(V, Pair.value(), Idx, "constexpr.ins",
  1408. InsertBB);
  1409. }
  1410. I = cast<Instruction>(V);
  1411. break;
  1412. }
  1413. case BitcodeConstant::ConstantStructOpcode:
  1414. case BitcodeConstant::ConstantArrayOpcode: {
  1415. Value *V = PoisonValue::get(BC->getType());
  1416. for (auto Pair : enumerate(Ops))
  1417. V = InsertValueInst::Create(V, Pair.value(), Pair.index(),
  1418. "constexpr.ins", InsertBB);
  1419. I = cast<Instruction>(V);
  1420. break;
  1421. }
  1422. case Instruction::ICmp:
  1423. case Instruction::FCmp:
  1424. I = CmpInst::Create((Instruction::OtherOps)BC->Opcode,
  1425. (CmpInst::Predicate)BC->Flags, Ops[0], Ops[1],
  1426. "constexpr", InsertBB);
  1427. break;
  1428. case Instruction::GetElementPtr:
  1429. I = GetElementPtrInst::Create(BC->SrcElemTy, Ops[0],
  1430. ArrayRef(Ops).drop_front(), "constexpr",
  1431. InsertBB);
  1432. if (BC->Flags)
  1433. cast<GetElementPtrInst>(I)->setIsInBounds();
  1434. break;
  1435. case Instruction::Select:
  1436. I = SelectInst::Create(Ops[0], Ops[1], Ops[2], "constexpr", InsertBB);
  1437. break;
  1438. case Instruction::ExtractElement:
  1439. I = ExtractElementInst::Create(Ops[0], Ops[1], "constexpr", InsertBB);
  1440. break;
  1441. case Instruction::InsertElement:
  1442. I = InsertElementInst::Create(Ops[0], Ops[1], Ops[2], "constexpr",
  1443. InsertBB);
  1444. break;
  1445. case Instruction::ShuffleVector:
  1446. I = new ShuffleVectorInst(Ops[0], Ops[1], Ops[2], "constexpr",
  1447. InsertBB);
  1448. break;
  1449. default:
  1450. llvm_unreachable("Unhandled bitcode constant");
  1451. }
  1452. }
  1453. MaterializedValues.insert({ValID, I});
  1454. Worklist.pop_back();
  1455. }
  1456. return MaterializedValues[StartValID];
  1457. }
  1458. Expected<Constant *> BitcodeReader::getValueForInitializer(unsigned ID) {
  1459. Expected<Value *> MaybeV = materializeValue(ID, /* InsertBB */ nullptr);
  1460. if (!MaybeV)
  1461. return MaybeV.takeError();
  1462. // Result must be Constant if InsertBB is nullptr.
  1463. return cast<Constant>(MaybeV.get());
  1464. }
  1465. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
  1466. StringRef Name) {
  1467. auto *Ret = StructType::create(Context, Name);
  1468. IdentifiedStructTypes.push_back(Ret);
  1469. return Ret;
  1470. }
  1471. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
  1472. auto *Ret = StructType::create(Context);
  1473. IdentifiedStructTypes.push_back(Ret);
  1474. return Ret;
  1475. }
  1476. //===----------------------------------------------------------------------===//
  1477. // Functions for parsing blocks from the bitcode file
  1478. //===----------------------------------------------------------------------===//
  1479. static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
  1480. switch (Val) {
  1481. case Attribute::EndAttrKinds:
  1482. case Attribute::EmptyKey:
  1483. case Attribute::TombstoneKey:
  1484. llvm_unreachable("Synthetic enumerators which should never get here");
  1485. case Attribute::None: return 0;
  1486. case Attribute::ZExt: return 1 << 0;
  1487. case Attribute::SExt: return 1 << 1;
  1488. case Attribute::NoReturn: return 1 << 2;
  1489. case Attribute::InReg: return 1 << 3;
  1490. case Attribute::StructRet: return 1 << 4;
  1491. case Attribute::NoUnwind: return 1 << 5;
  1492. case Attribute::NoAlias: return 1 << 6;
  1493. case Attribute::ByVal: return 1 << 7;
  1494. case Attribute::Nest: return 1 << 8;
  1495. case Attribute::ReadNone: return 1 << 9;
  1496. case Attribute::ReadOnly: return 1 << 10;
  1497. case Attribute::NoInline: return 1 << 11;
  1498. case Attribute::AlwaysInline: return 1 << 12;
  1499. case Attribute::OptimizeForSize: return 1 << 13;
  1500. case Attribute::StackProtect: return 1 << 14;
  1501. case Attribute::StackProtectReq: return 1 << 15;
  1502. case Attribute::Alignment: return 31 << 16;
  1503. case Attribute::NoCapture: return 1 << 21;
  1504. case Attribute::NoRedZone: return 1 << 22;
  1505. case Attribute::NoImplicitFloat: return 1 << 23;
  1506. case Attribute::Naked: return 1 << 24;
  1507. case Attribute::InlineHint: return 1 << 25;
  1508. case Attribute::StackAlignment: return 7 << 26;
  1509. case Attribute::ReturnsTwice: return 1 << 29;
  1510. case Attribute::UWTable: return 1 << 30;
  1511. case Attribute::NonLazyBind: return 1U << 31;
  1512. case Attribute::SanitizeAddress: return 1ULL << 32;
  1513. case Attribute::MinSize: return 1ULL << 33;
  1514. case Attribute::NoDuplicate: return 1ULL << 34;
  1515. case Attribute::StackProtectStrong: return 1ULL << 35;
  1516. case Attribute::SanitizeThread: return 1ULL << 36;
  1517. case Attribute::SanitizeMemory: return 1ULL << 37;
  1518. case Attribute::NoBuiltin: return 1ULL << 38;
  1519. case Attribute::Returned: return 1ULL << 39;
  1520. case Attribute::Cold: return 1ULL << 40;
  1521. case Attribute::Builtin: return 1ULL << 41;
  1522. case Attribute::OptimizeNone: return 1ULL << 42;
  1523. case Attribute::InAlloca: return 1ULL << 43;
  1524. case Attribute::NonNull: return 1ULL << 44;
  1525. case Attribute::JumpTable: return 1ULL << 45;
  1526. case Attribute::Convergent: return 1ULL << 46;
  1527. case Attribute::SafeStack: return 1ULL << 47;
  1528. case Attribute::NoRecurse: return 1ULL << 48;
  1529. // 1ULL << 49 is InaccessibleMemOnly, which is upgraded separately.
  1530. // 1ULL << 50 is InaccessibleMemOrArgMemOnly, which is upgraded separately.
  1531. case Attribute::SwiftSelf: return 1ULL << 51;
  1532. case Attribute::SwiftError: return 1ULL << 52;
  1533. case Attribute::WriteOnly: return 1ULL << 53;
  1534. case Attribute::Speculatable: return 1ULL << 54;
  1535. case Attribute::StrictFP: return 1ULL << 55;
  1536. case Attribute::SanitizeHWAddress: return 1ULL << 56;
  1537. case Attribute::NoCfCheck: return 1ULL << 57;
  1538. case Attribute::OptForFuzzing: return 1ULL << 58;
  1539. case Attribute::ShadowCallStack: return 1ULL << 59;
  1540. case Attribute::SpeculativeLoadHardening:
  1541. return 1ULL << 60;
  1542. case Attribute::ImmArg:
  1543. return 1ULL << 61;
  1544. case Attribute::WillReturn:
  1545. return 1ULL << 62;
  1546. case Attribute::NoFree:
  1547. return 1ULL << 63;
  1548. default:
  1549. // Other attributes are not supported in the raw format,
  1550. // as we ran out of space.
  1551. return 0;
  1552. }
  1553. llvm_unreachable("Unsupported attribute type");
  1554. }
  1555. static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
  1556. if (!Val) return;
  1557. for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
  1558. I = Attribute::AttrKind(I + 1)) {
  1559. if (uint64_t A = (Val & getRawAttributeMask(I))) {
  1560. if (I == Attribute::Alignment)
  1561. B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
  1562. else if (I == Attribute::StackAlignment)
  1563. B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
  1564. else if (Attribute::isTypeAttrKind(I))
  1565. B.addTypeAttr(I, nullptr); // Type will be auto-upgraded.
  1566. else
  1567. B.addAttribute(I);
  1568. }
  1569. }
  1570. }
  1571. /// This fills an AttrBuilder object with the LLVM attributes that have
  1572. /// been decoded from the given integer. This function must stay in sync with
  1573. /// 'encodeLLVMAttributesForBitcode'.
  1574. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  1575. uint64_t EncodedAttrs,
  1576. uint64_t AttrIdx) {
  1577. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  1578. // the bits above 31 down by 11 bits.
  1579. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  1580. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  1581. "Alignment must be a power of two.");
  1582. if (Alignment)
  1583. B.addAlignmentAttr(Alignment);
  1584. uint64_t Attrs = ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  1585. (EncodedAttrs & 0xffff);
  1586. if (AttrIdx == AttributeList::FunctionIndex) {
  1587. // Upgrade old memory attributes.
  1588. MemoryEffects ME = MemoryEffects::unknown();
  1589. if (Attrs & (1ULL << 9)) {
  1590. // ReadNone
  1591. Attrs &= ~(1ULL << 9);
  1592. ME &= MemoryEffects::none();
  1593. }
  1594. if (Attrs & (1ULL << 10)) {
  1595. // ReadOnly
  1596. Attrs &= ~(1ULL << 10);
  1597. ME &= MemoryEffects::readOnly();
  1598. }
  1599. if (Attrs & (1ULL << 49)) {
  1600. // InaccessibleMemOnly
  1601. Attrs &= ~(1ULL << 49);
  1602. ME &= MemoryEffects::inaccessibleMemOnly();
  1603. }
  1604. if (Attrs & (1ULL << 50)) {
  1605. // InaccessibleMemOrArgMemOnly
  1606. Attrs &= ~(1ULL << 50);
  1607. ME &= MemoryEffects::inaccessibleOrArgMemOnly();
  1608. }
  1609. if (Attrs & (1ULL << 53)) {
  1610. // WriteOnly
  1611. Attrs &= ~(1ULL << 53);
  1612. ME &= MemoryEffects::writeOnly();
  1613. }
  1614. if (ME != MemoryEffects::unknown())
  1615. B.addMemoryAttr(ME);
  1616. }
  1617. addRawAttributeValue(B, Attrs);
  1618. }
  1619. Error BitcodeReader::parseAttributeBlock() {
  1620. if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  1621. return Err;
  1622. if (!MAttributes.empty())
  1623. return error("Invalid multiple blocks");
  1624. SmallVector<uint64_t, 64> Record;
  1625. SmallVector<AttributeList, 8> Attrs;
  1626. // Read all the records.
  1627. while (true) {
  1628. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  1629. if (!MaybeEntry)
  1630. return MaybeEntry.takeError();
  1631. BitstreamEntry Entry = MaybeEntry.get();
  1632. switch (Entry.Kind) {
  1633. case BitstreamEntry::SubBlock: // Handled for us already.
  1634. case BitstreamEntry::Error:
  1635. return error("Malformed block");
  1636. case BitstreamEntry::EndBlock:
  1637. return Error::success();
  1638. case BitstreamEntry::Record:
  1639. // The interesting case.
  1640. break;
  1641. }
  1642. // Read a record.
  1643. Record.clear();
  1644. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  1645. if (!MaybeRecord)
  1646. return MaybeRecord.takeError();
  1647. switch (MaybeRecord.get()) {
  1648. default: // Default behavior: ignore.
  1649. break;
  1650. case bitc::PARAMATTR_CODE_ENTRY_OLD: // ENTRY: [paramidx0, attr0, ...]
  1651. // Deprecated, but still needed to read old bitcode files.
  1652. if (Record.size() & 1)
  1653. return error("Invalid parameter attribute record");
  1654. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  1655. AttrBuilder B(Context);
  1656. decodeLLVMAttributesForBitcode(B, Record[i+1], Record[i]);
  1657. Attrs.push_back(AttributeList::get(Context, Record[i], B));
  1658. }
  1659. MAttributes.push_back(AttributeList::get(Context, Attrs));
  1660. Attrs.clear();
  1661. break;
  1662. case bitc::PARAMATTR_CODE_ENTRY: // ENTRY: [attrgrp0, attrgrp1, ...]
  1663. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  1664. Attrs.push_back(MAttributeGroups[Record[i]]);
  1665. MAttributes.push_back(AttributeList::get(Context, Attrs));
  1666. Attrs.clear();
  1667. break;
  1668. }
  1669. }
  1670. }
  1671. // Returns Attribute::None on unrecognized codes.
  1672. static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
  1673. switch (Code) {
  1674. default:
  1675. return Attribute::None;
  1676. case bitc::ATTR_KIND_ALIGNMENT:
  1677. return Attribute::Alignment;
  1678. case bitc::ATTR_KIND_ALWAYS_INLINE:
  1679. return Attribute::AlwaysInline;
  1680. case bitc::ATTR_KIND_BUILTIN:
  1681. return Attribute::Builtin;
  1682. case bitc::ATTR_KIND_BY_VAL:
  1683. return Attribute::ByVal;
  1684. case bitc::ATTR_KIND_IN_ALLOCA:
  1685. return Attribute::InAlloca;
  1686. case bitc::ATTR_KIND_COLD:
  1687. return Attribute::Cold;
  1688. case bitc::ATTR_KIND_CONVERGENT:
  1689. return Attribute::Convergent;
  1690. case bitc::ATTR_KIND_DISABLE_SANITIZER_INSTRUMENTATION:
  1691. return Attribute::DisableSanitizerInstrumentation;
  1692. case bitc::ATTR_KIND_ELEMENTTYPE:
  1693. return Attribute::ElementType;
  1694. case bitc::ATTR_KIND_FNRETTHUNK_EXTERN:
  1695. return Attribute::FnRetThunkExtern;
  1696. case bitc::ATTR_KIND_INLINE_HINT:
  1697. return Attribute::InlineHint;
  1698. case bitc::ATTR_KIND_IN_REG:
  1699. return Attribute::InReg;
  1700. case bitc::ATTR_KIND_JUMP_TABLE:
  1701. return Attribute::JumpTable;
  1702. case bitc::ATTR_KIND_MEMORY:
  1703. return Attribute::Memory;
  1704. case bitc::ATTR_KIND_MIN_SIZE:
  1705. return Attribute::MinSize;
  1706. case bitc::ATTR_KIND_NAKED:
  1707. return Attribute::Naked;
  1708. case bitc::ATTR_KIND_NEST:
  1709. return Attribute::Nest;
  1710. case bitc::ATTR_KIND_NO_ALIAS:
  1711. return Attribute::NoAlias;
  1712. case bitc::ATTR_KIND_NO_BUILTIN:
  1713. return Attribute::NoBuiltin;
  1714. case bitc::ATTR_KIND_NO_CALLBACK:
  1715. return Attribute::NoCallback;
  1716. case bitc::ATTR_KIND_NO_CAPTURE:
  1717. return Attribute::NoCapture;
  1718. case bitc::ATTR_KIND_NO_DUPLICATE:
  1719. return Attribute::NoDuplicate;
  1720. case bitc::ATTR_KIND_NOFREE:
  1721. return Attribute::NoFree;
  1722. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  1723. return Attribute::NoImplicitFloat;
  1724. case bitc::ATTR_KIND_NO_INLINE:
  1725. return Attribute::NoInline;
  1726. case bitc::ATTR_KIND_NO_RECURSE:
  1727. return Attribute::NoRecurse;
  1728. case bitc::ATTR_KIND_NO_MERGE:
  1729. return Attribute::NoMerge;
  1730. case bitc::ATTR_KIND_NON_LAZY_BIND:
  1731. return Attribute::NonLazyBind;
  1732. case bitc::ATTR_KIND_NON_NULL:
  1733. return Attribute::NonNull;
  1734. case bitc::ATTR_KIND_DEREFERENCEABLE:
  1735. return Attribute::Dereferenceable;
  1736. case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
  1737. return Attribute::DereferenceableOrNull;
  1738. case bitc::ATTR_KIND_ALLOC_ALIGN:
  1739. return Attribute::AllocAlign;
  1740. case bitc::ATTR_KIND_ALLOC_KIND:
  1741. return Attribute::AllocKind;
  1742. case bitc::ATTR_KIND_ALLOC_SIZE:
  1743. return Attribute::AllocSize;
  1744. case bitc::ATTR_KIND_ALLOCATED_POINTER:
  1745. return Attribute::AllocatedPointer;
  1746. case bitc::ATTR_KIND_NO_RED_ZONE:
  1747. return Attribute::NoRedZone;
  1748. case bitc::ATTR_KIND_NO_RETURN:
  1749. return Attribute::NoReturn;
  1750. case bitc::ATTR_KIND_NOSYNC:
  1751. return Attribute::NoSync;
  1752. case bitc::ATTR_KIND_NOCF_CHECK:
  1753. return Attribute::NoCfCheck;
  1754. case bitc::ATTR_KIND_NO_PROFILE:
  1755. return Attribute::NoProfile;
  1756. case bitc::ATTR_KIND_SKIP_PROFILE:
  1757. return Attribute::SkipProfile;
  1758. case bitc::ATTR_KIND_NO_UNWIND:
  1759. return Attribute::NoUnwind;
  1760. case bitc::ATTR_KIND_NO_SANITIZE_BOUNDS:
  1761. return Attribute::NoSanitizeBounds;
  1762. case bitc::ATTR_KIND_NO_SANITIZE_COVERAGE:
  1763. return Attribute::NoSanitizeCoverage;
  1764. case bitc::ATTR_KIND_NULL_POINTER_IS_VALID:
  1765. return Attribute::NullPointerIsValid;
  1766. case bitc::ATTR_KIND_OPT_FOR_FUZZING:
  1767. return Attribute::OptForFuzzing;
  1768. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  1769. return Attribute::OptimizeForSize;
  1770. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  1771. return Attribute::OptimizeNone;
  1772. case bitc::ATTR_KIND_READ_NONE:
  1773. return Attribute::ReadNone;
  1774. case bitc::ATTR_KIND_READ_ONLY:
  1775. return Attribute::ReadOnly;
  1776. case bitc::ATTR_KIND_RETURNED:
  1777. return Attribute::Returned;
  1778. case bitc::ATTR_KIND_RETURNS_TWICE:
  1779. return Attribute::ReturnsTwice;
  1780. case bitc::ATTR_KIND_S_EXT:
  1781. return Attribute::SExt;
  1782. case bitc::ATTR_KIND_SPECULATABLE:
  1783. return Attribute::Speculatable;
  1784. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  1785. return Attribute::StackAlignment;
  1786. case bitc::ATTR_KIND_STACK_PROTECT:
  1787. return Attribute::StackProtect;
  1788. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  1789. return Attribute::StackProtectReq;
  1790. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  1791. return Attribute::StackProtectStrong;
  1792. case bitc::ATTR_KIND_SAFESTACK:
  1793. return Attribute::SafeStack;
  1794. case bitc::ATTR_KIND_SHADOWCALLSTACK:
  1795. return Attribute::ShadowCallStack;
  1796. case bitc::ATTR_KIND_STRICT_FP:
  1797. return Attribute::StrictFP;
  1798. case bitc::ATTR_KIND_STRUCT_RET:
  1799. return Attribute::StructRet;
  1800. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  1801. return Attribute::SanitizeAddress;
  1802. case bitc::ATTR_KIND_SANITIZE_HWADDRESS:
  1803. return Attribute::SanitizeHWAddress;
  1804. case bitc::ATTR_KIND_SANITIZE_THREAD:
  1805. return Attribute::SanitizeThread;
  1806. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  1807. return Attribute::SanitizeMemory;
  1808. case bitc::ATTR_KIND_SPECULATIVE_LOAD_HARDENING:
  1809. return Attribute::SpeculativeLoadHardening;
  1810. case bitc::ATTR_KIND_SWIFT_ERROR:
  1811. return Attribute::SwiftError;
  1812. case bitc::ATTR_KIND_SWIFT_SELF:
  1813. return Attribute::SwiftSelf;
  1814. case bitc::ATTR_KIND_SWIFT_ASYNC:
  1815. return Attribute::SwiftAsync;
  1816. case bitc::ATTR_KIND_UW_TABLE:
  1817. return Attribute::UWTable;
  1818. case bitc::ATTR_KIND_VSCALE_RANGE:
  1819. return Attribute::VScaleRange;
  1820. case bitc::ATTR_KIND_WILLRETURN:
  1821. return Attribute::WillReturn;
  1822. case bitc::ATTR_KIND_WRITEONLY:
  1823. return Attribute::WriteOnly;
  1824. case bitc::ATTR_KIND_Z_EXT:
  1825. return Attribute::ZExt;
  1826. case bitc::ATTR_KIND_IMMARG:
  1827. return Attribute::ImmArg;
  1828. case bitc::ATTR_KIND_SANITIZE_MEMTAG:
  1829. return Attribute::SanitizeMemTag;
  1830. case bitc::ATTR_KIND_PREALLOCATED:
  1831. return Attribute::Preallocated;
  1832. case bitc::ATTR_KIND_NOUNDEF:
  1833. return Attribute::NoUndef;
  1834. case bitc::ATTR_KIND_BYREF:
  1835. return Attribute::ByRef;
  1836. case bitc::ATTR_KIND_MUSTPROGRESS:
  1837. return Attribute::MustProgress;
  1838. case bitc::ATTR_KIND_HOT:
  1839. return Attribute::Hot;
  1840. case bitc::ATTR_KIND_PRESPLIT_COROUTINE:
  1841. return Attribute::PresplitCoroutine;
  1842. }
  1843. }
  1844. Error BitcodeReader::parseAlignmentValue(uint64_t Exponent,
  1845. MaybeAlign &Alignment) {
  1846. // Note: Alignment in bitcode files is incremented by 1, so that zero
  1847. // can be used for default alignment.
  1848. if (Exponent > Value::MaxAlignmentExponent + 1)
  1849. return error("Invalid alignment value");
  1850. Alignment = decodeMaybeAlign(Exponent);
  1851. return Error::success();
  1852. }
  1853. Error BitcodeReader::parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind) {
  1854. *Kind = getAttrFromCode(Code);
  1855. if (*Kind == Attribute::None)
  1856. return error("Unknown attribute kind (" + Twine(Code) + ")");
  1857. return Error::success();
  1858. }
  1859. static bool upgradeOldMemoryAttribute(MemoryEffects &ME, uint64_t EncodedKind) {
  1860. switch (EncodedKind) {
  1861. case bitc::ATTR_KIND_READ_NONE:
  1862. ME &= MemoryEffects::none();
  1863. return true;
  1864. case bitc::ATTR_KIND_READ_ONLY:
  1865. ME &= MemoryEffects::readOnly();
  1866. return true;
  1867. case bitc::ATTR_KIND_WRITEONLY:
  1868. ME &= MemoryEffects::writeOnly();
  1869. return true;
  1870. case bitc::ATTR_KIND_ARGMEMONLY:
  1871. ME &= MemoryEffects::argMemOnly();
  1872. return true;
  1873. case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
  1874. ME &= MemoryEffects::inaccessibleMemOnly();
  1875. return true;
  1876. case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
  1877. ME &= MemoryEffects::inaccessibleOrArgMemOnly();
  1878. return true;
  1879. default:
  1880. return false;
  1881. }
  1882. }
  1883. Error BitcodeReader::parseAttributeGroupBlock() {
  1884. if (Error Err = Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  1885. return Err;
  1886. if (!MAttributeGroups.empty())
  1887. return error("Invalid multiple blocks");
  1888. SmallVector<uint64_t, 64> Record;
  1889. // Read all the records.
  1890. while (true) {
  1891. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  1892. if (!MaybeEntry)
  1893. return MaybeEntry.takeError();
  1894. BitstreamEntry Entry = MaybeEntry.get();
  1895. switch (Entry.Kind) {
  1896. case BitstreamEntry::SubBlock: // Handled for us already.
  1897. case BitstreamEntry::Error:
  1898. return error("Malformed block");
  1899. case BitstreamEntry::EndBlock:
  1900. return Error::success();
  1901. case BitstreamEntry::Record:
  1902. // The interesting case.
  1903. break;
  1904. }
  1905. // Read a record.
  1906. Record.clear();
  1907. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  1908. if (!MaybeRecord)
  1909. return MaybeRecord.takeError();
  1910. switch (MaybeRecord.get()) {
  1911. default: // Default behavior: ignore.
  1912. break;
  1913. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  1914. if (Record.size() < 3)
  1915. return error("Invalid grp record");
  1916. uint64_t GrpID = Record[0];
  1917. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  1918. AttrBuilder B(Context);
  1919. MemoryEffects ME = MemoryEffects::unknown();
  1920. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1921. if (Record[i] == 0) { // Enum attribute
  1922. Attribute::AttrKind Kind;
  1923. uint64_t EncodedKind = Record[++i];
  1924. if (Idx == AttributeList::FunctionIndex &&
  1925. upgradeOldMemoryAttribute(ME, EncodedKind))
  1926. continue;
  1927. if (Error Err = parseAttrKind(EncodedKind, &Kind))
  1928. return Err;
  1929. // Upgrade old-style byval attribute to one with a type, even if it's
  1930. // nullptr. We will have to insert the real type when we associate
  1931. // this AttributeList with a function.
  1932. if (Kind == Attribute::ByVal)
  1933. B.addByValAttr(nullptr);
  1934. else if (Kind == Attribute::StructRet)
  1935. B.addStructRetAttr(nullptr);
  1936. else if (Kind == Attribute::InAlloca)
  1937. B.addInAllocaAttr(nullptr);
  1938. else if (Kind == Attribute::UWTable)
  1939. B.addUWTableAttr(UWTableKind::Default);
  1940. else if (Attribute::isEnumAttrKind(Kind))
  1941. B.addAttribute(Kind);
  1942. else
  1943. return error("Not an enum attribute");
  1944. } else if (Record[i] == 1) { // Integer attribute
  1945. Attribute::AttrKind Kind;
  1946. if (Error Err = parseAttrKind(Record[++i], &Kind))
  1947. return Err;
  1948. if (!Attribute::isIntAttrKind(Kind))
  1949. return error("Not an int attribute");
  1950. if (Kind == Attribute::Alignment)
  1951. B.addAlignmentAttr(Record[++i]);
  1952. else if (Kind == Attribute::StackAlignment)
  1953. B.addStackAlignmentAttr(Record[++i]);
  1954. else if (Kind == Attribute::Dereferenceable)
  1955. B.addDereferenceableAttr(Record[++i]);
  1956. else if (Kind == Attribute::DereferenceableOrNull)
  1957. B.addDereferenceableOrNullAttr(Record[++i]);
  1958. else if (Kind == Attribute::AllocSize)
  1959. B.addAllocSizeAttrFromRawRepr(Record[++i]);
  1960. else if (Kind == Attribute::VScaleRange)
  1961. B.addVScaleRangeAttrFromRawRepr(Record[++i]);
  1962. else if (Kind == Attribute::UWTable)
  1963. B.addUWTableAttr(UWTableKind(Record[++i]));
  1964. else if (Kind == Attribute::AllocKind)
  1965. B.addAllocKindAttr(static_cast<AllocFnKind>(Record[++i]));
  1966. else if (Kind == Attribute::Memory)
  1967. B.addMemoryAttr(MemoryEffects::createFromIntValue(Record[++i]));
  1968. } else if (Record[i] == 3 || Record[i] == 4) { // String attribute
  1969. bool HasValue = (Record[i++] == 4);
  1970. SmallString<64> KindStr;
  1971. SmallString<64> ValStr;
  1972. while (Record[i] != 0 && i != e)
  1973. KindStr += Record[i++];
  1974. assert(Record[i] == 0 && "Kind string not null terminated");
  1975. if (HasValue) {
  1976. // Has a value associated with it.
  1977. ++i; // Skip the '0' that terminates the "kind" string.
  1978. while (Record[i] != 0 && i != e)
  1979. ValStr += Record[i++];
  1980. assert(Record[i] == 0 && "Value string not null terminated");
  1981. }
  1982. B.addAttribute(KindStr.str(), ValStr.str());
  1983. } else if (Record[i] == 5 || Record[i] == 6) {
  1984. bool HasType = Record[i] == 6;
  1985. Attribute::AttrKind Kind;
  1986. if (Error Err = parseAttrKind(Record[++i], &Kind))
  1987. return Err;
  1988. if (!Attribute::isTypeAttrKind(Kind))
  1989. return error("Not a type attribute");
  1990. B.addTypeAttr(Kind, HasType ? getTypeByID(Record[++i]) : nullptr);
  1991. } else {
  1992. return error("Invalid attribute group entry");
  1993. }
  1994. }
  1995. if (ME != MemoryEffects::unknown())
  1996. B.addMemoryAttr(ME);
  1997. UpgradeAttributes(B);
  1998. MAttributeGroups[GrpID] = AttributeList::get(Context, Idx, B);
  1999. break;
  2000. }
  2001. }
  2002. }
  2003. }
  2004. Error BitcodeReader::parseTypeTable() {
  2005. if (Error Err = Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  2006. return Err;
  2007. return parseTypeTableBody();
  2008. }
  2009. Error BitcodeReader::parseTypeTableBody() {
  2010. if (!TypeList.empty())
  2011. return error("Invalid multiple blocks");
  2012. SmallVector<uint64_t, 64> Record;
  2013. unsigned NumRecords = 0;
  2014. SmallString<64> TypeName;
  2015. // Read all the records for this type table.
  2016. while (true) {
  2017. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  2018. if (!MaybeEntry)
  2019. return MaybeEntry.takeError();
  2020. BitstreamEntry Entry = MaybeEntry.get();
  2021. switch (Entry.Kind) {
  2022. case BitstreamEntry::SubBlock: // Handled for us already.
  2023. case BitstreamEntry::Error:
  2024. return error("Malformed block");
  2025. case BitstreamEntry::EndBlock:
  2026. if (NumRecords != TypeList.size())
  2027. return error("Malformed block");
  2028. return Error::success();
  2029. case BitstreamEntry::Record:
  2030. // The interesting case.
  2031. break;
  2032. }
  2033. // Read a record.
  2034. Record.clear();
  2035. Type *ResultTy = nullptr;
  2036. SmallVector<unsigned> ContainedIDs;
  2037. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  2038. if (!MaybeRecord)
  2039. return MaybeRecord.takeError();
  2040. switch (MaybeRecord.get()) {
  2041. default:
  2042. return error("Invalid value");
  2043. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  2044. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  2045. // type list. This allows us to reserve space.
  2046. if (Record.empty())
  2047. return error("Invalid numentry record");
  2048. TypeList.resize(Record[0]);
  2049. continue;
  2050. case bitc::TYPE_CODE_VOID: // VOID
  2051. ResultTy = Type::getVoidTy(Context);
  2052. break;
  2053. case bitc::TYPE_CODE_HALF: // HALF
  2054. ResultTy = Type::getHalfTy(Context);
  2055. break;
  2056. case bitc::TYPE_CODE_BFLOAT: // BFLOAT
  2057. ResultTy = Type::getBFloatTy(Context);
  2058. break;
  2059. case bitc::TYPE_CODE_FLOAT: // FLOAT
  2060. ResultTy = Type::getFloatTy(Context);
  2061. break;
  2062. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  2063. ResultTy = Type::getDoubleTy(Context);
  2064. break;
  2065. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  2066. ResultTy = Type::getX86_FP80Ty(Context);
  2067. break;
  2068. case bitc::TYPE_CODE_FP128: // FP128
  2069. ResultTy = Type::getFP128Ty(Context);
  2070. break;
  2071. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  2072. ResultTy = Type::getPPC_FP128Ty(Context);
  2073. break;
  2074. case bitc::TYPE_CODE_LABEL: // LABEL
  2075. ResultTy = Type::getLabelTy(Context);
  2076. break;
  2077. case bitc::TYPE_CODE_METADATA: // METADATA
  2078. ResultTy = Type::getMetadataTy(Context);
  2079. break;
  2080. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  2081. ResultTy = Type::getX86_MMXTy(Context);
  2082. break;
  2083. case bitc::TYPE_CODE_X86_AMX: // X86_AMX
  2084. ResultTy = Type::getX86_AMXTy(Context);
  2085. break;
  2086. case bitc::TYPE_CODE_TOKEN: // TOKEN
  2087. ResultTy = Type::getTokenTy(Context);
  2088. break;
  2089. case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
  2090. if (Record.empty())
  2091. return error("Invalid integer record");
  2092. uint64_t NumBits = Record[0];
  2093. if (NumBits < IntegerType::MIN_INT_BITS ||
  2094. NumBits > IntegerType::MAX_INT_BITS)
  2095. return error("Bitwidth for integer type out of range");
  2096. ResultTy = IntegerType::get(Context, NumBits);
  2097. break;
  2098. }
  2099. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  2100. // [pointee type, address space]
  2101. if (Record.empty())
  2102. return error("Invalid pointer record");
  2103. unsigned AddressSpace = 0;
  2104. if (Record.size() == 2)
  2105. AddressSpace = Record[1];
  2106. ResultTy = getTypeByID(Record[0]);
  2107. if (!ResultTy ||
  2108. !PointerType::isValidElementType(ResultTy))
  2109. return error("Invalid type");
  2110. ContainedIDs.push_back(Record[0]);
  2111. ResultTy = PointerType::get(ResultTy, AddressSpace);
  2112. break;
  2113. }
  2114. case bitc::TYPE_CODE_OPAQUE_POINTER: { // OPAQUE_POINTER: [addrspace]
  2115. if (Record.size() != 1)
  2116. return error("Invalid opaque pointer record");
  2117. if (Context.supportsTypedPointers())
  2118. return error(
  2119. "Opaque pointers are only supported in -opaque-pointers mode");
  2120. unsigned AddressSpace = Record[0];
  2121. ResultTy = PointerType::get(Context, AddressSpace);
  2122. break;
  2123. }
  2124. case bitc::TYPE_CODE_FUNCTION_OLD: {
  2125. // Deprecated, but still needed to read old bitcode files.
  2126. // FUNCTION: [vararg, attrid, retty, paramty x N]
  2127. if (Record.size() < 3)
  2128. return error("Invalid function record");
  2129. SmallVector<Type*, 8> ArgTys;
  2130. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  2131. if (Type *T = getTypeByID(Record[i]))
  2132. ArgTys.push_back(T);
  2133. else
  2134. break;
  2135. }
  2136. ResultTy = getTypeByID(Record[2]);
  2137. if (!ResultTy || ArgTys.size() < Record.size()-3)
  2138. return error("Invalid type");
  2139. ContainedIDs.append(Record.begin() + 2, Record.end());
  2140. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  2141. break;
  2142. }
  2143. case bitc::TYPE_CODE_FUNCTION: {
  2144. // FUNCTION: [vararg, retty, paramty x N]
  2145. if (Record.size() < 2)
  2146. return error("Invalid function record");
  2147. SmallVector<Type*, 8> ArgTys;
  2148. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  2149. if (Type *T = getTypeByID(Record[i])) {
  2150. if (!FunctionType::isValidArgumentType(T))
  2151. return error("Invalid function argument type");
  2152. ArgTys.push_back(T);
  2153. }
  2154. else
  2155. break;
  2156. }
  2157. ResultTy = getTypeByID(Record[1]);
  2158. if (!ResultTy || ArgTys.size() < Record.size()-2)
  2159. return error("Invalid type");
  2160. ContainedIDs.append(Record.begin() + 1, Record.end());
  2161. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  2162. break;
  2163. }
  2164. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  2165. if (Record.empty())
  2166. return error("Invalid anon struct record");
  2167. SmallVector<Type*, 8> EltTys;
  2168. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  2169. if (Type *T = getTypeByID(Record[i]))
  2170. EltTys.push_back(T);
  2171. else
  2172. break;
  2173. }
  2174. if (EltTys.size() != Record.size()-1)
  2175. return error("Invalid type");
  2176. ContainedIDs.append(Record.begin() + 1, Record.end());
  2177. ResultTy = StructType::get(Context, EltTys, Record[0]);
  2178. break;
  2179. }
  2180. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  2181. if (convertToString(Record, 0, TypeName))
  2182. return error("Invalid struct name record");
  2183. continue;
  2184. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  2185. if (Record.empty())
  2186. return error("Invalid named struct record");
  2187. if (NumRecords >= TypeList.size())
  2188. return error("Invalid TYPE table");
  2189. // Check to see if this was forward referenced, if so fill in the temp.
  2190. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  2191. if (Res) {
  2192. Res->setName(TypeName);
  2193. TypeList[NumRecords] = nullptr;
  2194. } else // Otherwise, create a new struct.
  2195. Res = createIdentifiedStructType(Context, TypeName);
  2196. TypeName.clear();
  2197. SmallVector<Type*, 8> EltTys;
  2198. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  2199. if (Type *T = getTypeByID(Record[i]))
  2200. EltTys.push_back(T);
  2201. else
  2202. break;
  2203. }
  2204. if (EltTys.size() != Record.size()-1)
  2205. return error("Invalid named struct record");
  2206. Res->setBody(EltTys, Record[0]);
  2207. ContainedIDs.append(Record.begin() + 1, Record.end());
  2208. ResultTy = Res;
  2209. break;
  2210. }
  2211. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  2212. if (Record.size() != 1)
  2213. return error("Invalid opaque type record");
  2214. if (NumRecords >= TypeList.size())
  2215. return error("Invalid TYPE table");
  2216. // Check to see if this was forward referenced, if so fill in the temp.
  2217. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  2218. if (Res) {
  2219. Res->setName(TypeName);
  2220. TypeList[NumRecords] = nullptr;
  2221. } else // Otherwise, create a new struct with no body.
  2222. Res = createIdentifiedStructType(Context, TypeName);
  2223. TypeName.clear();
  2224. ResultTy = Res;
  2225. break;
  2226. }
  2227. case bitc::TYPE_CODE_TARGET_TYPE: { // TARGET_TYPE: [NumTy, Tys..., Ints...]
  2228. if (Record.size() < 1)
  2229. return error("Invalid target extension type record");
  2230. if (NumRecords >= TypeList.size())
  2231. return error("Invalid TYPE table");
  2232. if (Record[0] >= Record.size())
  2233. return error("Too many type parameters");
  2234. unsigned NumTys = Record[0];
  2235. SmallVector<Type *, 4> TypeParams;
  2236. SmallVector<unsigned, 8> IntParams;
  2237. for (unsigned i = 0; i < NumTys; i++) {
  2238. if (Type *T = getTypeByID(Record[i + 1]))
  2239. TypeParams.push_back(T);
  2240. else
  2241. return error("Invalid type");
  2242. }
  2243. for (unsigned i = NumTys + 1, e = Record.size(); i < e; i++) {
  2244. if (Record[i] > UINT_MAX)
  2245. return error("Integer parameter too large");
  2246. IntParams.push_back(Record[i]);
  2247. }
  2248. ResultTy = TargetExtType::get(Context, TypeName, TypeParams, IntParams);
  2249. TypeName.clear();
  2250. break;
  2251. }
  2252. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  2253. if (Record.size() < 2)
  2254. return error("Invalid array type record");
  2255. ResultTy = getTypeByID(Record[1]);
  2256. if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
  2257. return error("Invalid type");
  2258. ContainedIDs.push_back(Record[1]);
  2259. ResultTy = ArrayType::get(ResultTy, Record[0]);
  2260. break;
  2261. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty] or
  2262. // [numelts, eltty, scalable]
  2263. if (Record.size() < 2)
  2264. return error("Invalid vector type record");
  2265. if (Record[0] == 0)
  2266. return error("Invalid vector length");
  2267. ResultTy = getTypeByID(Record[1]);
  2268. if (!ResultTy || !VectorType::isValidElementType(ResultTy))
  2269. return error("Invalid type");
  2270. bool Scalable = Record.size() > 2 ? Record[2] : false;
  2271. ContainedIDs.push_back(Record[1]);
  2272. ResultTy = VectorType::get(ResultTy, Record[0], Scalable);
  2273. break;
  2274. }
  2275. if (NumRecords >= TypeList.size())
  2276. return error("Invalid TYPE table");
  2277. if (TypeList[NumRecords])
  2278. return error(
  2279. "Invalid TYPE table: Only named structs can be forward referenced");
  2280. assert(ResultTy && "Didn't read a type?");
  2281. TypeList[NumRecords] = ResultTy;
  2282. if (!ContainedIDs.empty())
  2283. ContainedTypeIDs[NumRecords] = std::move(ContainedIDs);
  2284. ++NumRecords;
  2285. }
  2286. }
  2287. Error BitcodeReader::parseOperandBundleTags() {
  2288. if (Error Err = Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
  2289. return Err;
  2290. if (!BundleTags.empty())
  2291. return error("Invalid multiple blocks");
  2292. SmallVector<uint64_t, 64> Record;
  2293. while (true) {
  2294. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  2295. if (!MaybeEntry)
  2296. return MaybeEntry.takeError();
  2297. BitstreamEntry Entry = MaybeEntry.get();
  2298. switch (Entry.Kind) {
  2299. case BitstreamEntry::SubBlock: // Handled for us already.
  2300. case BitstreamEntry::Error:
  2301. return error("Malformed block");
  2302. case BitstreamEntry::EndBlock:
  2303. return Error::success();
  2304. case BitstreamEntry::Record:
  2305. // The interesting case.
  2306. break;
  2307. }
  2308. // Tags are implicitly mapped to integers by their order.
  2309. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  2310. if (!MaybeRecord)
  2311. return MaybeRecord.takeError();
  2312. if (MaybeRecord.get() != bitc::OPERAND_BUNDLE_TAG)
  2313. return error("Invalid operand bundle record");
  2314. // OPERAND_BUNDLE_TAG: [strchr x N]
  2315. BundleTags.emplace_back();
  2316. if (convertToString(Record, 0, BundleTags.back()))
  2317. return error("Invalid operand bundle record");
  2318. Record.clear();
  2319. }
  2320. }
  2321. Error BitcodeReader::parseSyncScopeNames() {
  2322. if (Error Err = Stream.EnterSubBlock(bitc::SYNC_SCOPE_NAMES_BLOCK_ID))
  2323. return Err;
  2324. if (!SSIDs.empty())
  2325. return error("Invalid multiple synchronization scope names blocks");
  2326. SmallVector<uint64_t, 64> Record;
  2327. while (true) {
  2328. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  2329. if (!MaybeEntry)
  2330. return MaybeEntry.takeError();
  2331. BitstreamEntry Entry = MaybeEntry.get();
  2332. switch (Entry.Kind) {
  2333. case BitstreamEntry::SubBlock: // Handled for us already.
  2334. case BitstreamEntry::Error:
  2335. return error("Malformed block");
  2336. case BitstreamEntry::EndBlock:
  2337. if (SSIDs.empty())
  2338. return error("Invalid empty synchronization scope names block");
  2339. return Error::success();
  2340. case BitstreamEntry::Record:
  2341. // The interesting case.
  2342. break;
  2343. }
  2344. // Synchronization scope names are implicitly mapped to synchronization
  2345. // scope IDs by their order.
  2346. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  2347. if (!MaybeRecord)
  2348. return MaybeRecord.takeError();
  2349. if (MaybeRecord.get() != bitc::SYNC_SCOPE_NAME)
  2350. return error("Invalid sync scope record");
  2351. SmallString<16> SSN;
  2352. if (convertToString(Record, 0, SSN))
  2353. return error("Invalid sync scope record");
  2354. SSIDs.push_back(Context.getOrInsertSyncScopeID(SSN));
  2355. Record.clear();
  2356. }
  2357. }
  2358. /// Associate a value with its name from the given index in the provided record.
  2359. Expected<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
  2360. unsigned NameIndex, Triple &TT) {
  2361. SmallString<128> ValueName;
  2362. if (convertToString(Record, NameIndex, ValueName))
  2363. return error("Invalid record");
  2364. unsigned ValueID = Record[0];
  2365. if (ValueID >= ValueList.size() || !ValueList[ValueID])
  2366. return error("Invalid record");
  2367. Value *V = ValueList[ValueID];
  2368. StringRef NameStr(ValueName.data(), ValueName.size());
  2369. if (NameStr.find_first_of(0) != StringRef::npos)
  2370. return error("Invalid value name");
  2371. V->setName(NameStr);
  2372. auto *GO = dyn_cast<GlobalObject>(V);
  2373. if (GO && ImplicitComdatObjects.contains(GO) && TT.supportsCOMDAT())
  2374. GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
  2375. return V;
  2376. }
  2377. /// Helper to note and return the current location, and jump to the given
  2378. /// offset.
  2379. static Expected<uint64_t> jumpToValueSymbolTable(uint64_t Offset,
  2380. BitstreamCursor &Stream) {
  2381. // Save the current parsing location so we can jump back at the end
  2382. // of the VST read.
  2383. uint64_t CurrentBit = Stream.GetCurrentBitNo();
  2384. if (Error JumpFailed = Stream.JumpToBit(Offset * 32))
  2385. return std::move(JumpFailed);
  2386. Expected<BitstreamEntry> MaybeEntry = Stream.advance();
  2387. if (!MaybeEntry)
  2388. return MaybeEntry.takeError();
  2389. if (MaybeEntry.get().Kind != BitstreamEntry::SubBlock ||
  2390. MaybeEntry.get().ID != bitc::VALUE_SYMTAB_BLOCK_ID)
  2391. return error("Expected value symbol table subblock");
  2392. return CurrentBit;
  2393. }
  2394. void BitcodeReader::setDeferredFunctionInfo(unsigned FuncBitcodeOffsetDelta,
  2395. Function *F,
  2396. ArrayRef<uint64_t> Record) {
  2397. // Note that we subtract 1 here because the offset is relative to one word
  2398. // before the start of the identification or module block, which was
  2399. // historically always the start of the regular bitcode header.
  2400. uint64_t FuncWordOffset = Record[1] - 1;
  2401. uint64_t FuncBitOffset = FuncWordOffset * 32;
  2402. DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
  2403. // Set the LastFunctionBlockBit to point to the last function block.
  2404. // Later when parsing is resumed after function materialization,
  2405. // we can simply skip that last function block.
  2406. if (FuncBitOffset > LastFunctionBlockBit)
  2407. LastFunctionBlockBit = FuncBitOffset;
  2408. }
  2409. /// Read a new-style GlobalValue symbol table.
  2410. Error BitcodeReader::parseGlobalValueSymbolTable() {
  2411. unsigned FuncBitcodeOffsetDelta =
  2412. Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
  2413. if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  2414. return Err;
  2415. SmallVector<uint64_t, 64> Record;
  2416. while (true) {
  2417. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  2418. if (!MaybeEntry)
  2419. return MaybeEntry.takeError();
  2420. BitstreamEntry Entry = MaybeEntry.get();
  2421. switch (Entry.Kind) {
  2422. case BitstreamEntry::SubBlock:
  2423. case BitstreamEntry::Error:
  2424. return error("Malformed block");
  2425. case BitstreamEntry::EndBlock:
  2426. return Error::success();
  2427. case BitstreamEntry::Record:
  2428. break;
  2429. }
  2430. Record.clear();
  2431. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  2432. if (!MaybeRecord)
  2433. return MaybeRecord.takeError();
  2434. switch (MaybeRecord.get()) {
  2435. case bitc::VST_CODE_FNENTRY: { // [valueid, offset]
  2436. unsigned ValueID = Record[0];
  2437. if (ValueID >= ValueList.size() || !ValueList[ValueID])
  2438. return error("Invalid value reference in symbol table");
  2439. setDeferredFunctionInfo(FuncBitcodeOffsetDelta,
  2440. cast<Function>(ValueList[ValueID]), Record);
  2441. break;
  2442. }
  2443. }
  2444. }
  2445. }
  2446. /// Parse the value symbol table at either the current parsing location or
  2447. /// at the given bit offset if provided.
  2448. Error BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
  2449. uint64_t CurrentBit;
  2450. // Pass in the Offset to distinguish between calling for the module-level
  2451. // VST (where we want to jump to the VST offset) and the function-level
  2452. // VST (where we don't).
  2453. if (Offset > 0) {
  2454. Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
  2455. if (!MaybeCurrentBit)
  2456. return MaybeCurrentBit.takeError();
  2457. CurrentBit = MaybeCurrentBit.get();
  2458. // If this module uses a string table, read this as a module-level VST.
  2459. if (UseStrtab) {
  2460. if (Error Err = parseGlobalValueSymbolTable())
  2461. return Err;
  2462. if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
  2463. return JumpFailed;
  2464. return Error::success();
  2465. }
  2466. // Otherwise, the VST will be in a similar format to a function-level VST,
  2467. // and will contain symbol names.
  2468. }
  2469. // Compute the delta between the bitcode indices in the VST (the word offset
  2470. // to the word-aligned ENTER_SUBBLOCK for the function block, and that
  2471. // expected by the lazy reader. The reader's EnterSubBlock expects to have
  2472. // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
  2473. // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
  2474. // just before entering the VST subblock because: 1) the EnterSubBlock
  2475. // changes the AbbrevID width; 2) the VST block is nested within the same
  2476. // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
  2477. // AbbrevID width before calling EnterSubBlock; and 3) when we want to
  2478. // jump to the FUNCTION_BLOCK using this offset later, we don't want
  2479. // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
  2480. unsigned FuncBitcodeOffsetDelta =
  2481. Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
  2482. if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  2483. return Err;
  2484. SmallVector<uint64_t, 64> Record;
  2485. Triple TT(TheModule->getTargetTriple());
  2486. // Read all the records for this value table.
  2487. SmallString<128> ValueName;
  2488. while (true) {
  2489. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  2490. if (!MaybeEntry)
  2491. return MaybeEntry.takeError();
  2492. BitstreamEntry Entry = MaybeEntry.get();
  2493. switch (Entry.Kind) {
  2494. case BitstreamEntry::SubBlock: // Handled for us already.
  2495. case BitstreamEntry::Error:
  2496. return error("Malformed block");
  2497. case BitstreamEntry::EndBlock:
  2498. if (Offset > 0)
  2499. if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
  2500. return JumpFailed;
  2501. return Error::success();
  2502. case BitstreamEntry::Record:
  2503. // The interesting case.
  2504. break;
  2505. }
  2506. // Read a record.
  2507. Record.clear();
  2508. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  2509. if (!MaybeRecord)
  2510. return MaybeRecord.takeError();
  2511. switch (MaybeRecord.get()) {
  2512. default: // Default behavior: unknown type.
  2513. break;
  2514. case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
  2515. Expected<Value *> ValOrErr = recordValue(Record, 1, TT);
  2516. if (Error Err = ValOrErr.takeError())
  2517. return Err;
  2518. ValOrErr.get();
  2519. break;
  2520. }
  2521. case bitc::VST_CODE_FNENTRY: {
  2522. // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
  2523. Expected<Value *> ValOrErr = recordValue(Record, 2, TT);
  2524. if (Error Err = ValOrErr.takeError())
  2525. return Err;
  2526. Value *V = ValOrErr.get();
  2527. // Ignore function offsets emitted for aliases of functions in older
  2528. // versions of LLVM.
  2529. if (auto *F = dyn_cast<Function>(V))
  2530. setDeferredFunctionInfo(FuncBitcodeOffsetDelta, F, Record);
  2531. break;
  2532. }
  2533. case bitc::VST_CODE_BBENTRY: {
  2534. if (convertToString(Record, 1, ValueName))
  2535. return error("Invalid bbentry record");
  2536. BasicBlock *BB = getBasicBlock(Record[0]);
  2537. if (!BB)
  2538. return error("Invalid bbentry record");
  2539. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  2540. ValueName.clear();
  2541. break;
  2542. }
  2543. }
  2544. }
  2545. }
  2546. /// Decode a signed value stored with the sign bit in the LSB for dense VBR
  2547. /// encoding.
  2548. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  2549. if ((V & 1) == 0)
  2550. return V >> 1;
  2551. if (V != 1)
  2552. return -(V >> 1);
  2553. // There is no such thing as -0 with integers. "-0" really means MININT.
  2554. return 1ULL << 63;
  2555. }
  2556. /// Resolve all of the initializers for global values and aliases that we can.
  2557. Error BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
  2558. std::vector<std::pair<GlobalVariable *, unsigned>> GlobalInitWorklist;
  2559. std::vector<std::pair<GlobalValue *, unsigned>> IndirectSymbolInitWorklist;
  2560. std::vector<FunctionOperandInfo> FunctionOperandWorklist;
  2561. GlobalInitWorklist.swap(GlobalInits);
  2562. IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
  2563. FunctionOperandWorklist.swap(FunctionOperands);
  2564. while (!GlobalInitWorklist.empty()) {
  2565. unsigned ValID = GlobalInitWorklist.back().second;
  2566. if (ValID >= ValueList.size()) {
  2567. // Not ready to resolve this yet, it requires something later in the file.
  2568. GlobalInits.push_back(GlobalInitWorklist.back());
  2569. } else {
  2570. Expected<Constant *> MaybeC = getValueForInitializer(ValID);
  2571. if (!MaybeC)
  2572. return MaybeC.takeError();
  2573. GlobalInitWorklist.back().first->setInitializer(MaybeC.get());
  2574. }
  2575. GlobalInitWorklist.pop_back();
  2576. }
  2577. while (!IndirectSymbolInitWorklist.empty()) {
  2578. unsigned ValID = IndirectSymbolInitWorklist.back().second;
  2579. if (ValID >= ValueList.size()) {
  2580. IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
  2581. } else {
  2582. Expected<Constant *> MaybeC = getValueForInitializer(ValID);
  2583. if (!MaybeC)
  2584. return MaybeC.takeError();
  2585. Constant *C = MaybeC.get();
  2586. GlobalValue *GV = IndirectSymbolInitWorklist.back().first;
  2587. if (auto *GA = dyn_cast<GlobalAlias>(GV)) {
  2588. if (C->getType() != GV->getType())
  2589. return error("Alias and aliasee types don't match");
  2590. GA->setAliasee(C);
  2591. } else if (auto *GI = dyn_cast<GlobalIFunc>(GV)) {
  2592. Type *ResolverFTy =
  2593. GlobalIFunc::getResolverFunctionType(GI->getValueType());
  2594. // Transparently fix up the type for compatibility with older bitcode
  2595. GI->setResolver(ConstantExpr::getBitCast(
  2596. C, ResolverFTy->getPointerTo(GI->getAddressSpace())));
  2597. } else {
  2598. return error("Expected an alias or an ifunc");
  2599. }
  2600. }
  2601. IndirectSymbolInitWorklist.pop_back();
  2602. }
  2603. while (!FunctionOperandWorklist.empty()) {
  2604. FunctionOperandInfo &Info = FunctionOperandWorklist.back();
  2605. if (Info.PersonalityFn) {
  2606. unsigned ValID = Info.PersonalityFn - 1;
  2607. if (ValID < ValueList.size()) {
  2608. Expected<Constant *> MaybeC = getValueForInitializer(ValID);
  2609. if (!MaybeC)
  2610. return MaybeC.takeError();
  2611. Info.F->setPersonalityFn(MaybeC.get());
  2612. Info.PersonalityFn = 0;
  2613. }
  2614. }
  2615. if (Info.Prefix) {
  2616. unsigned ValID = Info.Prefix - 1;
  2617. if (ValID < ValueList.size()) {
  2618. Expected<Constant *> MaybeC = getValueForInitializer(ValID);
  2619. if (!MaybeC)
  2620. return MaybeC.takeError();
  2621. Info.F->setPrefixData(MaybeC.get());
  2622. Info.Prefix = 0;
  2623. }
  2624. }
  2625. if (Info.Prologue) {
  2626. unsigned ValID = Info.Prologue - 1;
  2627. if (ValID < ValueList.size()) {
  2628. Expected<Constant *> MaybeC = getValueForInitializer(ValID);
  2629. if (!MaybeC)
  2630. return MaybeC.takeError();
  2631. Info.F->setPrologueData(MaybeC.get());
  2632. Info.Prologue = 0;
  2633. }
  2634. }
  2635. if (Info.PersonalityFn || Info.Prefix || Info.Prologue)
  2636. FunctionOperands.push_back(Info);
  2637. FunctionOperandWorklist.pop_back();
  2638. }
  2639. return Error::success();
  2640. }
  2641. APInt llvm::readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  2642. SmallVector<uint64_t, 8> Words(Vals.size());
  2643. transform(Vals, Words.begin(),
  2644. BitcodeReader::decodeSignRotatedValue);
  2645. return APInt(TypeBits, Words);
  2646. }
  2647. Error BitcodeReader::parseConstants() {
  2648. if (Error Err = Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  2649. return Err;
  2650. SmallVector<uint64_t, 64> Record;
  2651. // Read all the records for this value table.
  2652. Type *CurTy = Type::getInt32Ty(Context);
  2653. unsigned Int32TyID = getVirtualTypeID(CurTy);
  2654. unsigned CurTyID = Int32TyID;
  2655. Type *CurElemTy = nullptr;
  2656. unsigned NextCstNo = ValueList.size();
  2657. while (true) {
  2658. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  2659. if (!MaybeEntry)
  2660. return MaybeEntry.takeError();
  2661. BitstreamEntry Entry = MaybeEntry.get();
  2662. switch (Entry.Kind) {
  2663. case BitstreamEntry::SubBlock: // Handled for us already.
  2664. case BitstreamEntry::Error:
  2665. return error("Malformed block");
  2666. case BitstreamEntry::EndBlock:
  2667. if (NextCstNo != ValueList.size())
  2668. return error("Invalid constant reference");
  2669. return Error::success();
  2670. case BitstreamEntry::Record:
  2671. // The interesting case.
  2672. break;
  2673. }
  2674. // Read a record.
  2675. Record.clear();
  2676. Type *VoidType = Type::getVoidTy(Context);
  2677. Value *V = nullptr;
  2678. Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
  2679. if (!MaybeBitCode)
  2680. return MaybeBitCode.takeError();
  2681. switch (unsigned BitCode = MaybeBitCode.get()) {
  2682. default: // Default behavior: unknown constant
  2683. case bitc::CST_CODE_UNDEF: // UNDEF
  2684. V = UndefValue::get(CurTy);
  2685. break;
  2686. case bitc::CST_CODE_POISON: // POISON
  2687. V = PoisonValue::get(CurTy);
  2688. break;
  2689. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  2690. if (Record.empty())
  2691. return error("Invalid settype record");
  2692. if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
  2693. return error("Invalid settype record");
  2694. if (TypeList[Record[0]] == VoidType)
  2695. return error("Invalid constant type");
  2696. CurTyID = Record[0];
  2697. CurTy = TypeList[CurTyID];
  2698. CurElemTy = getPtrElementTypeByID(CurTyID);
  2699. continue; // Skip the ValueList manipulation.
  2700. case bitc::CST_CODE_NULL: // NULL
  2701. if (CurTy->isVoidTy() || CurTy->isFunctionTy() || CurTy->isLabelTy())
  2702. return error("Invalid type for a constant null value");
  2703. if (auto *TETy = dyn_cast<TargetExtType>(CurTy))
  2704. if (!TETy->hasProperty(TargetExtType::HasZeroInit))
  2705. return error("Invalid type for a constant null value");
  2706. V = Constant::getNullValue(CurTy);
  2707. break;
  2708. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  2709. if (!CurTy->isIntegerTy() || Record.empty())
  2710. return error("Invalid integer const record");
  2711. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  2712. break;
  2713. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  2714. if (!CurTy->isIntegerTy() || Record.empty())
  2715. return error("Invalid wide integer const record");
  2716. APInt VInt =
  2717. readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
  2718. V = ConstantInt::get(Context, VInt);
  2719. break;
  2720. }
  2721. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  2722. if (Record.empty())
  2723. return error("Invalid float const record");
  2724. if (CurTy->isHalfTy())
  2725. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf(),
  2726. APInt(16, (uint16_t)Record[0])));
  2727. else if (CurTy->isBFloatTy())
  2728. V = ConstantFP::get(Context, APFloat(APFloat::BFloat(),
  2729. APInt(16, (uint32_t)Record[0])));
  2730. else if (CurTy->isFloatTy())
  2731. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle(),
  2732. APInt(32, (uint32_t)Record[0])));
  2733. else if (CurTy->isDoubleTy())
  2734. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble(),
  2735. APInt(64, Record[0])));
  2736. else if (CurTy->isX86_FP80Ty()) {
  2737. // Bits are not stored the same way as a normal i80 APInt, compensate.
  2738. uint64_t Rearrange[2];
  2739. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  2740. Rearrange[1] = Record[0] >> 48;
  2741. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended(),
  2742. APInt(80, Rearrange)));
  2743. } else if (CurTy->isFP128Ty())
  2744. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad(),
  2745. APInt(128, Record)));
  2746. else if (CurTy->isPPC_FP128Ty())
  2747. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble(),
  2748. APInt(128, Record)));
  2749. else
  2750. V = UndefValue::get(CurTy);
  2751. break;
  2752. }
  2753. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  2754. if (Record.empty())
  2755. return error("Invalid aggregate record");
  2756. unsigned Size = Record.size();
  2757. SmallVector<unsigned, 16> Elts;
  2758. for (unsigned i = 0; i != Size; ++i)
  2759. Elts.push_back(Record[i]);
  2760. if (isa<StructType>(CurTy)) {
  2761. V = BitcodeConstant::create(
  2762. Alloc, CurTy, BitcodeConstant::ConstantStructOpcode, Elts);
  2763. } else if (isa<ArrayType>(CurTy)) {
  2764. V = BitcodeConstant::create(Alloc, CurTy,
  2765. BitcodeConstant::ConstantArrayOpcode, Elts);
  2766. } else if (isa<VectorType>(CurTy)) {
  2767. V = BitcodeConstant::create(
  2768. Alloc, CurTy, BitcodeConstant::ConstantVectorOpcode, Elts);
  2769. } else {
  2770. V = UndefValue::get(CurTy);
  2771. }
  2772. break;
  2773. }
  2774. case bitc::CST_CODE_STRING: // STRING: [values]
  2775. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  2776. if (Record.empty())
  2777. return error("Invalid string record");
  2778. SmallString<16> Elts(Record.begin(), Record.end());
  2779. V = ConstantDataArray::getString(Context, Elts,
  2780. BitCode == bitc::CST_CODE_CSTRING);
  2781. break;
  2782. }
  2783. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  2784. if (Record.empty())
  2785. return error("Invalid data record");
  2786. Type *EltTy;
  2787. if (auto *Array = dyn_cast<ArrayType>(CurTy))
  2788. EltTy = Array->getElementType();
  2789. else
  2790. EltTy = cast<VectorType>(CurTy)->getElementType();
  2791. if (EltTy->isIntegerTy(8)) {
  2792. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  2793. if (isa<VectorType>(CurTy))
  2794. V = ConstantDataVector::get(Context, Elts);
  2795. else
  2796. V = ConstantDataArray::get(Context, Elts);
  2797. } else if (EltTy->isIntegerTy(16)) {
  2798. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2799. if (isa<VectorType>(CurTy))
  2800. V = ConstantDataVector::get(Context, Elts);
  2801. else
  2802. V = ConstantDataArray::get(Context, Elts);
  2803. } else if (EltTy->isIntegerTy(32)) {
  2804. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2805. if (isa<VectorType>(CurTy))
  2806. V = ConstantDataVector::get(Context, Elts);
  2807. else
  2808. V = ConstantDataArray::get(Context, Elts);
  2809. } else if (EltTy->isIntegerTy(64)) {
  2810. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2811. if (isa<VectorType>(CurTy))
  2812. V = ConstantDataVector::get(Context, Elts);
  2813. else
  2814. V = ConstantDataArray::get(Context, Elts);
  2815. } else if (EltTy->isHalfTy()) {
  2816. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2817. if (isa<VectorType>(CurTy))
  2818. V = ConstantDataVector::getFP(EltTy, Elts);
  2819. else
  2820. V = ConstantDataArray::getFP(EltTy, Elts);
  2821. } else if (EltTy->isBFloatTy()) {
  2822. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2823. if (isa<VectorType>(CurTy))
  2824. V = ConstantDataVector::getFP(EltTy, Elts);
  2825. else
  2826. V = ConstantDataArray::getFP(EltTy, Elts);
  2827. } else if (EltTy->isFloatTy()) {
  2828. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2829. if (isa<VectorType>(CurTy))
  2830. V = ConstantDataVector::getFP(EltTy, Elts);
  2831. else
  2832. V = ConstantDataArray::getFP(EltTy, Elts);
  2833. } else if (EltTy->isDoubleTy()) {
  2834. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2835. if (isa<VectorType>(CurTy))
  2836. V = ConstantDataVector::getFP(EltTy, Elts);
  2837. else
  2838. V = ConstantDataArray::getFP(EltTy, Elts);
  2839. } else {
  2840. return error("Invalid type for value");
  2841. }
  2842. break;
  2843. }
  2844. case bitc::CST_CODE_CE_UNOP: { // CE_UNOP: [opcode, opval]
  2845. if (Record.size() < 2)
  2846. return error("Invalid unary op constexpr record");
  2847. int Opc = getDecodedUnaryOpcode(Record[0], CurTy);
  2848. if (Opc < 0) {
  2849. V = UndefValue::get(CurTy); // Unknown unop.
  2850. } else {
  2851. V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[1]);
  2852. }
  2853. break;
  2854. }
  2855. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  2856. if (Record.size() < 3)
  2857. return error("Invalid binary op constexpr record");
  2858. int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
  2859. if (Opc < 0) {
  2860. V = UndefValue::get(CurTy); // Unknown binop.
  2861. } else {
  2862. uint8_t Flags = 0;
  2863. if (Record.size() >= 4) {
  2864. if (Opc == Instruction::Add ||
  2865. Opc == Instruction::Sub ||
  2866. Opc == Instruction::Mul ||
  2867. Opc == Instruction::Shl) {
  2868. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2869. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2870. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2871. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2872. } else if (Opc == Instruction::SDiv ||
  2873. Opc == Instruction::UDiv ||
  2874. Opc == Instruction::LShr ||
  2875. Opc == Instruction::AShr) {
  2876. if (Record[3] & (1 << bitc::PEO_EXACT))
  2877. Flags |= SDivOperator::IsExact;
  2878. }
  2879. }
  2880. V = BitcodeConstant::create(Alloc, CurTy, {(uint8_t)Opc, Flags},
  2881. {(unsigned)Record[1], (unsigned)Record[2]});
  2882. }
  2883. break;
  2884. }
  2885. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  2886. if (Record.size() < 3)
  2887. return error("Invalid cast constexpr record");
  2888. int Opc = getDecodedCastOpcode(Record[0]);
  2889. if (Opc < 0) {
  2890. V = UndefValue::get(CurTy); // Unknown cast.
  2891. } else {
  2892. unsigned OpTyID = Record[1];
  2893. Type *OpTy = getTypeByID(OpTyID);
  2894. if (!OpTy)
  2895. return error("Invalid cast constexpr record");
  2896. V = BitcodeConstant::create(Alloc, CurTy, Opc, (unsigned)Record[2]);
  2897. }
  2898. break;
  2899. }
  2900. case bitc::CST_CODE_CE_INBOUNDS_GEP: // [ty, n x operands]
  2901. case bitc::CST_CODE_CE_GEP: // [ty, n x operands]
  2902. case bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX: { // [ty, flags, n x
  2903. // operands]
  2904. if (Record.size() < 2)
  2905. return error("Constant GEP record must have at least two elements");
  2906. unsigned OpNum = 0;
  2907. Type *PointeeType = nullptr;
  2908. if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX ||
  2909. Record.size() % 2)
  2910. PointeeType = getTypeByID(Record[OpNum++]);
  2911. bool InBounds = false;
  2912. std::optional<unsigned> InRangeIndex;
  2913. if (BitCode == bitc::CST_CODE_CE_GEP_WITH_INRANGE_INDEX) {
  2914. uint64_t Op = Record[OpNum++];
  2915. InBounds = Op & 1;
  2916. InRangeIndex = Op >> 1;
  2917. } else if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
  2918. InBounds = true;
  2919. SmallVector<unsigned, 16> Elts;
  2920. unsigned BaseTypeID = Record[OpNum];
  2921. while (OpNum != Record.size()) {
  2922. unsigned ElTyID = Record[OpNum++];
  2923. Type *ElTy = getTypeByID(ElTyID);
  2924. if (!ElTy)
  2925. return error("Invalid getelementptr constexpr record");
  2926. Elts.push_back(Record[OpNum++]);
  2927. }
  2928. if (Elts.size() < 1)
  2929. return error("Invalid gep with no operands");
  2930. Type *BaseType = getTypeByID(BaseTypeID);
  2931. if (isa<VectorType>(BaseType)) {
  2932. BaseTypeID = getContainedTypeID(BaseTypeID, 0);
  2933. BaseType = getTypeByID(BaseTypeID);
  2934. }
  2935. PointerType *OrigPtrTy = dyn_cast_or_null<PointerType>(BaseType);
  2936. if (!OrigPtrTy)
  2937. return error("GEP base operand must be pointer or vector of pointer");
  2938. if (!PointeeType) {
  2939. PointeeType = getPtrElementTypeByID(BaseTypeID);
  2940. if (!PointeeType)
  2941. return error("Missing element type for old-style constant GEP");
  2942. } else if (!OrigPtrTy->isOpaqueOrPointeeTypeMatches(PointeeType))
  2943. return error("Explicit gep operator type does not match pointee type "
  2944. "of pointer operand");
  2945. V = BitcodeConstant::create(Alloc, CurTy,
  2946. {Instruction::GetElementPtr, InBounds,
  2947. InRangeIndex.value_or(-1), PointeeType},
  2948. Elts);
  2949. break;
  2950. }
  2951. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  2952. if (Record.size() < 3)
  2953. return error("Invalid select constexpr record");
  2954. V = BitcodeConstant::create(
  2955. Alloc, CurTy, Instruction::Select,
  2956. {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
  2957. break;
  2958. }
  2959. case bitc::CST_CODE_CE_EXTRACTELT
  2960. : { // CE_EXTRACTELT: [opty, opval, opty, opval]
  2961. if (Record.size() < 3)
  2962. return error("Invalid extractelement constexpr record");
  2963. unsigned OpTyID = Record[0];
  2964. VectorType *OpTy =
  2965. dyn_cast_or_null<VectorType>(getTypeByID(OpTyID));
  2966. if (!OpTy)
  2967. return error("Invalid extractelement constexpr record");
  2968. unsigned IdxRecord;
  2969. if (Record.size() == 4) {
  2970. unsigned IdxTyID = Record[2];
  2971. Type *IdxTy = getTypeByID(IdxTyID);
  2972. if (!IdxTy)
  2973. return error("Invalid extractelement constexpr record");
  2974. IdxRecord = Record[3];
  2975. } else {
  2976. // Deprecated, but still needed to read old bitcode files.
  2977. IdxRecord = Record[2];
  2978. }
  2979. V = BitcodeConstant::create(Alloc, CurTy, Instruction::ExtractElement,
  2980. {(unsigned)Record[1], IdxRecord});
  2981. break;
  2982. }
  2983. case bitc::CST_CODE_CE_INSERTELT
  2984. : { // CE_INSERTELT: [opval, opval, opty, opval]
  2985. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2986. if (Record.size() < 3 || !OpTy)
  2987. return error("Invalid insertelement constexpr record");
  2988. unsigned IdxRecord;
  2989. if (Record.size() == 4) {
  2990. unsigned IdxTyID = Record[2];
  2991. Type *IdxTy = getTypeByID(IdxTyID);
  2992. if (!IdxTy)
  2993. return error("Invalid insertelement constexpr record");
  2994. IdxRecord = Record[3];
  2995. } else {
  2996. // Deprecated, but still needed to read old bitcode files.
  2997. IdxRecord = Record[2];
  2998. }
  2999. V = BitcodeConstant::create(
  3000. Alloc, CurTy, Instruction::InsertElement,
  3001. {(unsigned)Record[0], (unsigned)Record[1], IdxRecord});
  3002. break;
  3003. }
  3004. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  3005. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  3006. if (Record.size() < 3 || !OpTy)
  3007. return error("Invalid shufflevector constexpr record");
  3008. V = BitcodeConstant::create(
  3009. Alloc, CurTy, Instruction::ShuffleVector,
  3010. {(unsigned)Record[0], (unsigned)Record[1], (unsigned)Record[2]});
  3011. break;
  3012. }
  3013. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  3014. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  3015. VectorType *OpTy =
  3016. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  3017. if (Record.size() < 4 || !RTy || !OpTy)
  3018. return error("Invalid shufflevector constexpr record");
  3019. V = BitcodeConstant::create(
  3020. Alloc, CurTy, Instruction::ShuffleVector,
  3021. {(unsigned)Record[1], (unsigned)Record[2], (unsigned)Record[3]});
  3022. break;
  3023. }
  3024. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  3025. if (Record.size() < 4)
  3026. return error("Invalid cmp constexpt record");
  3027. unsigned OpTyID = Record[0];
  3028. Type *OpTy = getTypeByID(OpTyID);
  3029. if (!OpTy)
  3030. return error("Invalid cmp constexpr record");
  3031. V = BitcodeConstant::create(
  3032. Alloc, CurTy,
  3033. {(uint8_t)(OpTy->isFPOrFPVectorTy() ? Instruction::FCmp
  3034. : Instruction::ICmp),
  3035. (uint8_t)Record[3]},
  3036. {(unsigned)Record[1], (unsigned)Record[2]});
  3037. break;
  3038. }
  3039. // This maintains backward compatibility, pre-asm dialect keywords.
  3040. // Deprecated, but still needed to read old bitcode files.
  3041. case bitc::CST_CODE_INLINEASM_OLD: {
  3042. if (Record.size() < 2)
  3043. return error("Invalid inlineasm record");
  3044. std::string AsmStr, ConstrStr;
  3045. bool HasSideEffects = Record[0] & 1;
  3046. bool IsAlignStack = Record[0] >> 1;
  3047. unsigned AsmStrSize = Record[1];
  3048. if (2+AsmStrSize >= Record.size())
  3049. return error("Invalid inlineasm record");
  3050. unsigned ConstStrSize = Record[2+AsmStrSize];
  3051. if (3+AsmStrSize+ConstStrSize > Record.size())
  3052. return error("Invalid inlineasm record");
  3053. for (unsigned i = 0; i != AsmStrSize; ++i)
  3054. AsmStr += (char)Record[2+i];
  3055. for (unsigned i = 0; i != ConstStrSize; ++i)
  3056. ConstrStr += (char)Record[3+AsmStrSize+i];
  3057. UpgradeInlineAsmString(&AsmStr);
  3058. if (!CurElemTy)
  3059. return error("Missing element type for old-style inlineasm");
  3060. V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
  3061. HasSideEffects, IsAlignStack);
  3062. break;
  3063. }
  3064. // This version adds support for the asm dialect keywords (e.g.,
  3065. // inteldialect).
  3066. case bitc::CST_CODE_INLINEASM_OLD2: {
  3067. if (Record.size() < 2)
  3068. return error("Invalid inlineasm record");
  3069. std::string AsmStr, ConstrStr;
  3070. bool HasSideEffects = Record[0] & 1;
  3071. bool IsAlignStack = (Record[0] >> 1) & 1;
  3072. unsigned AsmDialect = Record[0] >> 2;
  3073. unsigned AsmStrSize = Record[1];
  3074. if (2+AsmStrSize >= Record.size())
  3075. return error("Invalid inlineasm record");
  3076. unsigned ConstStrSize = Record[2+AsmStrSize];
  3077. if (3+AsmStrSize+ConstStrSize > Record.size())
  3078. return error("Invalid inlineasm record");
  3079. for (unsigned i = 0; i != AsmStrSize; ++i)
  3080. AsmStr += (char)Record[2+i];
  3081. for (unsigned i = 0; i != ConstStrSize; ++i)
  3082. ConstrStr += (char)Record[3+AsmStrSize+i];
  3083. UpgradeInlineAsmString(&AsmStr);
  3084. if (!CurElemTy)
  3085. return error("Missing element type for old-style inlineasm");
  3086. V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
  3087. HasSideEffects, IsAlignStack,
  3088. InlineAsm::AsmDialect(AsmDialect));
  3089. break;
  3090. }
  3091. // This version adds support for the unwind keyword.
  3092. case bitc::CST_CODE_INLINEASM_OLD3: {
  3093. if (Record.size() < 2)
  3094. return error("Invalid inlineasm record");
  3095. unsigned OpNum = 0;
  3096. std::string AsmStr, ConstrStr;
  3097. bool HasSideEffects = Record[OpNum] & 1;
  3098. bool IsAlignStack = (Record[OpNum] >> 1) & 1;
  3099. unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
  3100. bool CanThrow = (Record[OpNum] >> 3) & 1;
  3101. ++OpNum;
  3102. unsigned AsmStrSize = Record[OpNum];
  3103. ++OpNum;
  3104. if (OpNum + AsmStrSize >= Record.size())
  3105. return error("Invalid inlineasm record");
  3106. unsigned ConstStrSize = Record[OpNum + AsmStrSize];
  3107. if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
  3108. return error("Invalid inlineasm record");
  3109. for (unsigned i = 0; i != AsmStrSize; ++i)
  3110. AsmStr += (char)Record[OpNum + i];
  3111. ++OpNum;
  3112. for (unsigned i = 0; i != ConstStrSize; ++i)
  3113. ConstrStr += (char)Record[OpNum + AsmStrSize + i];
  3114. UpgradeInlineAsmString(&AsmStr);
  3115. if (!CurElemTy)
  3116. return error("Missing element type for old-style inlineasm");
  3117. V = InlineAsm::get(cast<FunctionType>(CurElemTy), AsmStr, ConstrStr,
  3118. HasSideEffects, IsAlignStack,
  3119. InlineAsm::AsmDialect(AsmDialect), CanThrow);
  3120. break;
  3121. }
  3122. // This version adds explicit function type.
  3123. case bitc::CST_CODE_INLINEASM: {
  3124. if (Record.size() < 3)
  3125. return error("Invalid inlineasm record");
  3126. unsigned OpNum = 0;
  3127. auto *FnTy = dyn_cast_or_null<FunctionType>(getTypeByID(Record[OpNum]));
  3128. ++OpNum;
  3129. if (!FnTy)
  3130. return error("Invalid inlineasm record");
  3131. std::string AsmStr, ConstrStr;
  3132. bool HasSideEffects = Record[OpNum] & 1;
  3133. bool IsAlignStack = (Record[OpNum] >> 1) & 1;
  3134. unsigned AsmDialect = (Record[OpNum] >> 2) & 1;
  3135. bool CanThrow = (Record[OpNum] >> 3) & 1;
  3136. ++OpNum;
  3137. unsigned AsmStrSize = Record[OpNum];
  3138. ++OpNum;
  3139. if (OpNum + AsmStrSize >= Record.size())
  3140. return error("Invalid inlineasm record");
  3141. unsigned ConstStrSize = Record[OpNum + AsmStrSize];
  3142. if (OpNum + 1 + AsmStrSize + ConstStrSize > Record.size())
  3143. return error("Invalid inlineasm record");
  3144. for (unsigned i = 0; i != AsmStrSize; ++i)
  3145. AsmStr += (char)Record[OpNum + i];
  3146. ++OpNum;
  3147. for (unsigned i = 0; i != ConstStrSize; ++i)
  3148. ConstrStr += (char)Record[OpNum + AsmStrSize + i];
  3149. UpgradeInlineAsmString(&AsmStr);
  3150. V = InlineAsm::get(FnTy, AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  3151. InlineAsm::AsmDialect(AsmDialect), CanThrow);
  3152. break;
  3153. }
  3154. case bitc::CST_CODE_BLOCKADDRESS:{
  3155. if (Record.size() < 3)
  3156. return error("Invalid blockaddress record");
  3157. unsigned FnTyID = Record[0];
  3158. Type *FnTy = getTypeByID(FnTyID);
  3159. if (!FnTy)
  3160. return error("Invalid blockaddress record");
  3161. V = BitcodeConstant::create(
  3162. Alloc, CurTy,
  3163. {BitcodeConstant::BlockAddressOpcode, 0, (unsigned)Record[2]},
  3164. Record[1]);
  3165. break;
  3166. }
  3167. case bitc::CST_CODE_DSO_LOCAL_EQUIVALENT: {
  3168. if (Record.size() < 2)
  3169. return error("Invalid dso_local record");
  3170. unsigned GVTyID = Record[0];
  3171. Type *GVTy = getTypeByID(GVTyID);
  3172. if (!GVTy)
  3173. return error("Invalid dso_local record");
  3174. V = BitcodeConstant::create(
  3175. Alloc, CurTy, BitcodeConstant::DSOLocalEquivalentOpcode, Record[1]);
  3176. break;
  3177. }
  3178. case bitc::CST_CODE_NO_CFI_VALUE: {
  3179. if (Record.size() < 2)
  3180. return error("Invalid no_cfi record");
  3181. unsigned GVTyID = Record[0];
  3182. Type *GVTy = getTypeByID(GVTyID);
  3183. if (!GVTy)
  3184. return error("Invalid no_cfi record");
  3185. V = BitcodeConstant::create(Alloc, CurTy, BitcodeConstant::NoCFIOpcode,
  3186. Record[1]);
  3187. break;
  3188. }
  3189. }
  3190. assert(V->getType() == getTypeByID(CurTyID) && "Incorrect result type ID");
  3191. if (Error Err = ValueList.assignValue(NextCstNo, V, CurTyID))
  3192. return Err;
  3193. ++NextCstNo;
  3194. }
  3195. }
  3196. Error BitcodeReader::parseUseLists() {
  3197. if (Error Err = Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  3198. return Err;
  3199. // Read all the records.
  3200. SmallVector<uint64_t, 64> Record;
  3201. while (true) {
  3202. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  3203. if (!MaybeEntry)
  3204. return MaybeEntry.takeError();
  3205. BitstreamEntry Entry = MaybeEntry.get();
  3206. switch (Entry.Kind) {
  3207. case BitstreamEntry::SubBlock: // Handled for us already.
  3208. case BitstreamEntry::Error:
  3209. return error("Malformed block");
  3210. case BitstreamEntry::EndBlock:
  3211. return Error::success();
  3212. case BitstreamEntry::Record:
  3213. // The interesting case.
  3214. break;
  3215. }
  3216. // Read a use list record.
  3217. Record.clear();
  3218. bool IsBB = false;
  3219. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  3220. if (!MaybeRecord)
  3221. return MaybeRecord.takeError();
  3222. switch (MaybeRecord.get()) {
  3223. default: // Default behavior: unknown type.
  3224. break;
  3225. case bitc::USELIST_CODE_BB:
  3226. IsBB = true;
  3227. [[fallthrough]];
  3228. case bitc::USELIST_CODE_DEFAULT: {
  3229. unsigned RecordLength = Record.size();
  3230. if (RecordLength < 3)
  3231. // Records should have at least an ID and two indexes.
  3232. return error("Invalid record");
  3233. unsigned ID = Record.pop_back_val();
  3234. Value *V;
  3235. if (IsBB) {
  3236. assert(ID < FunctionBBs.size() && "Basic block not found");
  3237. V = FunctionBBs[ID];
  3238. } else
  3239. V = ValueList[ID];
  3240. unsigned NumUses = 0;
  3241. SmallDenseMap<const Use *, unsigned, 16> Order;
  3242. for (const Use &U : V->materialized_uses()) {
  3243. if (++NumUses > Record.size())
  3244. break;
  3245. Order[&U] = Record[NumUses - 1];
  3246. }
  3247. if (Order.size() != Record.size() || NumUses > Record.size())
  3248. // Mismatches can happen if the functions are being materialized lazily
  3249. // (out-of-order), or a value has been upgraded.
  3250. break;
  3251. V->sortUseList([&](const Use &L, const Use &R) {
  3252. return Order.lookup(&L) < Order.lookup(&R);
  3253. });
  3254. break;
  3255. }
  3256. }
  3257. }
  3258. }
  3259. /// When we see the block for metadata, remember where it is and then skip it.
  3260. /// This lets us lazily deserialize the metadata.
  3261. Error BitcodeReader::rememberAndSkipMetadata() {
  3262. // Save the current stream state.
  3263. uint64_t CurBit = Stream.GetCurrentBitNo();
  3264. DeferredMetadataInfo.push_back(CurBit);
  3265. // Skip over the block for now.
  3266. if (Error Err = Stream.SkipBlock())
  3267. return Err;
  3268. return Error::success();
  3269. }
  3270. Error BitcodeReader::materializeMetadata() {
  3271. for (uint64_t BitPos : DeferredMetadataInfo) {
  3272. // Move the bit stream to the saved position.
  3273. if (Error JumpFailed = Stream.JumpToBit(BitPos))
  3274. return JumpFailed;
  3275. if (Error Err = MDLoader->parseModuleMetadata())
  3276. return Err;
  3277. }
  3278. // Upgrade "Linker Options" module flag to "llvm.linker.options" module-level
  3279. // metadata. Only upgrade if the new option doesn't exist to avoid upgrade
  3280. // multiple times.
  3281. if (!TheModule->getNamedMetadata("llvm.linker.options")) {
  3282. if (Metadata *Val = TheModule->getModuleFlag("Linker Options")) {
  3283. NamedMDNode *LinkerOpts =
  3284. TheModule->getOrInsertNamedMetadata("llvm.linker.options");
  3285. for (const MDOperand &MDOptions : cast<MDNode>(Val)->operands())
  3286. LinkerOpts->addOperand(cast<MDNode>(MDOptions));
  3287. }
  3288. }
  3289. DeferredMetadataInfo.clear();
  3290. return Error::success();
  3291. }
  3292. void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
  3293. /// When we see the block for a function body, remember where it is and then
  3294. /// skip it. This lets us lazily deserialize the functions.
  3295. Error BitcodeReader::rememberAndSkipFunctionBody() {
  3296. // Get the function we are talking about.
  3297. if (FunctionsWithBodies.empty())
  3298. return error("Insufficient function protos");
  3299. Function *Fn = FunctionsWithBodies.back();
  3300. FunctionsWithBodies.pop_back();
  3301. // Save the current stream state.
  3302. uint64_t CurBit = Stream.GetCurrentBitNo();
  3303. assert(
  3304. (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
  3305. "Mismatch between VST and scanned function offsets");
  3306. DeferredFunctionInfo[Fn] = CurBit;
  3307. // Skip over the function block for now.
  3308. if (Error Err = Stream.SkipBlock())
  3309. return Err;
  3310. return Error::success();
  3311. }
  3312. Error BitcodeReader::globalCleanup() {
  3313. // Patch the initializers for globals and aliases up.
  3314. if (Error Err = resolveGlobalAndIndirectSymbolInits())
  3315. return Err;
  3316. if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
  3317. return error("Malformed global initializer set");
  3318. // Look for intrinsic functions which need to be upgraded at some point
  3319. // and functions that need to have their function attributes upgraded.
  3320. for (Function &F : *TheModule) {
  3321. MDLoader->upgradeDebugIntrinsics(F);
  3322. Function *NewFn;
  3323. if (UpgradeIntrinsicFunction(&F, NewFn))
  3324. UpgradedIntrinsics[&F] = NewFn;
  3325. // Look for functions that rely on old function attribute behavior.
  3326. UpgradeFunctionAttributes(F);
  3327. }
  3328. // Look for global variables which need to be renamed.
  3329. std::vector<std::pair<GlobalVariable *, GlobalVariable *>> UpgradedVariables;
  3330. for (GlobalVariable &GV : TheModule->globals())
  3331. if (GlobalVariable *Upgraded = UpgradeGlobalVariable(&GV))
  3332. UpgradedVariables.emplace_back(&GV, Upgraded);
  3333. for (auto &Pair : UpgradedVariables) {
  3334. Pair.first->eraseFromParent();
  3335. TheModule->getGlobalList().push_back(Pair.second);
  3336. }
  3337. // Force deallocation of memory for these vectors to favor the client that
  3338. // want lazy deserialization.
  3339. std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
  3340. std::vector<std::pair<GlobalValue *, unsigned>>().swap(IndirectSymbolInits);
  3341. return Error::success();
  3342. }
  3343. /// Support for lazy parsing of function bodies. This is required if we
  3344. /// either have an old bitcode file without a VST forward declaration record,
  3345. /// or if we have an anonymous function being materialized, since anonymous
  3346. /// functions do not have a name and are therefore not in the VST.
  3347. Error BitcodeReader::rememberAndSkipFunctionBodies() {
  3348. if (Error JumpFailed = Stream.JumpToBit(NextUnreadBit))
  3349. return JumpFailed;
  3350. if (Stream.AtEndOfStream())
  3351. return error("Could not find function in stream");
  3352. if (!SeenFirstFunctionBody)
  3353. return error("Trying to materialize functions before seeing function blocks");
  3354. // An old bitcode file with the symbol table at the end would have
  3355. // finished the parse greedily.
  3356. assert(SeenValueSymbolTable);
  3357. SmallVector<uint64_t, 64> Record;
  3358. while (true) {
  3359. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  3360. if (!MaybeEntry)
  3361. return MaybeEntry.takeError();
  3362. llvm::BitstreamEntry Entry = MaybeEntry.get();
  3363. switch (Entry.Kind) {
  3364. default:
  3365. return error("Expect SubBlock");
  3366. case BitstreamEntry::SubBlock:
  3367. switch (Entry.ID) {
  3368. default:
  3369. return error("Expect function block");
  3370. case bitc::FUNCTION_BLOCK_ID:
  3371. if (Error Err = rememberAndSkipFunctionBody())
  3372. return Err;
  3373. NextUnreadBit = Stream.GetCurrentBitNo();
  3374. return Error::success();
  3375. }
  3376. }
  3377. }
  3378. }
  3379. Error BitcodeReaderBase::readBlockInfo() {
  3380. Expected<std::optional<BitstreamBlockInfo>> MaybeNewBlockInfo =
  3381. Stream.ReadBlockInfoBlock();
  3382. if (!MaybeNewBlockInfo)
  3383. return MaybeNewBlockInfo.takeError();
  3384. std::optional<BitstreamBlockInfo> NewBlockInfo =
  3385. std::move(MaybeNewBlockInfo.get());
  3386. if (!NewBlockInfo)
  3387. return error("Malformed block");
  3388. BlockInfo = std::move(*NewBlockInfo);
  3389. return Error::success();
  3390. }
  3391. Error BitcodeReader::parseComdatRecord(ArrayRef<uint64_t> Record) {
  3392. // v1: [selection_kind, name]
  3393. // v2: [strtab_offset, strtab_size, selection_kind]
  3394. StringRef Name;
  3395. std::tie(Name, Record) = readNameFromStrtab(Record);
  3396. if (Record.empty())
  3397. return error("Invalid record");
  3398. Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
  3399. std::string OldFormatName;
  3400. if (!UseStrtab) {
  3401. if (Record.size() < 2)
  3402. return error("Invalid record");
  3403. unsigned ComdatNameSize = Record[1];
  3404. if (ComdatNameSize > Record.size() - 2)
  3405. return error("Comdat name size too large");
  3406. OldFormatName.reserve(ComdatNameSize);
  3407. for (unsigned i = 0; i != ComdatNameSize; ++i)
  3408. OldFormatName += (char)Record[2 + i];
  3409. Name = OldFormatName;
  3410. }
  3411. Comdat *C = TheModule->getOrInsertComdat(Name);
  3412. C->setSelectionKind(SK);
  3413. ComdatList.push_back(C);
  3414. return Error::success();
  3415. }
  3416. static void inferDSOLocal(GlobalValue *GV) {
  3417. // infer dso_local from linkage and visibility if it is not encoded.
  3418. if (GV->hasLocalLinkage() ||
  3419. (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()))
  3420. GV->setDSOLocal(true);
  3421. }
  3422. GlobalValue::SanitizerMetadata deserializeSanitizerMetadata(unsigned V) {
  3423. GlobalValue::SanitizerMetadata Meta;
  3424. if (V & (1 << 0))
  3425. Meta.NoAddress = true;
  3426. if (V & (1 << 1))
  3427. Meta.NoHWAddress = true;
  3428. if (V & (1 << 2))
  3429. Meta.Memtag = true;
  3430. if (V & (1 << 3))
  3431. Meta.IsDynInit = true;
  3432. return Meta;
  3433. }
  3434. Error BitcodeReader::parseGlobalVarRecord(ArrayRef<uint64_t> Record) {
  3435. // v1: [pointer type, isconst, initid, linkage, alignment, section,
  3436. // visibility, threadlocal, unnamed_addr, externally_initialized,
  3437. // dllstorageclass, comdat, attributes, preemption specifier,
  3438. // partition strtab offset, partition strtab size] (name in VST)
  3439. // v2: [strtab_offset, strtab_size, v1]
  3440. StringRef Name;
  3441. std::tie(Name, Record) = readNameFromStrtab(Record);
  3442. if (Record.size() < 6)
  3443. return error("Invalid record");
  3444. unsigned TyID = Record[0];
  3445. Type *Ty = getTypeByID(TyID);
  3446. if (!Ty)
  3447. return error("Invalid record");
  3448. bool isConstant = Record[1] & 1;
  3449. bool explicitType = Record[1] & 2;
  3450. unsigned AddressSpace;
  3451. if (explicitType) {
  3452. AddressSpace = Record[1] >> 2;
  3453. } else {
  3454. if (!Ty->isPointerTy())
  3455. return error("Invalid type for value");
  3456. AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  3457. TyID = getContainedTypeID(TyID);
  3458. Ty = getTypeByID(TyID);
  3459. if (!Ty)
  3460. return error("Missing element type for old-style global");
  3461. }
  3462. uint64_t RawLinkage = Record[3];
  3463. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  3464. MaybeAlign Alignment;
  3465. if (Error Err = parseAlignmentValue(Record[4], Alignment))
  3466. return Err;
  3467. std::string Section;
  3468. if (Record[5]) {
  3469. if (Record[5] - 1 >= SectionTable.size())
  3470. return error("Invalid ID");
  3471. Section = SectionTable[Record[5] - 1];
  3472. }
  3473. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  3474. // Local linkage must have default visibility.
  3475. // auto-upgrade `hidden` and `protected` for old bitcode.
  3476. if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
  3477. Visibility = getDecodedVisibility(Record[6]);
  3478. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  3479. if (Record.size() > 7)
  3480. TLM = getDecodedThreadLocalMode(Record[7]);
  3481. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  3482. if (Record.size() > 8)
  3483. UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
  3484. bool ExternallyInitialized = false;
  3485. if (Record.size() > 9)
  3486. ExternallyInitialized = Record[9];
  3487. GlobalVariable *NewGV =
  3488. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, Name,
  3489. nullptr, TLM, AddressSpace, ExternallyInitialized);
  3490. NewGV->setAlignment(Alignment);
  3491. if (!Section.empty())
  3492. NewGV->setSection(Section);
  3493. NewGV->setVisibility(Visibility);
  3494. NewGV->setUnnamedAddr(UnnamedAddr);
  3495. if (Record.size() > 10) {
  3496. // A GlobalValue with local linkage cannot have a DLL storage class.
  3497. if (!NewGV->hasLocalLinkage()) {
  3498. NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
  3499. }
  3500. } else {
  3501. upgradeDLLImportExportLinkage(NewGV, RawLinkage);
  3502. }
  3503. ValueList.push_back(NewGV, getVirtualTypeID(NewGV->getType(), TyID));
  3504. // Remember which value to use for the global initializer.
  3505. if (unsigned InitID = Record[2])
  3506. GlobalInits.push_back(std::make_pair(NewGV, InitID - 1));
  3507. if (Record.size() > 11) {
  3508. if (unsigned ComdatID = Record[11]) {
  3509. if (ComdatID > ComdatList.size())
  3510. return error("Invalid global variable comdat ID");
  3511. NewGV->setComdat(ComdatList[ComdatID - 1]);
  3512. }
  3513. } else if (hasImplicitComdat(RawLinkage)) {
  3514. ImplicitComdatObjects.insert(NewGV);
  3515. }
  3516. if (Record.size() > 12) {
  3517. auto AS = getAttributes(Record[12]).getFnAttrs();
  3518. NewGV->setAttributes(AS);
  3519. }
  3520. if (Record.size() > 13) {
  3521. NewGV->setDSOLocal(getDecodedDSOLocal(Record[13]));
  3522. }
  3523. inferDSOLocal(NewGV);
  3524. // Check whether we have enough values to read a partition name.
  3525. if (Record.size() > 15)
  3526. NewGV->setPartition(StringRef(Strtab.data() + Record[14], Record[15]));
  3527. if (Record.size() > 16 && Record[16]) {
  3528. llvm::GlobalValue::SanitizerMetadata Meta =
  3529. deserializeSanitizerMetadata(Record[16]);
  3530. NewGV->setSanitizerMetadata(Meta);
  3531. }
  3532. return Error::success();
  3533. }
  3534. void BitcodeReader::callValueTypeCallback(Value *F, unsigned TypeID) {
  3535. if (ValueTypeCallback) {
  3536. (*ValueTypeCallback)(
  3537. F, TypeID, [this](unsigned I) { return getTypeByID(I); },
  3538. [this](unsigned I, unsigned J) { return getContainedTypeID(I, J); });
  3539. }
  3540. }
  3541. Error BitcodeReader::parseFunctionRecord(ArrayRef<uint64_t> Record) {
  3542. // v1: [type, callingconv, isproto, linkage, paramattr, alignment, section,
  3543. // visibility, gc, unnamed_addr, prologuedata, dllstorageclass, comdat,
  3544. // prefixdata, personalityfn, preemption specifier, addrspace] (name in VST)
  3545. // v2: [strtab_offset, strtab_size, v1]
  3546. StringRef Name;
  3547. std::tie(Name, Record) = readNameFromStrtab(Record);
  3548. if (Record.size() < 8)
  3549. return error("Invalid record");
  3550. unsigned FTyID = Record[0];
  3551. Type *FTy = getTypeByID(FTyID);
  3552. if (!FTy)
  3553. return error("Invalid record");
  3554. if (isa<PointerType>(FTy)) {
  3555. FTyID = getContainedTypeID(FTyID, 0);
  3556. FTy = getTypeByID(FTyID);
  3557. if (!FTy)
  3558. return error("Missing element type for old-style function");
  3559. }
  3560. if (!isa<FunctionType>(FTy))
  3561. return error("Invalid type for value");
  3562. auto CC = static_cast<CallingConv::ID>(Record[1]);
  3563. if (CC & ~CallingConv::MaxID)
  3564. return error("Invalid calling convention ID");
  3565. unsigned AddrSpace = TheModule->getDataLayout().getProgramAddressSpace();
  3566. if (Record.size() > 16)
  3567. AddrSpace = Record[16];
  3568. Function *Func =
  3569. Function::Create(cast<FunctionType>(FTy), GlobalValue::ExternalLinkage,
  3570. AddrSpace, Name, TheModule);
  3571. assert(Func->getFunctionType() == FTy &&
  3572. "Incorrect fully specified type provided for function");
  3573. FunctionTypeIDs[Func] = FTyID;
  3574. Func->setCallingConv(CC);
  3575. bool isProto = Record[2];
  3576. uint64_t RawLinkage = Record[3];
  3577. Func->setLinkage(getDecodedLinkage(RawLinkage));
  3578. Func->setAttributes(getAttributes(Record[4]));
  3579. callValueTypeCallback(Func, FTyID);
  3580. // Upgrade any old-style byval or sret without a type by propagating the
  3581. // argument's pointee type. There should be no opaque pointers where the byval
  3582. // type is implicit.
  3583. for (unsigned i = 0; i != Func->arg_size(); ++i) {
  3584. for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
  3585. Attribute::InAlloca}) {
  3586. if (!Func->hasParamAttribute(i, Kind))
  3587. continue;
  3588. if (Func->getParamAttribute(i, Kind).getValueAsType())
  3589. continue;
  3590. Func->removeParamAttr(i, Kind);
  3591. unsigned ParamTypeID = getContainedTypeID(FTyID, i + 1);
  3592. Type *PtrEltTy = getPtrElementTypeByID(ParamTypeID);
  3593. if (!PtrEltTy)
  3594. return error("Missing param element type for attribute upgrade");
  3595. Attribute NewAttr;
  3596. switch (Kind) {
  3597. case Attribute::ByVal:
  3598. NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
  3599. break;
  3600. case Attribute::StructRet:
  3601. NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
  3602. break;
  3603. case Attribute::InAlloca:
  3604. NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
  3605. break;
  3606. default:
  3607. llvm_unreachable("not an upgraded type attribute");
  3608. }
  3609. Func->addParamAttr(i, NewAttr);
  3610. }
  3611. }
  3612. if (Func->getCallingConv() == CallingConv::X86_INTR &&
  3613. !Func->arg_empty() && !Func->hasParamAttribute(0, Attribute::ByVal)) {
  3614. unsigned ParamTypeID = getContainedTypeID(FTyID, 1);
  3615. Type *ByValTy = getPtrElementTypeByID(ParamTypeID);
  3616. if (!ByValTy)
  3617. return error("Missing param element type for x86_intrcc upgrade");
  3618. Attribute NewAttr = Attribute::getWithByValType(Context, ByValTy);
  3619. Func->addParamAttr(0, NewAttr);
  3620. }
  3621. MaybeAlign Alignment;
  3622. if (Error Err = parseAlignmentValue(Record[5], Alignment))
  3623. return Err;
  3624. Func->setAlignment(Alignment);
  3625. if (Record[6]) {
  3626. if (Record[6] - 1 >= SectionTable.size())
  3627. return error("Invalid ID");
  3628. Func->setSection(SectionTable[Record[6] - 1]);
  3629. }
  3630. // Local linkage must have default visibility.
  3631. // auto-upgrade `hidden` and `protected` for old bitcode.
  3632. if (!Func->hasLocalLinkage())
  3633. Func->setVisibility(getDecodedVisibility(Record[7]));
  3634. if (Record.size() > 8 && Record[8]) {
  3635. if (Record[8] - 1 >= GCTable.size())
  3636. return error("Invalid ID");
  3637. Func->setGC(GCTable[Record[8] - 1]);
  3638. }
  3639. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  3640. if (Record.size() > 9)
  3641. UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
  3642. Func->setUnnamedAddr(UnnamedAddr);
  3643. FunctionOperandInfo OperandInfo = {Func, 0, 0, 0};
  3644. if (Record.size() > 10)
  3645. OperandInfo.Prologue = Record[10];
  3646. if (Record.size() > 11) {
  3647. // A GlobalValue with local linkage cannot have a DLL storage class.
  3648. if (!Func->hasLocalLinkage()) {
  3649. Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
  3650. }
  3651. } else {
  3652. upgradeDLLImportExportLinkage(Func, RawLinkage);
  3653. }
  3654. if (Record.size() > 12) {
  3655. if (unsigned ComdatID = Record[12]) {
  3656. if (ComdatID > ComdatList.size())
  3657. return error("Invalid function comdat ID");
  3658. Func->setComdat(ComdatList[ComdatID - 1]);
  3659. }
  3660. } else if (hasImplicitComdat(RawLinkage)) {
  3661. ImplicitComdatObjects.insert(Func);
  3662. }
  3663. if (Record.size() > 13)
  3664. OperandInfo.Prefix = Record[13];
  3665. if (Record.size() > 14)
  3666. OperandInfo.PersonalityFn = Record[14];
  3667. if (Record.size() > 15) {
  3668. Func->setDSOLocal(getDecodedDSOLocal(Record[15]));
  3669. }
  3670. inferDSOLocal(Func);
  3671. // Record[16] is the address space number.
  3672. // Check whether we have enough values to read a partition name. Also make
  3673. // sure Strtab has enough values.
  3674. if (Record.size() > 18 && Strtab.data() &&
  3675. Record[17] + Record[18] <= Strtab.size()) {
  3676. Func->setPartition(StringRef(Strtab.data() + Record[17], Record[18]));
  3677. }
  3678. ValueList.push_back(Func, getVirtualTypeID(Func->getType(), FTyID));
  3679. if (OperandInfo.PersonalityFn || OperandInfo.Prefix || OperandInfo.Prologue)
  3680. FunctionOperands.push_back(OperandInfo);
  3681. // If this is a function with a body, remember the prototype we are
  3682. // creating now, so that we can match up the body with them later.
  3683. if (!isProto) {
  3684. Func->setIsMaterializable(true);
  3685. FunctionsWithBodies.push_back(Func);
  3686. DeferredFunctionInfo[Func] = 0;
  3687. }
  3688. return Error::success();
  3689. }
  3690. Error BitcodeReader::parseGlobalIndirectSymbolRecord(
  3691. unsigned BitCode, ArrayRef<uint64_t> Record) {
  3692. // v1 ALIAS_OLD: [alias type, aliasee val#, linkage] (name in VST)
  3693. // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
  3694. // dllstorageclass, threadlocal, unnamed_addr,
  3695. // preemption specifier] (name in VST)
  3696. // v1 IFUNC: [alias type, addrspace, aliasee val#, linkage,
  3697. // visibility, dllstorageclass, threadlocal, unnamed_addr,
  3698. // preemption specifier] (name in VST)
  3699. // v2: [strtab_offset, strtab_size, v1]
  3700. StringRef Name;
  3701. std::tie(Name, Record) = readNameFromStrtab(Record);
  3702. bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
  3703. if (Record.size() < (3 + (unsigned)NewRecord))
  3704. return error("Invalid record");
  3705. unsigned OpNum = 0;
  3706. unsigned TypeID = Record[OpNum++];
  3707. Type *Ty = getTypeByID(TypeID);
  3708. if (!Ty)
  3709. return error("Invalid record");
  3710. unsigned AddrSpace;
  3711. if (!NewRecord) {
  3712. auto *PTy = dyn_cast<PointerType>(Ty);
  3713. if (!PTy)
  3714. return error("Invalid type for value");
  3715. AddrSpace = PTy->getAddressSpace();
  3716. TypeID = getContainedTypeID(TypeID);
  3717. Ty = getTypeByID(TypeID);
  3718. if (!Ty)
  3719. return error("Missing element type for old-style indirect symbol");
  3720. } else {
  3721. AddrSpace = Record[OpNum++];
  3722. }
  3723. auto Val = Record[OpNum++];
  3724. auto Linkage = Record[OpNum++];
  3725. GlobalValue *NewGA;
  3726. if (BitCode == bitc::MODULE_CODE_ALIAS ||
  3727. BitCode == bitc::MODULE_CODE_ALIAS_OLD)
  3728. NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
  3729. TheModule);
  3730. else
  3731. NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage), Name,
  3732. nullptr, TheModule);
  3733. // Local linkage must have default visibility.
  3734. // auto-upgrade `hidden` and `protected` for old bitcode.
  3735. if (OpNum != Record.size()) {
  3736. auto VisInd = OpNum++;
  3737. if (!NewGA->hasLocalLinkage())
  3738. NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
  3739. }
  3740. if (BitCode == bitc::MODULE_CODE_ALIAS ||
  3741. BitCode == bitc::MODULE_CODE_ALIAS_OLD) {
  3742. if (OpNum != Record.size()) {
  3743. auto S = Record[OpNum++];
  3744. // A GlobalValue with local linkage cannot have a DLL storage class.
  3745. if (!NewGA->hasLocalLinkage())
  3746. NewGA->setDLLStorageClass(getDecodedDLLStorageClass(S));
  3747. }
  3748. else
  3749. upgradeDLLImportExportLinkage(NewGA, Linkage);
  3750. if (OpNum != Record.size())
  3751. NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
  3752. if (OpNum != Record.size())
  3753. NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
  3754. }
  3755. if (OpNum != Record.size())
  3756. NewGA->setDSOLocal(getDecodedDSOLocal(Record[OpNum++]));
  3757. inferDSOLocal(NewGA);
  3758. // Check whether we have enough values to read a partition name.
  3759. if (OpNum + 1 < Record.size()) {
  3760. NewGA->setPartition(
  3761. StringRef(Strtab.data() + Record[OpNum], Record[OpNum + 1]));
  3762. OpNum += 2;
  3763. }
  3764. ValueList.push_back(NewGA, getVirtualTypeID(NewGA->getType(), TypeID));
  3765. IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
  3766. return Error::success();
  3767. }
  3768. Error BitcodeReader::parseModule(uint64_t ResumeBit,
  3769. bool ShouldLazyLoadMetadata,
  3770. ParserCallbacks Callbacks) {
  3771. this->ValueTypeCallback = std::move(Callbacks.ValueType);
  3772. if (ResumeBit) {
  3773. if (Error JumpFailed = Stream.JumpToBit(ResumeBit))
  3774. return JumpFailed;
  3775. } else if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  3776. return Err;
  3777. SmallVector<uint64_t, 64> Record;
  3778. // Parts of bitcode parsing depend on the datalayout. Make sure we
  3779. // finalize the datalayout before we run any of that code.
  3780. bool ResolvedDataLayout = false;
  3781. // In order to support importing modules with illegal data layout strings,
  3782. // delay parsing the data layout string until after upgrades and overrides
  3783. // have been applied, allowing to fix illegal data layout strings.
  3784. // Initialize to the current module's layout string in case none is specified.
  3785. std::string TentativeDataLayoutStr = TheModule->getDataLayoutStr();
  3786. auto ResolveDataLayout = [&]() -> Error {
  3787. if (ResolvedDataLayout)
  3788. return Error::success();
  3789. // Datalayout and triple can't be parsed after this point.
  3790. ResolvedDataLayout = true;
  3791. // Auto-upgrade the layout string
  3792. TentativeDataLayoutStr = llvm::UpgradeDataLayoutString(
  3793. TentativeDataLayoutStr, TheModule->getTargetTriple());
  3794. // Apply override
  3795. if (Callbacks.DataLayout) {
  3796. if (auto LayoutOverride = (*Callbacks.DataLayout)(
  3797. TheModule->getTargetTriple(), TentativeDataLayoutStr))
  3798. TentativeDataLayoutStr = *LayoutOverride;
  3799. }
  3800. // Now the layout string is finalized in TentativeDataLayoutStr. Parse it.
  3801. Expected<DataLayout> MaybeDL = DataLayout::parse(TentativeDataLayoutStr);
  3802. if (!MaybeDL)
  3803. return MaybeDL.takeError();
  3804. TheModule->setDataLayout(MaybeDL.get());
  3805. return Error::success();
  3806. };
  3807. // Read all the records for this module.
  3808. while (true) {
  3809. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  3810. if (!MaybeEntry)
  3811. return MaybeEntry.takeError();
  3812. llvm::BitstreamEntry Entry = MaybeEntry.get();
  3813. switch (Entry.Kind) {
  3814. case BitstreamEntry::Error:
  3815. return error("Malformed block");
  3816. case BitstreamEntry::EndBlock:
  3817. if (Error Err = ResolveDataLayout())
  3818. return Err;
  3819. return globalCleanup();
  3820. case BitstreamEntry::SubBlock:
  3821. switch (Entry.ID) {
  3822. default: // Skip unknown content.
  3823. if (Error Err = Stream.SkipBlock())
  3824. return Err;
  3825. break;
  3826. case bitc::BLOCKINFO_BLOCK_ID:
  3827. if (Error Err = readBlockInfo())
  3828. return Err;
  3829. break;
  3830. case bitc::PARAMATTR_BLOCK_ID:
  3831. if (Error Err = parseAttributeBlock())
  3832. return Err;
  3833. break;
  3834. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  3835. if (Error Err = parseAttributeGroupBlock())
  3836. return Err;
  3837. break;
  3838. case bitc::TYPE_BLOCK_ID_NEW:
  3839. if (Error Err = parseTypeTable())
  3840. return Err;
  3841. break;
  3842. case bitc::VALUE_SYMTAB_BLOCK_ID:
  3843. if (!SeenValueSymbolTable) {
  3844. // Either this is an old form VST without function index and an
  3845. // associated VST forward declaration record (which would have caused
  3846. // the VST to be jumped to and parsed before it was encountered
  3847. // normally in the stream), or there were no function blocks to
  3848. // trigger an earlier parsing of the VST.
  3849. assert(VSTOffset == 0 || FunctionsWithBodies.empty());
  3850. if (Error Err = parseValueSymbolTable())
  3851. return Err;
  3852. SeenValueSymbolTable = true;
  3853. } else {
  3854. // We must have had a VST forward declaration record, which caused
  3855. // the parser to jump to and parse the VST earlier.
  3856. assert(VSTOffset > 0);
  3857. if (Error Err = Stream.SkipBlock())
  3858. return Err;
  3859. }
  3860. break;
  3861. case bitc::CONSTANTS_BLOCK_ID:
  3862. if (Error Err = parseConstants())
  3863. return Err;
  3864. if (Error Err = resolveGlobalAndIndirectSymbolInits())
  3865. return Err;
  3866. break;
  3867. case bitc::METADATA_BLOCK_ID:
  3868. if (ShouldLazyLoadMetadata) {
  3869. if (Error Err = rememberAndSkipMetadata())
  3870. return Err;
  3871. break;
  3872. }
  3873. assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
  3874. if (Error Err = MDLoader->parseModuleMetadata())
  3875. return Err;
  3876. break;
  3877. case bitc::METADATA_KIND_BLOCK_ID:
  3878. if (Error Err = MDLoader->parseMetadataKinds())
  3879. return Err;
  3880. break;
  3881. case bitc::FUNCTION_BLOCK_ID:
  3882. if (Error Err = ResolveDataLayout())
  3883. return Err;
  3884. // If this is the first function body we've seen, reverse the
  3885. // FunctionsWithBodies list.
  3886. if (!SeenFirstFunctionBody) {
  3887. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  3888. if (Error Err = globalCleanup())
  3889. return Err;
  3890. SeenFirstFunctionBody = true;
  3891. }
  3892. if (VSTOffset > 0) {
  3893. // If we have a VST forward declaration record, make sure we
  3894. // parse the VST now if we haven't already. It is needed to
  3895. // set up the DeferredFunctionInfo vector for lazy reading.
  3896. if (!SeenValueSymbolTable) {
  3897. if (Error Err = BitcodeReader::parseValueSymbolTable(VSTOffset))
  3898. return Err;
  3899. SeenValueSymbolTable = true;
  3900. // Fall through so that we record the NextUnreadBit below.
  3901. // This is necessary in case we have an anonymous function that
  3902. // is later materialized. Since it will not have a VST entry we
  3903. // need to fall back to the lazy parse to find its offset.
  3904. } else {
  3905. // If we have a VST forward declaration record, but have already
  3906. // parsed the VST (just above, when the first function body was
  3907. // encountered here), then we are resuming the parse after
  3908. // materializing functions. The ResumeBit points to the
  3909. // start of the last function block recorded in the
  3910. // DeferredFunctionInfo map. Skip it.
  3911. if (Error Err = Stream.SkipBlock())
  3912. return Err;
  3913. continue;
  3914. }
  3915. }
  3916. // Support older bitcode files that did not have the function
  3917. // index in the VST, nor a VST forward declaration record, as
  3918. // well as anonymous functions that do not have VST entries.
  3919. // Build the DeferredFunctionInfo vector on the fly.
  3920. if (Error Err = rememberAndSkipFunctionBody())
  3921. return Err;
  3922. // Suspend parsing when we reach the function bodies. Subsequent
  3923. // materialization calls will resume it when necessary. If the bitcode
  3924. // file is old, the symbol table will be at the end instead and will not
  3925. // have been seen yet. In this case, just finish the parse now.
  3926. if (SeenValueSymbolTable) {
  3927. NextUnreadBit = Stream.GetCurrentBitNo();
  3928. // After the VST has been parsed, we need to make sure intrinsic name
  3929. // are auto-upgraded.
  3930. return globalCleanup();
  3931. }
  3932. break;
  3933. case bitc::USELIST_BLOCK_ID:
  3934. if (Error Err = parseUseLists())
  3935. return Err;
  3936. break;
  3937. case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
  3938. if (Error Err = parseOperandBundleTags())
  3939. return Err;
  3940. break;
  3941. case bitc::SYNC_SCOPE_NAMES_BLOCK_ID:
  3942. if (Error Err = parseSyncScopeNames())
  3943. return Err;
  3944. break;
  3945. }
  3946. continue;
  3947. case BitstreamEntry::Record:
  3948. // The interesting case.
  3949. break;
  3950. }
  3951. // Read a record.
  3952. Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
  3953. if (!MaybeBitCode)
  3954. return MaybeBitCode.takeError();
  3955. switch (unsigned BitCode = MaybeBitCode.get()) {
  3956. default: break; // Default behavior, ignore unknown content.
  3957. case bitc::MODULE_CODE_VERSION: {
  3958. Expected<unsigned> VersionOrErr = parseVersionRecord(Record);
  3959. if (!VersionOrErr)
  3960. return VersionOrErr.takeError();
  3961. UseRelativeIDs = *VersionOrErr >= 1;
  3962. break;
  3963. }
  3964. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  3965. if (ResolvedDataLayout)
  3966. return error("target triple too late in module");
  3967. std::string S;
  3968. if (convertToString(Record, 0, S))
  3969. return error("Invalid record");
  3970. TheModule->setTargetTriple(S);
  3971. break;
  3972. }
  3973. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  3974. if (ResolvedDataLayout)
  3975. return error("datalayout too late in module");
  3976. if (convertToString(Record, 0, TentativeDataLayoutStr))
  3977. return error("Invalid record");
  3978. break;
  3979. }
  3980. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  3981. std::string S;
  3982. if (convertToString(Record, 0, S))
  3983. return error("Invalid record");
  3984. TheModule->setModuleInlineAsm(S);
  3985. break;
  3986. }
  3987. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  3988. // Deprecated, but still needed to read old bitcode files.
  3989. std::string S;
  3990. if (convertToString(Record, 0, S))
  3991. return error("Invalid record");
  3992. // Ignore value.
  3993. break;
  3994. }
  3995. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  3996. std::string S;
  3997. if (convertToString(Record, 0, S))
  3998. return error("Invalid record");
  3999. SectionTable.push_back(S);
  4000. break;
  4001. }
  4002. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  4003. std::string S;
  4004. if (convertToString(Record, 0, S))
  4005. return error("Invalid record");
  4006. GCTable.push_back(S);
  4007. break;
  4008. }
  4009. case bitc::MODULE_CODE_COMDAT:
  4010. if (Error Err = parseComdatRecord(Record))
  4011. return Err;
  4012. break;
  4013. // FIXME: BitcodeReader should handle {GLOBALVAR, FUNCTION, ALIAS, IFUNC}
  4014. // written by ThinLinkBitcodeWriter. See
  4015. // `ThinLinkBitcodeWriter::writeSimplifiedModuleInfo` for the format of each
  4016. // record
  4017. // (https://github.com/llvm/llvm-project/blob/b6a93967d9c11e79802b5e75cec1584d6c8aa472/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp#L4714)
  4018. case bitc::MODULE_CODE_GLOBALVAR:
  4019. if (Error Err = parseGlobalVarRecord(Record))
  4020. return Err;
  4021. break;
  4022. case bitc::MODULE_CODE_FUNCTION:
  4023. if (Error Err = ResolveDataLayout())
  4024. return Err;
  4025. if (Error Err = parseFunctionRecord(Record))
  4026. return Err;
  4027. break;
  4028. case bitc::MODULE_CODE_IFUNC:
  4029. case bitc::MODULE_CODE_ALIAS:
  4030. case bitc::MODULE_CODE_ALIAS_OLD:
  4031. if (Error Err = parseGlobalIndirectSymbolRecord(BitCode, Record))
  4032. return Err;
  4033. break;
  4034. /// MODULE_CODE_VSTOFFSET: [offset]
  4035. case bitc::MODULE_CODE_VSTOFFSET:
  4036. if (Record.empty())
  4037. return error("Invalid record");
  4038. // Note that we subtract 1 here because the offset is relative to one word
  4039. // before the start of the identification or module block, which was
  4040. // historically always the start of the regular bitcode header.
  4041. VSTOffset = Record[0] - 1;
  4042. break;
  4043. /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  4044. case bitc::MODULE_CODE_SOURCE_FILENAME:
  4045. SmallString<128> ValueName;
  4046. if (convertToString(Record, 0, ValueName))
  4047. return error("Invalid record");
  4048. TheModule->setSourceFileName(ValueName);
  4049. break;
  4050. }
  4051. Record.clear();
  4052. }
  4053. this->ValueTypeCallback = std::nullopt;
  4054. return Error::success();
  4055. }
  4056. Error BitcodeReader::parseBitcodeInto(Module *M, bool ShouldLazyLoadMetadata,
  4057. bool IsImporting,
  4058. ParserCallbacks Callbacks) {
  4059. TheModule = M;
  4060. MetadataLoaderCallbacks MDCallbacks;
  4061. MDCallbacks.GetTypeByID = [&](unsigned ID) { return getTypeByID(ID); };
  4062. MDCallbacks.GetContainedTypeID = [&](unsigned I, unsigned J) {
  4063. return getContainedTypeID(I, J);
  4064. };
  4065. MDCallbacks.MDType = Callbacks.MDType;
  4066. MDLoader = MetadataLoader(Stream, *M, ValueList, IsImporting, MDCallbacks);
  4067. return parseModule(0, ShouldLazyLoadMetadata, Callbacks);
  4068. }
  4069. Error BitcodeReader::typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
  4070. if (!isa<PointerType>(PtrType))
  4071. return error("Load/Store operand is not a pointer type");
  4072. if (!cast<PointerType>(PtrType)->isOpaqueOrPointeeTypeMatches(ValType))
  4073. return error("Explicit load/store type does not match pointee "
  4074. "type of pointer operand");
  4075. if (!PointerType::isLoadableOrStorableType(ValType))
  4076. return error("Cannot load/store from pointer");
  4077. return Error::success();
  4078. }
  4079. Error BitcodeReader::propagateAttributeTypes(CallBase *CB,
  4080. ArrayRef<unsigned> ArgTyIDs) {
  4081. AttributeList Attrs = CB->getAttributes();
  4082. for (unsigned i = 0; i != CB->arg_size(); ++i) {
  4083. for (Attribute::AttrKind Kind : {Attribute::ByVal, Attribute::StructRet,
  4084. Attribute::InAlloca}) {
  4085. if (!Attrs.hasParamAttr(i, Kind) ||
  4086. Attrs.getParamAttr(i, Kind).getValueAsType())
  4087. continue;
  4088. Type *PtrEltTy = getPtrElementTypeByID(ArgTyIDs[i]);
  4089. if (!PtrEltTy)
  4090. return error("Missing element type for typed attribute upgrade");
  4091. Attribute NewAttr;
  4092. switch (Kind) {
  4093. case Attribute::ByVal:
  4094. NewAttr = Attribute::getWithByValType(Context, PtrEltTy);
  4095. break;
  4096. case Attribute::StructRet:
  4097. NewAttr = Attribute::getWithStructRetType(Context, PtrEltTy);
  4098. break;
  4099. case Attribute::InAlloca:
  4100. NewAttr = Attribute::getWithInAllocaType(Context, PtrEltTy);
  4101. break;
  4102. default:
  4103. llvm_unreachable("not an upgraded type attribute");
  4104. }
  4105. Attrs = Attrs.addParamAttribute(Context, i, NewAttr);
  4106. }
  4107. }
  4108. if (CB->isInlineAsm()) {
  4109. const InlineAsm *IA = cast<InlineAsm>(CB->getCalledOperand());
  4110. unsigned ArgNo = 0;
  4111. for (const InlineAsm::ConstraintInfo &CI : IA->ParseConstraints()) {
  4112. if (!CI.hasArg())
  4113. continue;
  4114. if (CI.isIndirect && !Attrs.getParamElementType(ArgNo)) {
  4115. Type *ElemTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
  4116. if (!ElemTy)
  4117. return error("Missing element type for inline asm upgrade");
  4118. Attrs = Attrs.addParamAttribute(
  4119. Context, ArgNo,
  4120. Attribute::get(Context, Attribute::ElementType, ElemTy));
  4121. }
  4122. ArgNo++;
  4123. }
  4124. }
  4125. switch (CB->getIntrinsicID()) {
  4126. case Intrinsic::preserve_array_access_index:
  4127. case Intrinsic::preserve_struct_access_index:
  4128. case Intrinsic::aarch64_ldaxr:
  4129. case Intrinsic::aarch64_ldxr:
  4130. case Intrinsic::aarch64_stlxr:
  4131. case Intrinsic::aarch64_stxr:
  4132. case Intrinsic::arm_ldaex:
  4133. case Intrinsic::arm_ldrex:
  4134. case Intrinsic::arm_stlex:
  4135. case Intrinsic::arm_strex: {
  4136. unsigned ArgNo;
  4137. switch (CB->getIntrinsicID()) {
  4138. case Intrinsic::aarch64_stlxr:
  4139. case Intrinsic::aarch64_stxr:
  4140. case Intrinsic::arm_stlex:
  4141. case Intrinsic::arm_strex:
  4142. ArgNo = 1;
  4143. break;
  4144. default:
  4145. ArgNo = 0;
  4146. break;
  4147. }
  4148. if (!Attrs.getParamElementType(ArgNo)) {
  4149. Type *ElTy = getPtrElementTypeByID(ArgTyIDs[ArgNo]);
  4150. if (!ElTy)
  4151. return error("Missing element type for elementtype upgrade");
  4152. Attribute NewAttr = Attribute::get(Context, Attribute::ElementType, ElTy);
  4153. Attrs = Attrs.addParamAttribute(Context, ArgNo, NewAttr);
  4154. }
  4155. break;
  4156. }
  4157. default:
  4158. break;
  4159. }
  4160. CB->setAttributes(Attrs);
  4161. return Error::success();
  4162. }
  4163. /// Lazily parse the specified function body block.
  4164. Error BitcodeReader::parseFunctionBody(Function *F) {
  4165. if (Error Err = Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  4166. return Err;
  4167. // Unexpected unresolved metadata when parsing function.
  4168. if (MDLoader->hasFwdRefs())
  4169. return error("Invalid function metadata: incoming forward references");
  4170. InstructionList.clear();
  4171. unsigned ModuleValueListSize = ValueList.size();
  4172. unsigned ModuleMDLoaderSize = MDLoader->size();
  4173. // Add all the function arguments to the value table.
  4174. unsigned ArgNo = 0;
  4175. unsigned FTyID = FunctionTypeIDs[F];
  4176. for (Argument &I : F->args()) {
  4177. unsigned ArgTyID = getContainedTypeID(FTyID, ArgNo + 1);
  4178. assert(I.getType() == getTypeByID(ArgTyID) &&
  4179. "Incorrect fully specified type for Function Argument");
  4180. ValueList.push_back(&I, ArgTyID);
  4181. ++ArgNo;
  4182. }
  4183. unsigned NextValueNo = ValueList.size();
  4184. BasicBlock *CurBB = nullptr;
  4185. unsigned CurBBNo = 0;
  4186. // Block into which constant expressions from phi nodes are materialized.
  4187. BasicBlock *PhiConstExprBB = nullptr;
  4188. // Edge blocks for phi nodes into which constant expressions have been
  4189. // expanded.
  4190. SmallMapVector<std::pair<BasicBlock *, BasicBlock *>, BasicBlock *, 4>
  4191. ConstExprEdgeBBs;
  4192. DebugLoc LastLoc;
  4193. auto getLastInstruction = [&]() -> Instruction * {
  4194. if (CurBB && !CurBB->empty())
  4195. return &CurBB->back();
  4196. else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
  4197. !FunctionBBs[CurBBNo - 1]->empty())
  4198. return &FunctionBBs[CurBBNo - 1]->back();
  4199. return nullptr;
  4200. };
  4201. std::vector<OperandBundleDef> OperandBundles;
  4202. // Read all the records.
  4203. SmallVector<uint64_t, 64> Record;
  4204. while (true) {
  4205. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4206. if (!MaybeEntry)
  4207. return MaybeEntry.takeError();
  4208. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4209. switch (Entry.Kind) {
  4210. case BitstreamEntry::Error:
  4211. return error("Malformed block");
  4212. case BitstreamEntry::EndBlock:
  4213. goto OutOfRecordLoop;
  4214. case BitstreamEntry::SubBlock:
  4215. switch (Entry.ID) {
  4216. default: // Skip unknown content.
  4217. if (Error Err = Stream.SkipBlock())
  4218. return Err;
  4219. break;
  4220. case bitc::CONSTANTS_BLOCK_ID:
  4221. if (Error Err = parseConstants())
  4222. return Err;
  4223. NextValueNo = ValueList.size();
  4224. break;
  4225. case bitc::VALUE_SYMTAB_BLOCK_ID:
  4226. if (Error Err = parseValueSymbolTable())
  4227. return Err;
  4228. break;
  4229. case bitc::METADATA_ATTACHMENT_ID:
  4230. if (Error Err = MDLoader->parseMetadataAttachment(*F, InstructionList))
  4231. return Err;
  4232. break;
  4233. case bitc::METADATA_BLOCK_ID:
  4234. assert(DeferredMetadataInfo.empty() &&
  4235. "Must read all module-level metadata before function-level");
  4236. if (Error Err = MDLoader->parseFunctionMetadata())
  4237. return Err;
  4238. break;
  4239. case bitc::USELIST_BLOCK_ID:
  4240. if (Error Err = parseUseLists())
  4241. return Err;
  4242. break;
  4243. }
  4244. continue;
  4245. case BitstreamEntry::Record:
  4246. // The interesting case.
  4247. break;
  4248. }
  4249. // Read a record.
  4250. Record.clear();
  4251. Instruction *I = nullptr;
  4252. unsigned ResTypeID = InvalidTypeID;
  4253. Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
  4254. if (!MaybeBitCode)
  4255. return MaybeBitCode.takeError();
  4256. switch (unsigned BitCode = MaybeBitCode.get()) {
  4257. default: // Default behavior: reject
  4258. return error("Invalid value");
  4259. case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
  4260. if (Record.empty() || Record[0] == 0)
  4261. return error("Invalid record");
  4262. // Create all the basic blocks for the function.
  4263. FunctionBBs.resize(Record[0]);
  4264. // See if anything took the address of blocks in this function.
  4265. auto BBFRI = BasicBlockFwdRefs.find(F);
  4266. if (BBFRI == BasicBlockFwdRefs.end()) {
  4267. for (BasicBlock *&BB : FunctionBBs)
  4268. BB = BasicBlock::Create(Context, "", F);
  4269. } else {
  4270. auto &BBRefs = BBFRI->second;
  4271. // Check for invalid basic block references.
  4272. if (BBRefs.size() > FunctionBBs.size())
  4273. return error("Invalid ID");
  4274. assert(!BBRefs.empty() && "Unexpected empty array");
  4275. assert(!BBRefs.front() && "Invalid reference to entry block");
  4276. for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
  4277. ++I)
  4278. if (I < RE && BBRefs[I]) {
  4279. BBRefs[I]->insertInto(F);
  4280. FunctionBBs[I] = BBRefs[I];
  4281. } else {
  4282. FunctionBBs[I] = BasicBlock::Create(Context, "", F);
  4283. }
  4284. // Erase from the table.
  4285. BasicBlockFwdRefs.erase(BBFRI);
  4286. }
  4287. CurBB = FunctionBBs[0];
  4288. continue;
  4289. }
  4290. case bitc::FUNC_CODE_BLOCKADDR_USERS: // BLOCKADDR_USERS: [vals...]
  4291. // The record should not be emitted if it's an empty list.
  4292. if (Record.empty())
  4293. return error("Invalid record");
  4294. // When we have the RARE case of a BlockAddress Constant that is not
  4295. // scoped to the Function it refers to, we need to conservatively
  4296. // materialize the referred to Function, regardless of whether or not
  4297. // that Function will ultimately be linked, otherwise users of
  4298. // BitcodeReader might start splicing out Function bodies such that we
  4299. // might no longer be able to materialize the BlockAddress since the
  4300. // BasicBlock (and entire body of the Function) the BlockAddress refers
  4301. // to may have been moved. In the case that the user of BitcodeReader
  4302. // decides ultimately not to link the Function body, materializing here
  4303. // could be considered wasteful, but it's better than a deserialization
  4304. // failure as described. This keeps BitcodeReader unaware of complex
  4305. // linkage policy decisions such as those use by LTO, leaving those
  4306. // decisions "one layer up."
  4307. for (uint64_t ValID : Record)
  4308. if (auto *F = dyn_cast<Function>(ValueList[ValID]))
  4309. BackwardRefFunctions.push_back(F);
  4310. else
  4311. return error("Invalid record");
  4312. continue;
  4313. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  4314. // This record indicates that the last instruction is at the same
  4315. // location as the previous instruction with a location.
  4316. I = getLastInstruction();
  4317. if (!I)
  4318. return error("Invalid record");
  4319. I->setDebugLoc(LastLoc);
  4320. I = nullptr;
  4321. continue;
  4322. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  4323. I = getLastInstruction();
  4324. if (!I || Record.size() < 4)
  4325. return error("Invalid record");
  4326. unsigned Line = Record[0], Col = Record[1];
  4327. unsigned ScopeID = Record[2], IAID = Record[3];
  4328. bool isImplicitCode = Record.size() == 5 && Record[4];
  4329. MDNode *Scope = nullptr, *IA = nullptr;
  4330. if (ScopeID) {
  4331. Scope = dyn_cast_or_null<MDNode>(
  4332. MDLoader->getMetadataFwdRefOrLoad(ScopeID - 1));
  4333. if (!Scope)
  4334. return error("Invalid record");
  4335. }
  4336. if (IAID) {
  4337. IA = dyn_cast_or_null<MDNode>(
  4338. MDLoader->getMetadataFwdRefOrLoad(IAID - 1));
  4339. if (!IA)
  4340. return error("Invalid record");
  4341. }
  4342. LastLoc = DILocation::get(Scope->getContext(), Line, Col, Scope, IA,
  4343. isImplicitCode);
  4344. I->setDebugLoc(LastLoc);
  4345. I = nullptr;
  4346. continue;
  4347. }
  4348. case bitc::FUNC_CODE_INST_UNOP: { // UNOP: [opval, ty, opcode]
  4349. unsigned OpNum = 0;
  4350. Value *LHS;
  4351. unsigned TypeID;
  4352. if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
  4353. OpNum+1 > Record.size())
  4354. return error("Invalid record");
  4355. int Opc = getDecodedUnaryOpcode(Record[OpNum++], LHS->getType());
  4356. if (Opc == -1)
  4357. return error("Invalid record");
  4358. I = UnaryOperator::Create((Instruction::UnaryOps)Opc, LHS);
  4359. ResTypeID = TypeID;
  4360. InstructionList.push_back(I);
  4361. if (OpNum < Record.size()) {
  4362. if (isa<FPMathOperator>(I)) {
  4363. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  4364. if (FMF.any())
  4365. I->setFastMathFlags(FMF);
  4366. }
  4367. }
  4368. break;
  4369. }
  4370. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  4371. unsigned OpNum = 0;
  4372. Value *LHS, *RHS;
  4373. unsigned TypeID;
  4374. if (getValueTypePair(Record, OpNum, NextValueNo, LHS, TypeID, CurBB) ||
  4375. popValue(Record, OpNum, NextValueNo, LHS->getType(), TypeID, RHS,
  4376. CurBB) ||
  4377. OpNum+1 > Record.size())
  4378. return error("Invalid record");
  4379. int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  4380. if (Opc == -1)
  4381. return error("Invalid record");
  4382. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  4383. ResTypeID = TypeID;
  4384. InstructionList.push_back(I);
  4385. if (OpNum < Record.size()) {
  4386. if (Opc == Instruction::Add ||
  4387. Opc == Instruction::Sub ||
  4388. Opc == Instruction::Mul ||
  4389. Opc == Instruction::Shl) {
  4390. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  4391. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  4392. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  4393. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  4394. } else if (Opc == Instruction::SDiv ||
  4395. Opc == Instruction::UDiv ||
  4396. Opc == Instruction::LShr ||
  4397. Opc == Instruction::AShr) {
  4398. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  4399. cast<BinaryOperator>(I)->setIsExact(true);
  4400. } else if (isa<FPMathOperator>(I)) {
  4401. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  4402. if (FMF.any())
  4403. I->setFastMathFlags(FMF);
  4404. }
  4405. }
  4406. break;
  4407. }
  4408. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  4409. unsigned OpNum = 0;
  4410. Value *Op;
  4411. unsigned OpTypeID;
  4412. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
  4413. OpNum+2 != Record.size())
  4414. return error("Invalid record");
  4415. ResTypeID = Record[OpNum];
  4416. Type *ResTy = getTypeByID(ResTypeID);
  4417. int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
  4418. if (Opc == -1 || !ResTy)
  4419. return error("Invalid record");
  4420. Instruction *Temp = nullptr;
  4421. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  4422. if (Temp) {
  4423. InstructionList.push_back(Temp);
  4424. assert(CurBB && "No current BB?");
  4425. Temp->insertInto(CurBB, CurBB->end());
  4426. }
  4427. } else {
  4428. auto CastOp = (Instruction::CastOps)Opc;
  4429. if (!CastInst::castIsValid(CastOp, Op, ResTy))
  4430. return error("Invalid cast");
  4431. I = CastInst::Create(CastOp, Op, ResTy);
  4432. }
  4433. InstructionList.push_back(I);
  4434. break;
  4435. }
  4436. case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
  4437. case bitc::FUNC_CODE_INST_GEP_OLD:
  4438. case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
  4439. unsigned OpNum = 0;
  4440. unsigned TyID;
  4441. Type *Ty;
  4442. bool InBounds;
  4443. if (BitCode == bitc::FUNC_CODE_INST_GEP) {
  4444. InBounds = Record[OpNum++];
  4445. TyID = Record[OpNum++];
  4446. Ty = getTypeByID(TyID);
  4447. } else {
  4448. InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
  4449. TyID = InvalidTypeID;
  4450. Ty = nullptr;
  4451. }
  4452. Value *BasePtr;
  4453. unsigned BasePtrTypeID;
  4454. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr, BasePtrTypeID,
  4455. CurBB))
  4456. return error("Invalid record");
  4457. if (!Ty) {
  4458. TyID = getContainedTypeID(BasePtrTypeID);
  4459. if (BasePtr->getType()->isVectorTy())
  4460. TyID = getContainedTypeID(TyID);
  4461. Ty = getTypeByID(TyID);
  4462. } else if (!cast<PointerType>(BasePtr->getType()->getScalarType())
  4463. ->isOpaqueOrPointeeTypeMatches(Ty)) {
  4464. return error(
  4465. "Explicit gep type does not match pointee type of pointer operand");
  4466. }
  4467. SmallVector<Value*, 16> GEPIdx;
  4468. while (OpNum != Record.size()) {
  4469. Value *Op;
  4470. unsigned OpTypeID;
  4471. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
  4472. return error("Invalid record");
  4473. GEPIdx.push_back(Op);
  4474. }
  4475. I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
  4476. ResTypeID = TyID;
  4477. if (cast<GEPOperator>(I)->getNumIndices() != 0) {
  4478. auto GTI = std::next(gep_type_begin(I));
  4479. for (Value *Idx : drop_begin(cast<GEPOperator>(I)->indices())) {
  4480. unsigned SubType = 0;
  4481. if (GTI.isStruct()) {
  4482. ConstantInt *IdxC =
  4483. Idx->getType()->isVectorTy()
  4484. ? cast<ConstantInt>(cast<Constant>(Idx)->getSplatValue())
  4485. : cast<ConstantInt>(Idx);
  4486. SubType = IdxC->getZExtValue();
  4487. }
  4488. ResTypeID = getContainedTypeID(ResTypeID, SubType);
  4489. ++GTI;
  4490. }
  4491. }
  4492. // At this point ResTypeID is the result element type. We need a pointer
  4493. // or vector of pointer to it.
  4494. ResTypeID = getVirtualTypeID(I->getType()->getScalarType(), ResTypeID);
  4495. if (I->getType()->isVectorTy())
  4496. ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
  4497. InstructionList.push_back(I);
  4498. if (InBounds)
  4499. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  4500. break;
  4501. }
  4502. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  4503. // EXTRACTVAL: [opty, opval, n x indices]
  4504. unsigned OpNum = 0;
  4505. Value *Agg;
  4506. unsigned AggTypeID;
  4507. if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
  4508. return error("Invalid record");
  4509. Type *Ty = Agg->getType();
  4510. unsigned RecSize = Record.size();
  4511. if (OpNum == RecSize)
  4512. return error("EXTRACTVAL: Invalid instruction with 0 indices");
  4513. SmallVector<unsigned, 4> EXTRACTVALIdx;
  4514. ResTypeID = AggTypeID;
  4515. for (; OpNum != RecSize; ++OpNum) {
  4516. bool IsArray = Ty->isArrayTy();
  4517. bool IsStruct = Ty->isStructTy();
  4518. uint64_t Index = Record[OpNum];
  4519. if (!IsStruct && !IsArray)
  4520. return error("EXTRACTVAL: Invalid type");
  4521. if ((unsigned)Index != Index)
  4522. return error("Invalid value");
  4523. if (IsStruct && Index >= Ty->getStructNumElements())
  4524. return error("EXTRACTVAL: Invalid struct index");
  4525. if (IsArray && Index >= Ty->getArrayNumElements())
  4526. return error("EXTRACTVAL: Invalid array index");
  4527. EXTRACTVALIdx.push_back((unsigned)Index);
  4528. if (IsStruct) {
  4529. Ty = Ty->getStructElementType(Index);
  4530. ResTypeID = getContainedTypeID(ResTypeID, Index);
  4531. } else {
  4532. Ty = Ty->getArrayElementType();
  4533. ResTypeID = getContainedTypeID(ResTypeID);
  4534. }
  4535. }
  4536. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  4537. InstructionList.push_back(I);
  4538. break;
  4539. }
  4540. case bitc::FUNC_CODE_INST_INSERTVAL: {
  4541. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  4542. unsigned OpNum = 0;
  4543. Value *Agg;
  4544. unsigned AggTypeID;
  4545. if (getValueTypePair(Record, OpNum, NextValueNo, Agg, AggTypeID, CurBB))
  4546. return error("Invalid record");
  4547. Value *Val;
  4548. unsigned ValTypeID;
  4549. if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
  4550. return error("Invalid record");
  4551. unsigned RecSize = Record.size();
  4552. if (OpNum == RecSize)
  4553. return error("INSERTVAL: Invalid instruction with 0 indices");
  4554. SmallVector<unsigned, 4> INSERTVALIdx;
  4555. Type *CurTy = Agg->getType();
  4556. for (; OpNum != RecSize; ++OpNum) {
  4557. bool IsArray = CurTy->isArrayTy();
  4558. bool IsStruct = CurTy->isStructTy();
  4559. uint64_t Index = Record[OpNum];
  4560. if (!IsStruct && !IsArray)
  4561. return error("INSERTVAL: Invalid type");
  4562. if ((unsigned)Index != Index)
  4563. return error("Invalid value");
  4564. if (IsStruct && Index >= CurTy->getStructNumElements())
  4565. return error("INSERTVAL: Invalid struct index");
  4566. if (IsArray && Index >= CurTy->getArrayNumElements())
  4567. return error("INSERTVAL: Invalid array index");
  4568. INSERTVALIdx.push_back((unsigned)Index);
  4569. if (IsStruct)
  4570. CurTy = CurTy->getStructElementType(Index);
  4571. else
  4572. CurTy = CurTy->getArrayElementType();
  4573. }
  4574. if (CurTy != Val->getType())
  4575. return error("Inserted value type doesn't match aggregate type");
  4576. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  4577. ResTypeID = AggTypeID;
  4578. InstructionList.push_back(I);
  4579. break;
  4580. }
  4581. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  4582. // obsolete form of select
  4583. // handles select i1 ... in old bitcode
  4584. unsigned OpNum = 0;
  4585. Value *TrueVal, *FalseVal, *Cond;
  4586. unsigned TypeID;
  4587. Type *CondType = Type::getInt1Ty(Context);
  4588. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, TypeID,
  4589. CurBB) ||
  4590. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), TypeID,
  4591. FalseVal, CurBB) ||
  4592. popValue(Record, OpNum, NextValueNo, CondType,
  4593. getVirtualTypeID(CondType), Cond, CurBB))
  4594. return error("Invalid record");
  4595. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  4596. ResTypeID = TypeID;
  4597. InstructionList.push_back(I);
  4598. break;
  4599. }
  4600. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  4601. // new form of select
  4602. // handles select i1 or select [N x i1]
  4603. unsigned OpNum = 0;
  4604. Value *TrueVal, *FalseVal, *Cond;
  4605. unsigned ValTypeID, CondTypeID;
  4606. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal, ValTypeID,
  4607. CurBB) ||
  4608. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), ValTypeID,
  4609. FalseVal, CurBB) ||
  4610. getValueTypePair(Record, OpNum, NextValueNo, Cond, CondTypeID, CurBB))
  4611. return error("Invalid record");
  4612. // select condition can be either i1 or [N x i1]
  4613. if (VectorType* vector_type =
  4614. dyn_cast<VectorType>(Cond->getType())) {
  4615. // expect <n x i1>
  4616. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  4617. return error("Invalid type for value");
  4618. } else {
  4619. // expect i1
  4620. if (Cond->getType() != Type::getInt1Ty(Context))
  4621. return error("Invalid type for value");
  4622. }
  4623. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  4624. ResTypeID = ValTypeID;
  4625. InstructionList.push_back(I);
  4626. if (OpNum < Record.size() && isa<FPMathOperator>(I)) {
  4627. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  4628. if (FMF.any())
  4629. I->setFastMathFlags(FMF);
  4630. }
  4631. break;
  4632. }
  4633. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  4634. unsigned OpNum = 0;
  4635. Value *Vec, *Idx;
  4636. unsigned VecTypeID, IdxTypeID;
  4637. if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB) ||
  4638. getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
  4639. return error("Invalid record");
  4640. if (!Vec->getType()->isVectorTy())
  4641. return error("Invalid type for value");
  4642. I = ExtractElementInst::Create(Vec, Idx);
  4643. ResTypeID = getContainedTypeID(VecTypeID);
  4644. InstructionList.push_back(I);
  4645. break;
  4646. }
  4647. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  4648. unsigned OpNum = 0;
  4649. Value *Vec, *Elt, *Idx;
  4650. unsigned VecTypeID, IdxTypeID;
  4651. if (getValueTypePair(Record, OpNum, NextValueNo, Vec, VecTypeID, CurBB))
  4652. return error("Invalid record");
  4653. if (!Vec->getType()->isVectorTy())
  4654. return error("Invalid type for value");
  4655. if (popValue(Record, OpNum, NextValueNo,
  4656. cast<VectorType>(Vec->getType())->getElementType(),
  4657. getContainedTypeID(VecTypeID), Elt, CurBB) ||
  4658. getValueTypePair(Record, OpNum, NextValueNo, Idx, IdxTypeID, CurBB))
  4659. return error("Invalid record");
  4660. I = InsertElementInst::Create(Vec, Elt, Idx);
  4661. ResTypeID = VecTypeID;
  4662. InstructionList.push_back(I);
  4663. break;
  4664. }
  4665. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  4666. unsigned OpNum = 0;
  4667. Value *Vec1, *Vec2, *Mask;
  4668. unsigned Vec1TypeID;
  4669. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1, Vec1TypeID,
  4670. CurBB) ||
  4671. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec1TypeID,
  4672. Vec2, CurBB))
  4673. return error("Invalid record");
  4674. unsigned MaskTypeID;
  4675. if (getValueTypePair(Record, OpNum, NextValueNo, Mask, MaskTypeID, CurBB))
  4676. return error("Invalid record");
  4677. if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
  4678. return error("Invalid type for value");
  4679. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  4680. ResTypeID =
  4681. getVirtualTypeID(I->getType(), getContainedTypeID(Vec1TypeID));
  4682. InstructionList.push_back(I);
  4683. break;
  4684. }
  4685. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  4686. // Old form of ICmp/FCmp returning bool
  4687. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  4688. // both legal on vectors but had different behaviour.
  4689. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  4690. // FCmp/ICmp returning bool or vector of bool
  4691. unsigned OpNum = 0;
  4692. Value *LHS, *RHS;
  4693. unsigned LHSTypeID;
  4694. if (getValueTypePair(Record, OpNum, NextValueNo, LHS, LHSTypeID, CurBB) ||
  4695. popValue(Record, OpNum, NextValueNo, LHS->getType(), LHSTypeID, RHS,
  4696. CurBB))
  4697. return error("Invalid record");
  4698. if (OpNum >= Record.size())
  4699. return error(
  4700. "Invalid record: operand number exceeded available operands");
  4701. unsigned PredVal = Record[OpNum];
  4702. bool IsFP = LHS->getType()->isFPOrFPVectorTy();
  4703. FastMathFlags FMF;
  4704. if (IsFP && Record.size() > OpNum+1)
  4705. FMF = getDecodedFastMathFlags(Record[++OpNum]);
  4706. if (OpNum+1 != Record.size())
  4707. return error("Invalid record");
  4708. if (LHS->getType()->isFPOrFPVectorTy())
  4709. I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
  4710. else
  4711. I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
  4712. ResTypeID = getVirtualTypeID(I->getType()->getScalarType());
  4713. if (LHS->getType()->isVectorTy())
  4714. ResTypeID = getVirtualTypeID(I->getType(), ResTypeID);
  4715. if (FMF.any())
  4716. I->setFastMathFlags(FMF);
  4717. InstructionList.push_back(I);
  4718. break;
  4719. }
  4720. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  4721. {
  4722. unsigned Size = Record.size();
  4723. if (Size == 0) {
  4724. I = ReturnInst::Create(Context);
  4725. InstructionList.push_back(I);
  4726. break;
  4727. }
  4728. unsigned OpNum = 0;
  4729. Value *Op = nullptr;
  4730. unsigned OpTypeID;
  4731. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
  4732. return error("Invalid record");
  4733. if (OpNum != Record.size())
  4734. return error("Invalid record");
  4735. I = ReturnInst::Create(Context, Op);
  4736. InstructionList.push_back(I);
  4737. break;
  4738. }
  4739. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  4740. if (Record.size() != 1 && Record.size() != 3)
  4741. return error("Invalid record");
  4742. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  4743. if (!TrueDest)
  4744. return error("Invalid record");
  4745. if (Record.size() == 1) {
  4746. I = BranchInst::Create(TrueDest);
  4747. InstructionList.push_back(I);
  4748. }
  4749. else {
  4750. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  4751. Type *CondType = Type::getInt1Ty(Context);
  4752. Value *Cond = getValue(Record, 2, NextValueNo, CondType,
  4753. getVirtualTypeID(CondType), CurBB);
  4754. if (!FalseDest || !Cond)
  4755. return error("Invalid record");
  4756. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  4757. InstructionList.push_back(I);
  4758. }
  4759. break;
  4760. }
  4761. case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
  4762. if (Record.size() != 1 && Record.size() != 2)
  4763. return error("Invalid record");
  4764. unsigned Idx = 0;
  4765. Type *TokenTy = Type::getTokenTy(Context);
  4766. Value *CleanupPad = getValue(Record, Idx++, NextValueNo, TokenTy,
  4767. getVirtualTypeID(TokenTy), CurBB);
  4768. if (!CleanupPad)
  4769. return error("Invalid record");
  4770. BasicBlock *UnwindDest = nullptr;
  4771. if (Record.size() == 2) {
  4772. UnwindDest = getBasicBlock(Record[Idx++]);
  4773. if (!UnwindDest)
  4774. return error("Invalid record");
  4775. }
  4776. I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
  4777. InstructionList.push_back(I);
  4778. break;
  4779. }
  4780. case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
  4781. if (Record.size() != 2)
  4782. return error("Invalid record");
  4783. unsigned Idx = 0;
  4784. Type *TokenTy = Type::getTokenTy(Context);
  4785. Value *CatchPad = getValue(Record, Idx++, NextValueNo, TokenTy,
  4786. getVirtualTypeID(TokenTy), CurBB);
  4787. if (!CatchPad)
  4788. return error("Invalid record");
  4789. BasicBlock *BB = getBasicBlock(Record[Idx++]);
  4790. if (!BB)
  4791. return error("Invalid record");
  4792. I = CatchReturnInst::Create(CatchPad, BB);
  4793. InstructionList.push_back(I);
  4794. break;
  4795. }
  4796. case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
  4797. // We must have, at minimum, the outer scope and the number of arguments.
  4798. if (Record.size() < 2)
  4799. return error("Invalid record");
  4800. unsigned Idx = 0;
  4801. Type *TokenTy = Type::getTokenTy(Context);
  4802. Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
  4803. getVirtualTypeID(TokenTy), CurBB);
  4804. unsigned NumHandlers = Record[Idx++];
  4805. SmallVector<BasicBlock *, 2> Handlers;
  4806. for (unsigned Op = 0; Op != NumHandlers; ++Op) {
  4807. BasicBlock *BB = getBasicBlock(Record[Idx++]);
  4808. if (!BB)
  4809. return error("Invalid record");
  4810. Handlers.push_back(BB);
  4811. }
  4812. BasicBlock *UnwindDest = nullptr;
  4813. if (Idx + 1 == Record.size()) {
  4814. UnwindDest = getBasicBlock(Record[Idx++]);
  4815. if (!UnwindDest)
  4816. return error("Invalid record");
  4817. }
  4818. if (Record.size() != Idx)
  4819. return error("Invalid record");
  4820. auto *CatchSwitch =
  4821. CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
  4822. for (BasicBlock *Handler : Handlers)
  4823. CatchSwitch->addHandler(Handler);
  4824. I = CatchSwitch;
  4825. ResTypeID = getVirtualTypeID(I->getType());
  4826. InstructionList.push_back(I);
  4827. break;
  4828. }
  4829. case bitc::FUNC_CODE_INST_CATCHPAD:
  4830. case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
  4831. // We must have, at minimum, the outer scope and the number of arguments.
  4832. if (Record.size() < 2)
  4833. return error("Invalid record");
  4834. unsigned Idx = 0;
  4835. Type *TokenTy = Type::getTokenTy(Context);
  4836. Value *ParentPad = getValue(Record, Idx++, NextValueNo, TokenTy,
  4837. getVirtualTypeID(TokenTy), CurBB);
  4838. unsigned NumArgOperands = Record[Idx++];
  4839. SmallVector<Value *, 2> Args;
  4840. for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
  4841. Value *Val;
  4842. unsigned ValTypeID;
  4843. if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, nullptr))
  4844. return error("Invalid record");
  4845. Args.push_back(Val);
  4846. }
  4847. if (Record.size() != Idx)
  4848. return error("Invalid record");
  4849. if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
  4850. I = CleanupPadInst::Create(ParentPad, Args);
  4851. else
  4852. I = CatchPadInst::Create(ParentPad, Args);
  4853. ResTypeID = getVirtualTypeID(I->getType());
  4854. InstructionList.push_back(I);
  4855. break;
  4856. }
  4857. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  4858. // Check magic
  4859. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  4860. // "New" SwitchInst format with case ranges. The changes to write this
  4861. // format were reverted but we still recognize bitcode that uses it.
  4862. // Hopefully someday we will have support for case ranges and can use
  4863. // this format again.
  4864. unsigned OpTyID = Record[1];
  4865. Type *OpTy = getTypeByID(OpTyID);
  4866. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  4867. Value *Cond = getValue(Record, 2, NextValueNo, OpTy, OpTyID, CurBB);
  4868. BasicBlock *Default = getBasicBlock(Record[3]);
  4869. if (!OpTy || !Cond || !Default)
  4870. return error("Invalid record");
  4871. unsigned NumCases = Record[4];
  4872. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  4873. InstructionList.push_back(SI);
  4874. unsigned CurIdx = 5;
  4875. for (unsigned i = 0; i != NumCases; ++i) {
  4876. SmallVector<ConstantInt*, 1> CaseVals;
  4877. unsigned NumItems = Record[CurIdx++];
  4878. for (unsigned ci = 0; ci != NumItems; ++ci) {
  4879. bool isSingleNumber = Record[CurIdx++];
  4880. APInt Low;
  4881. unsigned ActiveWords = 1;
  4882. if (ValueBitWidth > 64)
  4883. ActiveWords = Record[CurIdx++];
  4884. Low = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
  4885. ValueBitWidth);
  4886. CurIdx += ActiveWords;
  4887. if (!isSingleNumber) {
  4888. ActiveWords = 1;
  4889. if (ValueBitWidth > 64)
  4890. ActiveWords = Record[CurIdx++];
  4891. APInt High = readWideAPInt(ArrayRef(&Record[CurIdx], ActiveWords),
  4892. ValueBitWidth);
  4893. CurIdx += ActiveWords;
  4894. // FIXME: It is not clear whether values in the range should be
  4895. // compared as signed or unsigned values. The partially
  4896. // implemented changes that used this format in the past used
  4897. // unsigned comparisons.
  4898. for ( ; Low.ule(High); ++Low)
  4899. CaseVals.push_back(ConstantInt::get(Context, Low));
  4900. } else
  4901. CaseVals.push_back(ConstantInt::get(Context, Low));
  4902. }
  4903. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  4904. for (ConstantInt *Cst : CaseVals)
  4905. SI->addCase(Cst, DestBB);
  4906. }
  4907. I = SI;
  4908. break;
  4909. }
  4910. // Old SwitchInst format without case ranges.
  4911. if (Record.size() < 3 || (Record.size() & 1) == 0)
  4912. return error("Invalid record");
  4913. unsigned OpTyID = Record[0];
  4914. Type *OpTy = getTypeByID(OpTyID);
  4915. Value *Cond = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
  4916. BasicBlock *Default = getBasicBlock(Record[2]);
  4917. if (!OpTy || !Cond || !Default)
  4918. return error("Invalid record");
  4919. unsigned NumCases = (Record.size()-3)/2;
  4920. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  4921. InstructionList.push_back(SI);
  4922. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  4923. ConstantInt *CaseVal = dyn_cast_or_null<ConstantInt>(
  4924. getFnValueByID(Record[3+i*2], OpTy, OpTyID, nullptr));
  4925. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  4926. if (!CaseVal || !DestBB) {
  4927. delete SI;
  4928. return error("Invalid record");
  4929. }
  4930. SI->addCase(CaseVal, DestBB);
  4931. }
  4932. I = SI;
  4933. break;
  4934. }
  4935. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  4936. if (Record.size() < 2)
  4937. return error("Invalid record");
  4938. unsigned OpTyID = Record[0];
  4939. Type *OpTy = getTypeByID(OpTyID);
  4940. Value *Address = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
  4941. if (!OpTy || !Address)
  4942. return error("Invalid record");
  4943. unsigned NumDests = Record.size()-2;
  4944. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  4945. InstructionList.push_back(IBI);
  4946. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  4947. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  4948. IBI->addDestination(DestBB);
  4949. } else {
  4950. delete IBI;
  4951. return error("Invalid record");
  4952. }
  4953. }
  4954. I = IBI;
  4955. break;
  4956. }
  4957. case bitc::FUNC_CODE_INST_INVOKE: {
  4958. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  4959. if (Record.size() < 4)
  4960. return error("Invalid record");
  4961. unsigned OpNum = 0;
  4962. AttributeList PAL = getAttributes(Record[OpNum++]);
  4963. unsigned CCInfo = Record[OpNum++];
  4964. BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
  4965. BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
  4966. unsigned FTyID = InvalidTypeID;
  4967. FunctionType *FTy = nullptr;
  4968. if ((CCInfo >> 13) & 1) {
  4969. FTyID = Record[OpNum++];
  4970. FTy = dyn_cast<FunctionType>(getTypeByID(FTyID));
  4971. if (!FTy)
  4972. return error("Explicit invoke type is not a function type");
  4973. }
  4974. Value *Callee;
  4975. unsigned CalleeTypeID;
  4976. if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
  4977. CurBB))
  4978. return error("Invalid record");
  4979. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  4980. if (!CalleeTy)
  4981. return error("Callee is not a pointer");
  4982. if (!FTy) {
  4983. FTyID = getContainedTypeID(CalleeTypeID);
  4984. FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
  4985. if (!FTy)
  4986. return error("Callee is not of pointer to function type");
  4987. } else if (!CalleeTy->isOpaqueOrPointeeTypeMatches(FTy))
  4988. return error("Explicit invoke type does not match pointee type of "
  4989. "callee operand");
  4990. if (Record.size() < FTy->getNumParams() + OpNum)
  4991. return error("Insufficient operands to call");
  4992. SmallVector<Value*, 16> Ops;
  4993. SmallVector<unsigned, 16> ArgTyIDs;
  4994. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  4995. unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
  4996. Ops.push_back(getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
  4997. ArgTyID, CurBB));
  4998. ArgTyIDs.push_back(ArgTyID);
  4999. if (!Ops.back())
  5000. return error("Invalid record");
  5001. }
  5002. if (!FTy->isVarArg()) {
  5003. if (Record.size() != OpNum)
  5004. return error("Invalid record");
  5005. } else {
  5006. // Read type/value pairs for varargs params.
  5007. while (OpNum != Record.size()) {
  5008. Value *Op;
  5009. unsigned OpTypeID;
  5010. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
  5011. return error("Invalid record");
  5012. Ops.push_back(Op);
  5013. ArgTyIDs.push_back(OpTypeID);
  5014. }
  5015. }
  5016. // Upgrade the bundles if needed.
  5017. if (!OperandBundles.empty())
  5018. UpgradeOperandBundles(OperandBundles);
  5019. I = InvokeInst::Create(FTy, Callee, NormalBB, UnwindBB, Ops,
  5020. OperandBundles);
  5021. ResTypeID = getContainedTypeID(FTyID);
  5022. OperandBundles.clear();
  5023. InstructionList.push_back(I);
  5024. cast<InvokeInst>(I)->setCallingConv(
  5025. static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
  5026. cast<InvokeInst>(I)->setAttributes(PAL);
  5027. if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
  5028. I->deleteValue();
  5029. return Err;
  5030. }
  5031. break;
  5032. }
  5033. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  5034. unsigned Idx = 0;
  5035. Value *Val = nullptr;
  5036. unsigned ValTypeID;
  5037. if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID, CurBB))
  5038. return error("Invalid record");
  5039. I = ResumeInst::Create(Val);
  5040. InstructionList.push_back(I);
  5041. break;
  5042. }
  5043. case bitc::FUNC_CODE_INST_CALLBR: {
  5044. // CALLBR: [attr, cc, norm, transfs, fty, fnid, args]
  5045. unsigned OpNum = 0;
  5046. AttributeList PAL = getAttributes(Record[OpNum++]);
  5047. unsigned CCInfo = Record[OpNum++];
  5048. BasicBlock *DefaultDest = getBasicBlock(Record[OpNum++]);
  5049. unsigned NumIndirectDests = Record[OpNum++];
  5050. SmallVector<BasicBlock *, 16> IndirectDests;
  5051. for (unsigned i = 0, e = NumIndirectDests; i != e; ++i)
  5052. IndirectDests.push_back(getBasicBlock(Record[OpNum++]));
  5053. unsigned FTyID = InvalidTypeID;
  5054. FunctionType *FTy = nullptr;
  5055. if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
  5056. FTyID = Record[OpNum++];
  5057. FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
  5058. if (!FTy)
  5059. return error("Explicit call type is not a function type");
  5060. }
  5061. Value *Callee;
  5062. unsigned CalleeTypeID;
  5063. if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
  5064. CurBB))
  5065. return error("Invalid record");
  5066. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  5067. if (!OpTy)
  5068. return error("Callee is not a pointer type");
  5069. if (!FTy) {
  5070. FTyID = getContainedTypeID(CalleeTypeID);
  5071. FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
  5072. if (!FTy)
  5073. return error("Callee is not of pointer to function type");
  5074. } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
  5075. return error("Explicit call type does not match pointee type of "
  5076. "callee operand");
  5077. if (Record.size() < FTy->getNumParams() + OpNum)
  5078. return error("Insufficient operands to call");
  5079. SmallVector<Value*, 16> Args;
  5080. SmallVector<unsigned, 16> ArgTyIDs;
  5081. // Read the fixed params.
  5082. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  5083. Value *Arg;
  5084. unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
  5085. if (FTy->getParamType(i)->isLabelTy())
  5086. Arg = getBasicBlock(Record[OpNum]);
  5087. else
  5088. Arg = getValue(Record, OpNum, NextValueNo, FTy->getParamType(i),
  5089. ArgTyID, CurBB);
  5090. if (!Arg)
  5091. return error("Invalid record");
  5092. Args.push_back(Arg);
  5093. ArgTyIDs.push_back(ArgTyID);
  5094. }
  5095. // Read type/value pairs for varargs params.
  5096. if (!FTy->isVarArg()) {
  5097. if (OpNum != Record.size())
  5098. return error("Invalid record");
  5099. } else {
  5100. while (OpNum != Record.size()) {
  5101. Value *Op;
  5102. unsigned OpTypeID;
  5103. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
  5104. return error("Invalid record");
  5105. Args.push_back(Op);
  5106. ArgTyIDs.push_back(OpTypeID);
  5107. }
  5108. }
  5109. // Upgrade the bundles if needed.
  5110. if (!OperandBundles.empty())
  5111. UpgradeOperandBundles(OperandBundles);
  5112. if (auto *IA = dyn_cast<InlineAsm>(Callee)) {
  5113. InlineAsm::ConstraintInfoVector ConstraintInfo = IA->ParseConstraints();
  5114. auto IsLabelConstraint = [](const InlineAsm::ConstraintInfo &CI) {
  5115. return CI.Type == InlineAsm::isLabel;
  5116. };
  5117. if (none_of(ConstraintInfo, IsLabelConstraint)) {
  5118. // Upgrade explicit blockaddress arguments to label constraints.
  5119. // Verify that the last arguments are blockaddress arguments that
  5120. // match the indirect destinations. Clang always generates callbr
  5121. // in this form. We could support reordering with more effort.
  5122. unsigned FirstBlockArg = Args.size() - IndirectDests.size();
  5123. for (unsigned ArgNo = FirstBlockArg; ArgNo < Args.size(); ++ArgNo) {
  5124. unsigned LabelNo = ArgNo - FirstBlockArg;
  5125. auto *BA = dyn_cast<BlockAddress>(Args[ArgNo]);
  5126. if (!BA || BA->getFunction() != F ||
  5127. LabelNo > IndirectDests.size() ||
  5128. BA->getBasicBlock() != IndirectDests[LabelNo])
  5129. return error("callbr argument does not match indirect dest");
  5130. }
  5131. // Remove blockaddress arguments.
  5132. Args.erase(Args.begin() + FirstBlockArg, Args.end());
  5133. ArgTyIDs.erase(ArgTyIDs.begin() + FirstBlockArg, ArgTyIDs.end());
  5134. // Recreate the function type with less arguments.
  5135. SmallVector<Type *> ArgTys;
  5136. for (Value *Arg : Args)
  5137. ArgTys.push_back(Arg->getType());
  5138. FTy =
  5139. FunctionType::get(FTy->getReturnType(), ArgTys, FTy->isVarArg());
  5140. // Update constraint string to use label constraints.
  5141. std::string Constraints = IA->getConstraintString();
  5142. unsigned ArgNo = 0;
  5143. size_t Pos = 0;
  5144. for (const auto &CI : ConstraintInfo) {
  5145. if (CI.hasArg()) {
  5146. if (ArgNo >= FirstBlockArg)
  5147. Constraints.insert(Pos, "!");
  5148. ++ArgNo;
  5149. }
  5150. // Go to next constraint in string.
  5151. Pos = Constraints.find(',', Pos);
  5152. if (Pos == std::string::npos)
  5153. break;
  5154. ++Pos;
  5155. }
  5156. Callee = InlineAsm::get(FTy, IA->getAsmString(), Constraints,
  5157. IA->hasSideEffects(), IA->isAlignStack(),
  5158. IA->getDialect(), IA->canThrow());
  5159. }
  5160. }
  5161. I = CallBrInst::Create(FTy, Callee, DefaultDest, IndirectDests, Args,
  5162. OperandBundles);
  5163. ResTypeID = getContainedTypeID(FTyID);
  5164. OperandBundles.clear();
  5165. InstructionList.push_back(I);
  5166. cast<CallBrInst>(I)->setCallingConv(
  5167. static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
  5168. cast<CallBrInst>(I)->setAttributes(PAL);
  5169. if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
  5170. I->deleteValue();
  5171. return Err;
  5172. }
  5173. break;
  5174. }
  5175. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  5176. I = new UnreachableInst(Context);
  5177. InstructionList.push_back(I);
  5178. break;
  5179. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  5180. if (Record.empty())
  5181. return error("Invalid phi record");
  5182. // The first record specifies the type.
  5183. unsigned TyID = Record[0];
  5184. Type *Ty = getTypeByID(TyID);
  5185. if (!Ty)
  5186. return error("Invalid phi record");
  5187. // Phi arguments are pairs of records of [value, basic block].
  5188. // There is an optional final record for fast-math-flags if this phi has a
  5189. // floating-point type.
  5190. size_t NumArgs = (Record.size() - 1) / 2;
  5191. PHINode *PN = PHINode::Create(Ty, NumArgs);
  5192. if ((Record.size() - 1) % 2 == 1 && !isa<FPMathOperator>(PN)) {
  5193. PN->deleteValue();
  5194. return error("Invalid phi record");
  5195. }
  5196. InstructionList.push_back(PN);
  5197. SmallDenseMap<BasicBlock *, Value *> Args;
  5198. for (unsigned i = 0; i != NumArgs; i++) {
  5199. BasicBlock *BB = getBasicBlock(Record[i * 2 + 2]);
  5200. if (!BB) {
  5201. PN->deleteValue();
  5202. return error("Invalid phi BB");
  5203. }
  5204. // Phi nodes may contain the same predecessor multiple times, in which
  5205. // case the incoming value must be identical. Directly reuse the already
  5206. // seen value here, to avoid expanding a constant expression multiple
  5207. // times.
  5208. auto It = Args.find(BB);
  5209. if (It != Args.end()) {
  5210. PN->addIncoming(It->second, BB);
  5211. continue;
  5212. }
  5213. // If there already is a block for this edge (from a different phi),
  5214. // use it.
  5215. BasicBlock *EdgeBB = ConstExprEdgeBBs.lookup({BB, CurBB});
  5216. if (!EdgeBB) {
  5217. // Otherwise, use a temporary block (that we will discard if it
  5218. // turns out to be unnecessary).
  5219. if (!PhiConstExprBB)
  5220. PhiConstExprBB = BasicBlock::Create(Context, "phi.constexpr", F);
  5221. EdgeBB = PhiConstExprBB;
  5222. }
  5223. // With the new function encoding, it is possible that operands have
  5224. // negative IDs (for forward references). Use a signed VBR
  5225. // representation to keep the encoding small.
  5226. Value *V;
  5227. if (UseRelativeIDs)
  5228. V = getValueSigned(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
  5229. else
  5230. V = getValue(Record, i * 2 + 1, NextValueNo, Ty, TyID, EdgeBB);
  5231. if (!V) {
  5232. PN->deleteValue();
  5233. PhiConstExprBB->eraseFromParent();
  5234. return error("Invalid phi record");
  5235. }
  5236. if (EdgeBB == PhiConstExprBB && !EdgeBB->empty()) {
  5237. ConstExprEdgeBBs.insert({{BB, CurBB}, EdgeBB});
  5238. PhiConstExprBB = nullptr;
  5239. }
  5240. PN->addIncoming(V, BB);
  5241. Args.insert({BB, V});
  5242. }
  5243. I = PN;
  5244. ResTypeID = TyID;
  5245. // If there are an even number of records, the final record must be FMF.
  5246. if (Record.size() % 2 == 0) {
  5247. assert(isa<FPMathOperator>(I) && "Unexpected phi type");
  5248. FastMathFlags FMF = getDecodedFastMathFlags(Record[Record.size() - 1]);
  5249. if (FMF.any())
  5250. I->setFastMathFlags(FMF);
  5251. }
  5252. break;
  5253. }
  5254. case bitc::FUNC_CODE_INST_LANDINGPAD:
  5255. case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
  5256. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  5257. unsigned Idx = 0;
  5258. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
  5259. if (Record.size() < 3)
  5260. return error("Invalid record");
  5261. } else {
  5262. assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
  5263. if (Record.size() < 4)
  5264. return error("Invalid record");
  5265. }
  5266. ResTypeID = Record[Idx++];
  5267. Type *Ty = getTypeByID(ResTypeID);
  5268. if (!Ty)
  5269. return error("Invalid record");
  5270. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
  5271. Value *PersFn = nullptr;
  5272. unsigned PersFnTypeID;
  5273. if (getValueTypePair(Record, Idx, NextValueNo, PersFn, PersFnTypeID,
  5274. nullptr))
  5275. return error("Invalid record");
  5276. if (!F->hasPersonalityFn())
  5277. F->setPersonalityFn(cast<Constant>(PersFn));
  5278. else if (F->getPersonalityFn() != cast<Constant>(PersFn))
  5279. return error("Personality function mismatch");
  5280. }
  5281. bool IsCleanup = !!Record[Idx++];
  5282. unsigned NumClauses = Record[Idx++];
  5283. LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
  5284. LP->setCleanup(IsCleanup);
  5285. for (unsigned J = 0; J != NumClauses; ++J) {
  5286. LandingPadInst::ClauseType CT =
  5287. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  5288. Value *Val;
  5289. unsigned ValTypeID;
  5290. if (getValueTypePair(Record, Idx, NextValueNo, Val, ValTypeID,
  5291. nullptr)) {
  5292. delete LP;
  5293. return error("Invalid record");
  5294. }
  5295. assert((CT != LandingPadInst::Catch ||
  5296. !isa<ArrayType>(Val->getType())) &&
  5297. "Catch clause has a invalid type!");
  5298. assert((CT != LandingPadInst::Filter ||
  5299. isa<ArrayType>(Val->getType())) &&
  5300. "Filter clause has invalid type!");
  5301. LP->addClause(cast<Constant>(Val));
  5302. }
  5303. I = LP;
  5304. InstructionList.push_back(I);
  5305. break;
  5306. }
  5307. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  5308. if (Record.size() != 4 && Record.size() != 5)
  5309. return error("Invalid record");
  5310. using APV = AllocaPackedValues;
  5311. const uint64_t Rec = Record[3];
  5312. const bool InAlloca = Bitfield::get<APV::UsedWithInAlloca>(Rec);
  5313. const bool SwiftError = Bitfield::get<APV::SwiftError>(Rec);
  5314. unsigned TyID = Record[0];
  5315. Type *Ty = getTypeByID(TyID);
  5316. if (!Bitfield::get<APV::ExplicitType>(Rec)) {
  5317. TyID = getContainedTypeID(TyID);
  5318. Ty = getTypeByID(TyID);
  5319. if (!Ty)
  5320. return error("Missing element type for old-style alloca");
  5321. }
  5322. unsigned OpTyID = Record[1];
  5323. Type *OpTy = getTypeByID(OpTyID);
  5324. Value *Size = getFnValueByID(Record[2], OpTy, OpTyID, CurBB);
  5325. MaybeAlign Align;
  5326. uint64_t AlignExp =
  5327. Bitfield::get<APV::AlignLower>(Rec) |
  5328. (Bitfield::get<APV::AlignUpper>(Rec) << APV::AlignLower::Bits);
  5329. if (Error Err = parseAlignmentValue(AlignExp, Align)) {
  5330. return Err;
  5331. }
  5332. if (!Ty || !Size)
  5333. return error("Invalid record");
  5334. const DataLayout &DL = TheModule->getDataLayout();
  5335. unsigned AS = Record.size() == 5 ? Record[4] : DL.getAllocaAddrSpace();
  5336. SmallPtrSet<Type *, 4> Visited;
  5337. if (!Align && !Ty->isSized(&Visited))
  5338. return error("alloca of unsized type");
  5339. if (!Align)
  5340. Align = DL.getPrefTypeAlign(Ty);
  5341. AllocaInst *AI = new AllocaInst(Ty, AS, Size, *Align);
  5342. AI->setUsedWithInAlloca(InAlloca);
  5343. AI->setSwiftError(SwiftError);
  5344. I = AI;
  5345. ResTypeID = getVirtualTypeID(AI->getType(), TyID);
  5346. InstructionList.push_back(I);
  5347. break;
  5348. }
  5349. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  5350. unsigned OpNum = 0;
  5351. Value *Op;
  5352. unsigned OpTypeID;
  5353. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
  5354. (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
  5355. return error("Invalid record");
  5356. if (!isa<PointerType>(Op->getType()))
  5357. return error("Load operand is not a pointer type");
  5358. Type *Ty = nullptr;
  5359. if (OpNum + 3 == Record.size()) {
  5360. ResTypeID = Record[OpNum++];
  5361. Ty = getTypeByID(ResTypeID);
  5362. } else {
  5363. ResTypeID = getContainedTypeID(OpTypeID);
  5364. Ty = getTypeByID(ResTypeID);
  5365. if (!Ty)
  5366. return error("Missing element type for old-style load");
  5367. }
  5368. if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
  5369. return Err;
  5370. MaybeAlign Align;
  5371. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  5372. return Err;
  5373. SmallPtrSet<Type *, 4> Visited;
  5374. if (!Align && !Ty->isSized(&Visited))
  5375. return error("load of unsized type");
  5376. if (!Align)
  5377. Align = TheModule->getDataLayout().getABITypeAlign(Ty);
  5378. I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align);
  5379. InstructionList.push_back(I);
  5380. break;
  5381. }
  5382. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  5383. // LOADATOMIC: [opty, op, align, vol, ordering, ssid]
  5384. unsigned OpNum = 0;
  5385. Value *Op;
  5386. unsigned OpTypeID;
  5387. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB) ||
  5388. (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
  5389. return error("Invalid record");
  5390. if (!isa<PointerType>(Op->getType()))
  5391. return error("Load operand is not a pointer type");
  5392. Type *Ty = nullptr;
  5393. if (OpNum + 5 == Record.size()) {
  5394. ResTypeID = Record[OpNum++];
  5395. Ty = getTypeByID(ResTypeID);
  5396. } else {
  5397. ResTypeID = getContainedTypeID(OpTypeID);
  5398. Ty = getTypeByID(ResTypeID);
  5399. if (!Ty)
  5400. return error("Missing element type for old style atomic load");
  5401. }
  5402. if (Error Err = typeCheckLoadStoreInst(Ty, Op->getType()))
  5403. return Err;
  5404. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  5405. if (Ordering == AtomicOrdering::NotAtomic ||
  5406. Ordering == AtomicOrdering::Release ||
  5407. Ordering == AtomicOrdering::AcquireRelease)
  5408. return error("Invalid record");
  5409. if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
  5410. return error("Invalid record");
  5411. SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
  5412. MaybeAlign Align;
  5413. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  5414. return Err;
  5415. if (!Align)
  5416. return error("Alignment missing from atomic load");
  5417. I = new LoadInst(Ty, Op, "", Record[OpNum + 1], *Align, Ordering, SSID);
  5418. InstructionList.push_back(I);
  5419. break;
  5420. }
  5421. case bitc::FUNC_CODE_INST_STORE:
  5422. case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
  5423. unsigned OpNum = 0;
  5424. Value *Val, *Ptr;
  5425. unsigned PtrTypeID, ValTypeID;
  5426. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
  5427. return error("Invalid record");
  5428. if (BitCode == bitc::FUNC_CODE_INST_STORE) {
  5429. if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
  5430. return error("Invalid record");
  5431. } else {
  5432. ValTypeID = getContainedTypeID(PtrTypeID);
  5433. if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
  5434. ValTypeID, Val, CurBB))
  5435. return error("Invalid record");
  5436. }
  5437. if (OpNum + 2 != Record.size())
  5438. return error("Invalid record");
  5439. if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
  5440. return Err;
  5441. MaybeAlign Align;
  5442. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  5443. return Err;
  5444. SmallPtrSet<Type *, 4> Visited;
  5445. if (!Align && !Val->getType()->isSized(&Visited))
  5446. return error("store of unsized type");
  5447. if (!Align)
  5448. Align = TheModule->getDataLayout().getABITypeAlign(Val->getType());
  5449. I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align);
  5450. InstructionList.push_back(I);
  5451. break;
  5452. }
  5453. case bitc::FUNC_CODE_INST_STOREATOMIC:
  5454. case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
  5455. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, ssid]
  5456. unsigned OpNum = 0;
  5457. Value *Val, *Ptr;
  5458. unsigned PtrTypeID, ValTypeID;
  5459. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB) ||
  5460. !isa<PointerType>(Ptr->getType()))
  5461. return error("Invalid record");
  5462. if (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC) {
  5463. if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
  5464. return error("Invalid record");
  5465. } else {
  5466. ValTypeID = getContainedTypeID(PtrTypeID);
  5467. if (popValue(Record, OpNum, NextValueNo, getTypeByID(ValTypeID),
  5468. ValTypeID, Val, CurBB))
  5469. return error("Invalid record");
  5470. }
  5471. if (OpNum + 4 != Record.size())
  5472. return error("Invalid record");
  5473. if (Error Err = typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
  5474. return Err;
  5475. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  5476. if (Ordering == AtomicOrdering::NotAtomic ||
  5477. Ordering == AtomicOrdering::Acquire ||
  5478. Ordering == AtomicOrdering::AcquireRelease)
  5479. return error("Invalid record");
  5480. SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
  5481. if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
  5482. return error("Invalid record");
  5483. MaybeAlign Align;
  5484. if (Error Err = parseAlignmentValue(Record[OpNum], Align))
  5485. return Err;
  5486. if (!Align)
  5487. return error("Alignment missing from atomic store");
  5488. I = new StoreInst(Val, Ptr, Record[OpNum + 1], *Align, Ordering, SSID);
  5489. InstructionList.push_back(I);
  5490. break;
  5491. }
  5492. case bitc::FUNC_CODE_INST_CMPXCHG_OLD: {
  5493. // CMPXCHG_OLD: [ptrty, ptr, cmp, val, vol, ordering, synchscope,
  5494. // failure_ordering?, weak?]
  5495. const size_t NumRecords = Record.size();
  5496. unsigned OpNum = 0;
  5497. Value *Ptr = nullptr;
  5498. unsigned PtrTypeID;
  5499. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
  5500. return error("Invalid record");
  5501. if (!isa<PointerType>(Ptr->getType()))
  5502. return error("Cmpxchg operand is not a pointer type");
  5503. Value *Cmp = nullptr;
  5504. unsigned CmpTypeID = getContainedTypeID(PtrTypeID);
  5505. if (popValue(Record, OpNum, NextValueNo, getTypeByID(CmpTypeID),
  5506. CmpTypeID, Cmp, CurBB))
  5507. return error("Invalid record");
  5508. Value *New = nullptr;
  5509. if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID,
  5510. New, CurBB) ||
  5511. NumRecords < OpNum + 3 || NumRecords > OpNum + 5)
  5512. return error("Invalid record");
  5513. const AtomicOrdering SuccessOrdering =
  5514. getDecodedOrdering(Record[OpNum + 1]);
  5515. if (SuccessOrdering == AtomicOrdering::NotAtomic ||
  5516. SuccessOrdering == AtomicOrdering::Unordered)
  5517. return error("Invalid record");
  5518. const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
  5519. if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
  5520. return Err;
  5521. const AtomicOrdering FailureOrdering =
  5522. NumRecords < 7
  5523. ? AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering)
  5524. : getDecodedOrdering(Record[OpNum + 3]);
  5525. if (FailureOrdering == AtomicOrdering::NotAtomic ||
  5526. FailureOrdering == AtomicOrdering::Unordered)
  5527. return error("Invalid record");
  5528. const Align Alignment(
  5529. TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
  5530. I = new AtomicCmpXchgInst(Ptr, Cmp, New, Alignment, SuccessOrdering,
  5531. FailureOrdering, SSID);
  5532. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  5533. if (NumRecords < 8) {
  5534. // Before weak cmpxchgs existed, the instruction simply returned the
  5535. // value loaded from memory, so bitcode files from that era will be
  5536. // expecting the first component of a modern cmpxchg.
  5537. I->insertInto(CurBB, CurBB->end());
  5538. I = ExtractValueInst::Create(I, 0);
  5539. ResTypeID = CmpTypeID;
  5540. } else {
  5541. cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum + 4]);
  5542. unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
  5543. ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
  5544. }
  5545. InstructionList.push_back(I);
  5546. break;
  5547. }
  5548. case bitc::FUNC_CODE_INST_CMPXCHG: {
  5549. // CMPXCHG: [ptrty, ptr, cmp, val, vol, success_ordering, synchscope,
  5550. // failure_ordering, weak, align?]
  5551. const size_t NumRecords = Record.size();
  5552. unsigned OpNum = 0;
  5553. Value *Ptr = nullptr;
  5554. unsigned PtrTypeID;
  5555. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
  5556. return error("Invalid record");
  5557. if (!isa<PointerType>(Ptr->getType()))
  5558. return error("Cmpxchg operand is not a pointer type");
  5559. Value *Cmp = nullptr;
  5560. unsigned CmpTypeID;
  5561. if (getValueTypePair(Record, OpNum, NextValueNo, Cmp, CmpTypeID, CurBB))
  5562. return error("Invalid record");
  5563. Value *Val = nullptr;
  5564. if (popValue(Record, OpNum, NextValueNo, Cmp->getType(), CmpTypeID, Val,
  5565. CurBB))
  5566. return error("Invalid record");
  5567. if (NumRecords < OpNum + 3 || NumRecords > OpNum + 6)
  5568. return error("Invalid record");
  5569. const bool IsVol = Record[OpNum];
  5570. const AtomicOrdering SuccessOrdering =
  5571. getDecodedOrdering(Record[OpNum + 1]);
  5572. if (!AtomicCmpXchgInst::isValidSuccessOrdering(SuccessOrdering))
  5573. return error("Invalid cmpxchg success ordering");
  5574. const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 2]);
  5575. if (Error Err = typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
  5576. return Err;
  5577. const AtomicOrdering FailureOrdering =
  5578. getDecodedOrdering(Record[OpNum + 3]);
  5579. if (!AtomicCmpXchgInst::isValidFailureOrdering(FailureOrdering))
  5580. return error("Invalid cmpxchg failure ordering");
  5581. const bool IsWeak = Record[OpNum + 4];
  5582. MaybeAlign Alignment;
  5583. if (NumRecords == (OpNum + 6)) {
  5584. if (Error Err = parseAlignmentValue(Record[OpNum + 5], Alignment))
  5585. return Err;
  5586. }
  5587. if (!Alignment)
  5588. Alignment =
  5589. Align(TheModule->getDataLayout().getTypeStoreSize(Cmp->getType()));
  5590. I = new AtomicCmpXchgInst(Ptr, Cmp, Val, *Alignment, SuccessOrdering,
  5591. FailureOrdering, SSID);
  5592. cast<AtomicCmpXchgInst>(I)->setVolatile(IsVol);
  5593. cast<AtomicCmpXchgInst>(I)->setWeak(IsWeak);
  5594. unsigned I1TypeID = getVirtualTypeID(Type::getInt1Ty(Context));
  5595. ResTypeID = getVirtualTypeID(I->getType(), {CmpTypeID, I1TypeID});
  5596. InstructionList.push_back(I);
  5597. break;
  5598. }
  5599. case bitc::FUNC_CODE_INST_ATOMICRMW_OLD:
  5600. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  5601. // ATOMICRMW_OLD: [ptrty, ptr, val, op, vol, ordering, ssid, align?]
  5602. // ATOMICRMW: [ptrty, ptr, valty, val, op, vol, ordering, ssid, align?]
  5603. const size_t NumRecords = Record.size();
  5604. unsigned OpNum = 0;
  5605. Value *Ptr = nullptr;
  5606. unsigned PtrTypeID;
  5607. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr, PtrTypeID, CurBB))
  5608. return error("Invalid record");
  5609. if (!isa<PointerType>(Ptr->getType()))
  5610. return error("Invalid record");
  5611. Value *Val = nullptr;
  5612. unsigned ValTypeID = InvalidTypeID;
  5613. if (BitCode == bitc::FUNC_CODE_INST_ATOMICRMW_OLD) {
  5614. ValTypeID = getContainedTypeID(PtrTypeID);
  5615. if (popValue(Record, OpNum, NextValueNo,
  5616. getTypeByID(ValTypeID), ValTypeID, Val, CurBB))
  5617. return error("Invalid record");
  5618. } else {
  5619. if (getValueTypePair(Record, OpNum, NextValueNo, Val, ValTypeID, CurBB))
  5620. return error("Invalid record");
  5621. }
  5622. if (!(NumRecords == (OpNum + 4) || NumRecords == (OpNum + 5)))
  5623. return error("Invalid record");
  5624. const AtomicRMWInst::BinOp Operation =
  5625. getDecodedRMWOperation(Record[OpNum]);
  5626. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  5627. Operation > AtomicRMWInst::LAST_BINOP)
  5628. return error("Invalid record");
  5629. const bool IsVol = Record[OpNum + 1];
  5630. const AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  5631. if (Ordering == AtomicOrdering::NotAtomic ||
  5632. Ordering == AtomicOrdering::Unordered)
  5633. return error("Invalid record");
  5634. const SyncScope::ID SSID = getDecodedSyncScopeID(Record[OpNum + 3]);
  5635. MaybeAlign Alignment;
  5636. if (NumRecords == (OpNum + 5)) {
  5637. if (Error Err = parseAlignmentValue(Record[OpNum + 4], Alignment))
  5638. return Err;
  5639. }
  5640. if (!Alignment)
  5641. Alignment =
  5642. Align(TheModule->getDataLayout().getTypeStoreSize(Val->getType()));
  5643. I = new AtomicRMWInst(Operation, Ptr, Val, *Alignment, Ordering, SSID);
  5644. ResTypeID = ValTypeID;
  5645. cast<AtomicRMWInst>(I)->setVolatile(IsVol);
  5646. InstructionList.push_back(I);
  5647. break;
  5648. }
  5649. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, ssid]
  5650. if (2 != Record.size())
  5651. return error("Invalid record");
  5652. AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
  5653. if (Ordering == AtomicOrdering::NotAtomic ||
  5654. Ordering == AtomicOrdering::Unordered ||
  5655. Ordering == AtomicOrdering::Monotonic)
  5656. return error("Invalid record");
  5657. SyncScope::ID SSID = getDecodedSyncScopeID(Record[1]);
  5658. I = new FenceInst(Context, Ordering, SSID);
  5659. InstructionList.push_back(I);
  5660. break;
  5661. }
  5662. case bitc::FUNC_CODE_INST_CALL: {
  5663. // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
  5664. if (Record.size() < 3)
  5665. return error("Invalid record");
  5666. unsigned OpNum = 0;
  5667. AttributeList PAL = getAttributes(Record[OpNum++]);
  5668. unsigned CCInfo = Record[OpNum++];
  5669. FastMathFlags FMF;
  5670. if ((CCInfo >> bitc::CALL_FMF) & 1) {
  5671. FMF = getDecodedFastMathFlags(Record[OpNum++]);
  5672. if (!FMF.any())
  5673. return error("Fast math flags indicator set for call with no FMF");
  5674. }
  5675. unsigned FTyID = InvalidTypeID;
  5676. FunctionType *FTy = nullptr;
  5677. if ((CCInfo >> bitc::CALL_EXPLICIT_TYPE) & 1) {
  5678. FTyID = Record[OpNum++];
  5679. FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
  5680. if (!FTy)
  5681. return error("Explicit call type is not a function type");
  5682. }
  5683. Value *Callee;
  5684. unsigned CalleeTypeID;
  5685. if (getValueTypePair(Record, OpNum, NextValueNo, Callee, CalleeTypeID,
  5686. CurBB))
  5687. return error("Invalid record");
  5688. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  5689. if (!OpTy)
  5690. return error("Callee is not a pointer type");
  5691. if (!FTy) {
  5692. FTyID = getContainedTypeID(CalleeTypeID);
  5693. FTy = dyn_cast_or_null<FunctionType>(getTypeByID(FTyID));
  5694. if (!FTy)
  5695. return error("Callee is not of pointer to function type");
  5696. } else if (!OpTy->isOpaqueOrPointeeTypeMatches(FTy))
  5697. return error("Explicit call type does not match pointee type of "
  5698. "callee operand");
  5699. if (Record.size() < FTy->getNumParams() + OpNum)
  5700. return error("Insufficient operands to call");
  5701. SmallVector<Value*, 16> Args;
  5702. SmallVector<unsigned, 16> ArgTyIDs;
  5703. // Read the fixed params.
  5704. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  5705. unsigned ArgTyID = getContainedTypeID(FTyID, i + 1);
  5706. if (FTy->getParamType(i)->isLabelTy())
  5707. Args.push_back(getBasicBlock(Record[OpNum]));
  5708. else
  5709. Args.push_back(getValue(Record, OpNum, NextValueNo,
  5710. FTy->getParamType(i), ArgTyID, CurBB));
  5711. ArgTyIDs.push_back(ArgTyID);
  5712. if (!Args.back())
  5713. return error("Invalid record");
  5714. }
  5715. // Read type/value pairs for varargs params.
  5716. if (!FTy->isVarArg()) {
  5717. if (OpNum != Record.size())
  5718. return error("Invalid record");
  5719. } else {
  5720. while (OpNum != Record.size()) {
  5721. Value *Op;
  5722. unsigned OpTypeID;
  5723. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
  5724. return error("Invalid record");
  5725. Args.push_back(Op);
  5726. ArgTyIDs.push_back(OpTypeID);
  5727. }
  5728. }
  5729. // Upgrade the bundles if needed.
  5730. if (!OperandBundles.empty())
  5731. UpgradeOperandBundles(OperandBundles);
  5732. I = CallInst::Create(FTy, Callee, Args, OperandBundles);
  5733. ResTypeID = getContainedTypeID(FTyID);
  5734. OperandBundles.clear();
  5735. InstructionList.push_back(I);
  5736. cast<CallInst>(I)->setCallingConv(
  5737. static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
  5738. CallInst::TailCallKind TCK = CallInst::TCK_None;
  5739. if (CCInfo & 1 << bitc::CALL_TAIL)
  5740. TCK = CallInst::TCK_Tail;
  5741. if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
  5742. TCK = CallInst::TCK_MustTail;
  5743. if (CCInfo & (1 << bitc::CALL_NOTAIL))
  5744. TCK = CallInst::TCK_NoTail;
  5745. cast<CallInst>(I)->setTailCallKind(TCK);
  5746. cast<CallInst>(I)->setAttributes(PAL);
  5747. if (Error Err = propagateAttributeTypes(cast<CallBase>(I), ArgTyIDs)) {
  5748. I->deleteValue();
  5749. return Err;
  5750. }
  5751. if (FMF.any()) {
  5752. if (!isa<FPMathOperator>(I))
  5753. return error("Fast-math-flags specified for call without "
  5754. "floating-point scalar or vector return type");
  5755. I->setFastMathFlags(FMF);
  5756. }
  5757. break;
  5758. }
  5759. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  5760. if (Record.size() < 3)
  5761. return error("Invalid record");
  5762. unsigned OpTyID = Record[0];
  5763. Type *OpTy = getTypeByID(OpTyID);
  5764. Value *Op = getValue(Record, 1, NextValueNo, OpTy, OpTyID, CurBB);
  5765. ResTypeID = Record[2];
  5766. Type *ResTy = getTypeByID(ResTypeID);
  5767. if (!OpTy || !Op || !ResTy)
  5768. return error("Invalid record");
  5769. I = new VAArgInst(Op, ResTy);
  5770. InstructionList.push_back(I);
  5771. break;
  5772. }
  5773. case bitc::FUNC_CODE_OPERAND_BUNDLE: {
  5774. // A call or an invoke can be optionally prefixed with some variable
  5775. // number of operand bundle blocks. These blocks are read into
  5776. // OperandBundles and consumed at the next call or invoke instruction.
  5777. if (Record.empty() || Record[0] >= BundleTags.size())
  5778. return error("Invalid record");
  5779. std::vector<Value *> Inputs;
  5780. unsigned OpNum = 1;
  5781. while (OpNum != Record.size()) {
  5782. Value *Op;
  5783. unsigned OpTypeID;
  5784. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
  5785. return error("Invalid record");
  5786. Inputs.push_back(Op);
  5787. }
  5788. OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
  5789. continue;
  5790. }
  5791. case bitc::FUNC_CODE_INST_FREEZE: { // FREEZE: [opty,opval]
  5792. unsigned OpNum = 0;
  5793. Value *Op = nullptr;
  5794. unsigned OpTypeID;
  5795. if (getValueTypePair(Record, OpNum, NextValueNo, Op, OpTypeID, CurBB))
  5796. return error("Invalid record");
  5797. if (OpNum != Record.size())
  5798. return error("Invalid record");
  5799. I = new FreezeInst(Op);
  5800. ResTypeID = OpTypeID;
  5801. InstructionList.push_back(I);
  5802. break;
  5803. }
  5804. }
  5805. // Add instruction to end of current BB. If there is no current BB, reject
  5806. // this file.
  5807. if (!CurBB) {
  5808. I->deleteValue();
  5809. return error("Invalid instruction with no BB");
  5810. }
  5811. if (!OperandBundles.empty()) {
  5812. I->deleteValue();
  5813. return error("Operand bundles found with no consumer");
  5814. }
  5815. I->insertInto(CurBB, CurBB->end());
  5816. // If this was a terminator instruction, move to the next block.
  5817. if (I->isTerminator()) {
  5818. ++CurBBNo;
  5819. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
  5820. }
  5821. // Non-void values get registered in the value table for future use.
  5822. if (!I->getType()->isVoidTy()) {
  5823. assert(I->getType() == getTypeByID(ResTypeID) &&
  5824. "Incorrect result type ID");
  5825. if (Error Err = ValueList.assignValue(NextValueNo++, I, ResTypeID))
  5826. return Err;
  5827. }
  5828. }
  5829. OutOfRecordLoop:
  5830. if (!OperandBundles.empty())
  5831. return error("Operand bundles found with no consumer");
  5832. // Check the function list for unresolved values.
  5833. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  5834. if (!A->getParent()) {
  5835. // We found at least one unresolved value. Nuke them all to avoid leaks.
  5836. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  5837. if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
  5838. A->replaceAllUsesWith(PoisonValue::get(A->getType()));
  5839. delete A;
  5840. }
  5841. }
  5842. return error("Never resolved value found in function");
  5843. }
  5844. }
  5845. // Unexpected unresolved metadata about to be dropped.
  5846. if (MDLoader->hasFwdRefs())
  5847. return error("Invalid function metadata: outgoing forward refs");
  5848. if (PhiConstExprBB)
  5849. PhiConstExprBB->eraseFromParent();
  5850. for (const auto &Pair : ConstExprEdgeBBs) {
  5851. BasicBlock *From = Pair.first.first;
  5852. BasicBlock *To = Pair.first.second;
  5853. BasicBlock *EdgeBB = Pair.second;
  5854. BranchInst::Create(To, EdgeBB);
  5855. From->getTerminator()->replaceSuccessorWith(To, EdgeBB);
  5856. To->replacePhiUsesWith(From, EdgeBB);
  5857. EdgeBB->moveBefore(To);
  5858. }
  5859. // Trim the value list down to the size it was before we parsed this function.
  5860. ValueList.shrinkTo(ModuleValueListSize);
  5861. MDLoader->shrinkTo(ModuleMDLoaderSize);
  5862. std::vector<BasicBlock*>().swap(FunctionBBs);
  5863. return Error::success();
  5864. }
  5865. /// Find the function body in the bitcode stream
  5866. Error BitcodeReader::findFunctionInStream(
  5867. Function *F,
  5868. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
  5869. while (DeferredFunctionInfoIterator->second == 0) {
  5870. // This is the fallback handling for the old format bitcode that
  5871. // didn't contain the function index in the VST, or when we have
  5872. // an anonymous function which would not have a VST entry.
  5873. // Assert that we have one of those two cases.
  5874. assert(VSTOffset == 0 || !F->hasName());
  5875. // Parse the next body in the stream and set its position in the
  5876. // DeferredFunctionInfo map.
  5877. if (Error Err = rememberAndSkipFunctionBodies())
  5878. return Err;
  5879. }
  5880. return Error::success();
  5881. }
  5882. SyncScope::ID BitcodeReader::getDecodedSyncScopeID(unsigned Val) {
  5883. if (Val == SyncScope::SingleThread || Val == SyncScope::System)
  5884. return SyncScope::ID(Val);
  5885. if (Val >= SSIDs.size())
  5886. return SyncScope::System; // Map unknown synchronization scopes to system.
  5887. return SSIDs[Val];
  5888. }
  5889. //===----------------------------------------------------------------------===//
  5890. // GVMaterializer implementation
  5891. //===----------------------------------------------------------------------===//
  5892. Error BitcodeReader::materialize(GlobalValue *GV) {
  5893. Function *F = dyn_cast<Function>(GV);
  5894. // If it's not a function or is already material, ignore the request.
  5895. if (!F || !F->isMaterializable())
  5896. return Error::success();
  5897. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  5898. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  5899. // If its position is recorded as 0, its body is somewhere in the stream
  5900. // but we haven't seen it yet.
  5901. if (DFII->second == 0)
  5902. if (Error Err = findFunctionInStream(F, DFII))
  5903. return Err;
  5904. // Materialize metadata before parsing any function bodies.
  5905. if (Error Err = materializeMetadata())
  5906. return Err;
  5907. // Move the bit stream to the saved position of the deferred function body.
  5908. if (Error JumpFailed = Stream.JumpToBit(DFII->second))
  5909. return JumpFailed;
  5910. if (Error Err = parseFunctionBody(F))
  5911. return Err;
  5912. F->setIsMaterializable(false);
  5913. if (StripDebugInfo)
  5914. stripDebugInfo(*F);
  5915. // Upgrade any old intrinsic calls in the function.
  5916. for (auto &I : UpgradedIntrinsics) {
  5917. for (User *U : llvm::make_early_inc_range(I.first->materialized_users()))
  5918. if (CallInst *CI = dyn_cast<CallInst>(U))
  5919. UpgradeIntrinsicCall(CI, I.second);
  5920. }
  5921. // Finish fn->subprogram upgrade for materialized functions.
  5922. if (DISubprogram *SP = MDLoader->lookupSubprogramForFunction(F))
  5923. F->setSubprogram(SP);
  5924. // Check if the TBAA Metadata are valid, otherwise we will need to strip them.
  5925. if (!MDLoader->isStrippingTBAA()) {
  5926. for (auto &I : instructions(F)) {
  5927. MDNode *TBAA = I.getMetadata(LLVMContext::MD_tbaa);
  5928. if (!TBAA || TBAAVerifyHelper.visitTBAAMetadata(I, TBAA))
  5929. continue;
  5930. MDLoader->setStripTBAA(true);
  5931. stripTBAA(F->getParent());
  5932. }
  5933. }
  5934. for (auto &I : instructions(F)) {
  5935. // "Upgrade" older incorrect branch weights by dropping them.
  5936. if (auto *MD = I.getMetadata(LLVMContext::MD_prof)) {
  5937. if (MD->getOperand(0) != nullptr && isa<MDString>(MD->getOperand(0))) {
  5938. MDString *MDS = cast<MDString>(MD->getOperand(0));
  5939. StringRef ProfName = MDS->getString();
  5940. // Check consistency of !prof branch_weights metadata.
  5941. if (!ProfName.equals("branch_weights"))
  5942. continue;
  5943. unsigned ExpectedNumOperands = 0;
  5944. if (BranchInst *BI = dyn_cast<BranchInst>(&I))
  5945. ExpectedNumOperands = BI->getNumSuccessors();
  5946. else if (SwitchInst *SI = dyn_cast<SwitchInst>(&I))
  5947. ExpectedNumOperands = SI->getNumSuccessors();
  5948. else if (isa<CallInst>(&I))
  5949. ExpectedNumOperands = 1;
  5950. else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(&I))
  5951. ExpectedNumOperands = IBI->getNumDestinations();
  5952. else if (isa<SelectInst>(&I))
  5953. ExpectedNumOperands = 2;
  5954. else
  5955. continue; // ignore and continue.
  5956. // If branch weight doesn't match, just strip branch weight.
  5957. if (MD->getNumOperands() != 1 + ExpectedNumOperands)
  5958. I.setMetadata(LLVMContext::MD_prof, nullptr);
  5959. }
  5960. }
  5961. // Remove incompatible attributes on function calls.
  5962. if (auto *CI = dyn_cast<CallBase>(&I)) {
  5963. CI->removeRetAttrs(AttributeFuncs::typeIncompatible(
  5964. CI->getFunctionType()->getReturnType()));
  5965. for (unsigned ArgNo = 0; ArgNo < CI->arg_size(); ++ArgNo)
  5966. CI->removeParamAttrs(ArgNo, AttributeFuncs::typeIncompatible(
  5967. CI->getArgOperand(ArgNo)->getType()));
  5968. }
  5969. }
  5970. // Look for functions that rely on old function attribute behavior.
  5971. UpgradeFunctionAttributes(*F);
  5972. // Bring in any functions that this function forward-referenced via
  5973. // blockaddresses.
  5974. return materializeForwardReferencedFunctions();
  5975. }
  5976. Error BitcodeReader::materializeModule() {
  5977. if (Error Err = materializeMetadata())
  5978. return Err;
  5979. // Promise to materialize all forward references.
  5980. WillMaterializeAllForwardRefs = true;
  5981. // Iterate over the module, deserializing any functions that are still on
  5982. // disk.
  5983. for (Function &F : *TheModule) {
  5984. if (Error Err = materialize(&F))
  5985. return Err;
  5986. }
  5987. // At this point, if there are any function bodies, parse the rest of
  5988. // the bits in the module past the last function block we have recorded
  5989. // through either lazy scanning or the VST.
  5990. if (LastFunctionBlockBit || NextUnreadBit)
  5991. if (Error Err = parseModule(LastFunctionBlockBit > NextUnreadBit
  5992. ? LastFunctionBlockBit
  5993. : NextUnreadBit))
  5994. return Err;
  5995. // Check that all block address forward references got resolved (as we
  5996. // promised above).
  5997. if (!BasicBlockFwdRefs.empty())
  5998. return error("Never resolved function from blockaddress");
  5999. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  6000. // delete the old functions to clean up. We can't do this unless the entire
  6001. // module is materialized because there could always be another function body
  6002. // with calls to the old function.
  6003. for (auto &I : UpgradedIntrinsics) {
  6004. for (auto *U : I.first->users()) {
  6005. if (CallInst *CI = dyn_cast<CallInst>(U))
  6006. UpgradeIntrinsicCall(CI, I.second);
  6007. }
  6008. if (!I.first->use_empty())
  6009. I.first->replaceAllUsesWith(I.second);
  6010. I.first->eraseFromParent();
  6011. }
  6012. UpgradedIntrinsics.clear();
  6013. UpgradeDebugInfo(*TheModule);
  6014. UpgradeModuleFlags(*TheModule);
  6015. UpgradeARCRuntime(*TheModule);
  6016. return Error::success();
  6017. }
  6018. std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
  6019. return IdentifiedStructTypes;
  6020. }
  6021. ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
  6022. BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
  6023. StringRef ModulePath, unsigned ModuleId,
  6024. std::function<bool(GlobalValue::GUID)> IsPrevailing)
  6025. : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
  6026. ModulePath(ModulePath), ModuleId(ModuleId), IsPrevailing(IsPrevailing) {}
  6027. void ModuleSummaryIndexBitcodeReader::addThisModule() {
  6028. TheIndex.addModule(ModulePath, ModuleId);
  6029. }
  6030. ModuleSummaryIndex::ModuleInfo *
  6031. ModuleSummaryIndexBitcodeReader::getThisModule() {
  6032. return TheIndex.getModule(ModulePath);
  6033. }
  6034. template <bool AllowNullValueInfo>
  6035. std::tuple<ValueInfo, GlobalValue::GUID, GlobalValue::GUID>
  6036. ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
  6037. auto VGI = ValueIdToValueInfoMap[ValueId];
  6038. // We can have a null value info for memprof callsite info records in
  6039. // distributed ThinLTO index files when the callee function summary is not
  6040. // included in the index. The bitcode writer records 0 in that case,
  6041. // and the caller of this helper will set AllowNullValueInfo to true.
  6042. assert(AllowNullValueInfo || std::get<0>(VGI));
  6043. return VGI;
  6044. }
  6045. void ModuleSummaryIndexBitcodeReader::setValueGUID(
  6046. uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
  6047. StringRef SourceFileName) {
  6048. std::string GlobalId =
  6049. GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
  6050. auto ValueGUID = GlobalValue::getGUID(GlobalId);
  6051. auto OriginalNameID = ValueGUID;
  6052. if (GlobalValue::isLocalLinkage(Linkage))
  6053. OriginalNameID = GlobalValue::getGUID(ValueName);
  6054. if (PrintSummaryGUIDs)
  6055. dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
  6056. << ValueName << "\n";
  6057. // UseStrtab is false for legacy summary formats and value names are
  6058. // created on stack. In that case we save the name in a string saver in
  6059. // the index so that the value name can be recorded.
  6060. ValueIdToValueInfoMap[ValueID] = std::make_tuple(
  6061. TheIndex.getOrInsertValueInfo(
  6062. ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
  6063. OriginalNameID, ValueGUID);
  6064. }
  6065. // Specialized value symbol table parser used when reading module index
  6066. // blocks where we don't actually create global values. The parsed information
  6067. // is saved in the bitcode reader for use when later parsing summaries.
  6068. Error ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
  6069. uint64_t Offset,
  6070. DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
  6071. // With a strtab the VST is not required to parse the summary.
  6072. if (UseStrtab)
  6073. return Error::success();
  6074. assert(Offset > 0 && "Expected non-zero VST offset");
  6075. Expected<uint64_t> MaybeCurrentBit = jumpToValueSymbolTable(Offset, Stream);
  6076. if (!MaybeCurrentBit)
  6077. return MaybeCurrentBit.takeError();
  6078. uint64_t CurrentBit = MaybeCurrentBit.get();
  6079. if (Error Err = Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  6080. return Err;
  6081. SmallVector<uint64_t, 64> Record;
  6082. // Read all the records for this value table.
  6083. SmallString<128> ValueName;
  6084. while (true) {
  6085. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  6086. if (!MaybeEntry)
  6087. return MaybeEntry.takeError();
  6088. BitstreamEntry Entry = MaybeEntry.get();
  6089. switch (Entry.Kind) {
  6090. case BitstreamEntry::SubBlock: // Handled for us already.
  6091. case BitstreamEntry::Error:
  6092. return error("Malformed block");
  6093. case BitstreamEntry::EndBlock:
  6094. // Done parsing VST, jump back to wherever we came from.
  6095. if (Error JumpFailed = Stream.JumpToBit(CurrentBit))
  6096. return JumpFailed;
  6097. return Error::success();
  6098. case BitstreamEntry::Record:
  6099. // The interesting case.
  6100. break;
  6101. }
  6102. // Read a record.
  6103. Record.clear();
  6104. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  6105. if (!MaybeRecord)
  6106. return MaybeRecord.takeError();
  6107. switch (MaybeRecord.get()) {
  6108. default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
  6109. break;
  6110. case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
  6111. if (convertToString(Record, 1, ValueName))
  6112. return error("Invalid record");
  6113. unsigned ValueID = Record[0];
  6114. assert(!SourceFileName.empty());
  6115. auto VLI = ValueIdToLinkageMap.find(ValueID);
  6116. assert(VLI != ValueIdToLinkageMap.end() &&
  6117. "No linkage found for VST entry?");
  6118. auto Linkage = VLI->second;
  6119. setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
  6120. ValueName.clear();
  6121. break;
  6122. }
  6123. case bitc::VST_CODE_FNENTRY: {
  6124. // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
  6125. if (convertToString(Record, 2, ValueName))
  6126. return error("Invalid record");
  6127. unsigned ValueID = Record[0];
  6128. assert(!SourceFileName.empty());
  6129. auto VLI = ValueIdToLinkageMap.find(ValueID);
  6130. assert(VLI != ValueIdToLinkageMap.end() &&
  6131. "No linkage found for VST entry?");
  6132. auto Linkage = VLI->second;
  6133. setValueGUID(ValueID, ValueName, Linkage, SourceFileName);
  6134. ValueName.clear();
  6135. break;
  6136. }
  6137. case bitc::VST_CODE_COMBINED_ENTRY: {
  6138. // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
  6139. unsigned ValueID = Record[0];
  6140. GlobalValue::GUID RefGUID = Record[1];
  6141. // The "original name", which is the second value of the pair will be
  6142. // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
  6143. ValueIdToValueInfoMap[ValueID] = std::make_tuple(
  6144. TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
  6145. break;
  6146. }
  6147. }
  6148. }
  6149. }
  6150. // Parse just the blocks needed for building the index out of the module.
  6151. // At the end of this routine the module Index is populated with a map
  6152. // from global value id to GlobalValueSummary objects.
  6153. Error ModuleSummaryIndexBitcodeReader::parseModule() {
  6154. if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  6155. return Err;
  6156. SmallVector<uint64_t, 64> Record;
  6157. DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
  6158. unsigned ValueId = 0;
  6159. // Read the index for this module.
  6160. while (true) {
  6161. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  6162. if (!MaybeEntry)
  6163. return MaybeEntry.takeError();
  6164. llvm::BitstreamEntry Entry = MaybeEntry.get();
  6165. switch (Entry.Kind) {
  6166. case BitstreamEntry::Error:
  6167. return error("Malformed block");
  6168. case BitstreamEntry::EndBlock:
  6169. return Error::success();
  6170. case BitstreamEntry::SubBlock:
  6171. switch (Entry.ID) {
  6172. default: // Skip unknown content.
  6173. if (Error Err = Stream.SkipBlock())
  6174. return Err;
  6175. break;
  6176. case bitc::BLOCKINFO_BLOCK_ID:
  6177. // Need to parse these to get abbrev ids (e.g. for VST)
  6178. if (Error Err = readBlockInfo())
  6179. return Err;
  6180. break;
  6181. case bitc::VALUE_SYMTAB_BLOCK_ID:
  6182. // Should have been parsed earlier via VSTOffset, unless there
  6183. // is no summary section.
  6184. assert(((SeenValueSymbolTable && VSTOffset > 0) ||
  6185. !SeenGlobalValSummary) &&
  6186. "Expected early VST parse via VSTOffset record");
  6187. if (Error Err = Stream.SkipBlock())
  6188. return Err;
  6189. break;
  6190. case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
  6191. case bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID:
  6192. // Add the module if it is a per-module index (has a source file name).
  6193. if (!SourceFileName.empty())
  6194. addThisModule();
  6195. assert(!SeenValueSymbolTable &&
  6196. "Already read VST when parsing summary block?");
  6197. // We might not have a VST if there were no values in the
  6198. // summary. An empty summary block generated when we are
  6199. // performing ThinLTO compiles so we don't later invoke
  6200. // the regular LTO process on them.
  6201. if (VSTOffset > 0) {
  6202. if (Error Err = parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
  6203. return Err;
  6204. SeenValueSymbolTable = true;
  6205. }
  6206. SeenGlobalValSummary = true;
  6207. if (Error Err = parseEntireSummary(Entry.ID))
  6208. return Err;
  6209. break;
  6210. case bitc::MODULE_STRTAB_BLOCK_ID:
  6211. if (Error Err = parseModuleStringTable())
  6212. return Err;
  6213. break;
  6214. }
  6215. continue;
  6216. case BitstreamEntry::Record: {
  6217. Record.clear();
  6218. Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
  6219. if (!MaybeBitCode)
  6220. return MaybeBitCode.takeError();
  6221. switch (MaybeBitCode.get()) {
  6222. default:
  6223. break; // Default behavior, ignore unknown content.
  6224. case bitc::MODULE_CODE_VERSION: {
  6225. if (Error Err = parseVersionRecord(Record).takeError())
  6226. return Err;
  6227. break;
  6228. }
  6229. /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  6230. case bitc::MODULE_CODE_SOURCE_FILENAME: {
  6231. SmallString<128> ValueName;
  6232. if (convertToString(Record, 0, ValueName))
  6233. return error("Invalid record");
  6234. SourceFileName = ValueName.c_str();
  6235. break;
  6236. }
  6237. /// MODULE_CODE_HASH: [5*i32]
  6238. case bitc::MODULE_CODE_HASH: {
  6239. if (Record.size() != 5)
  6240. return error("Invalid hash length " + Twine(Record.size()).str());
  6241. auto &Hash = getThisModule()->second.second;
  6242. int Pos = 0;
  6243. for (auto &Val : Record) {
  6244. assert(!(Val >> 32) && "Unexpected high bits set");
  6245. Hash[Pos++] = Val;
  6246. }
  6247. break;
  6248. }
  6249. /// MODULE_CODE_VSTOFFSET: [offset]
  6250. case bitc::MODULE_CODE_VSTOFFSET:
  6251. if (Record.empty())
  6252. return error("Invalid record");
  6253. // Note that we subtract 1 here because the offset is relative to one
  6254. // word before the start of the identification or module block, which
  6255. // was historically always the start of the regular bitcode header.
  6256. VSTOffset = Record[0] - 1;
  6257. break;
  6258. // v1 GLOBALVAR: [pointer type, isconst, initid, linkage, ...]
  6259. // v1 FUNCTION: [type, callingconv, isproto, linkage, ...]
  6260. // v1 ALIAS: [alias type, addrspace, aliasee val#, linkage, ...]
  6261. // v2: [strtab offset, strtab size, v1]
  6262. case bitc::MODULE_CODE_GLOBALVAR:
  6263. case bitc::MODULE_CODE_FUNCTION:
  6264. case bitc::MODULE_CODE_ALIAS: {
  6265. StringRef Name;
  6266. ArrayRef<uint64_t> GVRecord;
  6267. std::tie(Name, GVRecord) = readNameFromStrtab(Record);
  6268. if (GVRecord.size() <= 3)
  6269. return error("Invalid record");
  6270. uint64_t RawLinkage = GVRecord[3];
  6271. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  6272. if (!UseStrtab) {
  6273. ValueIdToLinkageMap[ValueId++] = Linkage;
  6274. break;
  6275. }
  6276. setValueGUID(ValueId++, Name, Linkage, SourceFileName);
  6277. break;
  6278. }
  6279. }
  6280. }
  6281. continue;
  6282. }
  6283. }
  6284. }
  6285. std::vector<ValueInfo>
  6286. ModuleSummaryIndexBitcodeReader::makeRefList(ArrayRef<uint64_t> Record) {
  6287. std::vector<ValueInfo> Ret;
  6288. Ret.reserve(Record.size());
  6289. for (uint64_t RefValueId : Record)
  6290. Ret.push_back(std::get<0>(getValueInfoFromValueId(RefValueId)));
  6291. return Ret;
  6292. }
  6293. std::vector<FunctionSummary::EdgeTy>
  6294. ModuleSummaryIndexBitcodeReader::makeCallList(ArrayRef<uint64_t> Record,
  6295. bool IsOldProfileFormat,
  6296. bool HasProfile, bool HasRelBF) {
  6297. std::vector<FunctionSummary::EdgeTy> Ret;
  6298. Ret.reserve(Record.size());
  6299. for (unsigned I = 0, E = Record.size(); I != E; ++I) {
  6300. CalleeInfo::HotnessType Hotness = CalleeInfo::HotnessType::Unknown;
  6301. uint64_t RelBF = 0;
  6302. ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
  6303. if (IsOldProfileFormat) {
  6304. I += 1; // Skip old callsitecount field
  6305. if (HasProfile)
  6306. I += 1; // Skip old profilecount field
  6307. } else if (HasProfile)
  6308. Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
  6309. else if (HasRelBF)
  6310. RelBF = Record[++I];
  6311. Ret.push_back(FunctionSummary::EdgeTy{Callee, CalleeInfo(Hotness, RelBF)});
  6312. }
  6313. return Ret;
  6314. }
  6315. static void
  6316. parseWholeProgramDevirtResolutionByArg(ArrayRef<uint64_t> Record, size_t &Slot,
  6317. WholeProgramDevirtResolution &Wpd) {
  6318. uint64_t ArgNum = Record[Slot++];
  6319. WholeProgramDevirtResolution::ByArg &B =
  6320. Wpd.ResByArg[{Record.begin() + Slot, Record.begin() + Slot + ArgNum}];
  6321. Slot += ArgNum;
  6322. B.TheKind =
  6323. static_cast<WholeProgramDevirtResolution::ByArg::Kind>(Record[Slot++]);
  6324. B.Info = Record[Slot++];
  6325. B.Byte = Record[Slot++];
  6326. B.Bit = Record[Slot++];
  6327. }
  6328. static void parseWholeProgramDevirtResolution(ArrayRef<uint64_t> Record,
  6329. StringRef Strtab, size_t &Slot,
  6330. TypeIdSummary &TypeId) {
  6331. uint64_t Id = Record[Slot++];
  6332. WholeProgramDevirtResolution &Wpd = TypeId.WPDRes[Id];
  6333. Wpd.TheKind = static_cast<WholeProgramDevirtResolution::Kind>(Record[Slot++]);
  6334. Wpd.SingleImplName = {Strtab.data() + Record[Slot],
  6335. static_cast<size_t>(Record[Slot + 1])};
  6336. Slot += 2;
  6337. uint64_t ResByArgNum = Record[Slot++];
  6338. for (uint64_t I = 0; I != ResByArgNum; ++I)
  6339. parseWholeProgramDevirtResolutionByArg(Record, Slot, Wpd);
  6340. }
  6341. static void parseTypeIdSummaryRecord(ArrayRef<uint64_t> Record,
  6342. StringRef Strtab,
  6343. ModuleSummaryIndex &TheIndex) {
  6344. size_t Slot = 0;
  6345. TypeIdSummary &TypeId = TheIndex.getOrInsertTypeIdSummary(
  6346. {Strtab.data() + Record[Slot], static_cast<size_t>(Record[Slot + 1])});
  6347. Slot += 2;
  6348. TypeId.TTRes.TheKind = static_cast<TypeTestResolution::Kind>(Record[Slot++]);
  6349. TypeId.TTRes.SizeM1BitWidth = Record[Slot++];
  6350. TypeId.TTRes.AlignLog2 = Record[Slot++];
  6351. TypeId.TTRes.SizeM1 = Record[Slot++];
  6352. TypeId.TTRes.BitMask = Record[Slot++];
  6353. TypeId.TTRes.InlineBits = Record[Slot++];
  6354. while (Slot < Record.size())
  6355. parseWholeProgramDevirtResolution(Record, Strtab, Slot, TypeId);
  6356. }
  6357. std::vector<FunctionSummary::ParamAccess>
  6358. ModuleSummaryIndexBitcodeReader::parseParamAccesses(ArrayRef<uint64_t> Record) {
  6359. auto ReadRange = [&]() {
  6360. APInt Lower(FunctionSummary::ParamAccess::RangeWidth,
  6361. BitcodeReader::decodeSignRotatedValue(Record.front()));
  6362. Record = Record.drop_front();
  6363. APInt Upper(FunctionSummary::ParamAccess::RangeWidth,
  6364. BitcodeReader::decodeSignRotatedValue(Record.front()));
  6365. Record = Record.drop_front();
  6366. ConstantRange Range{Lower, Upper};
  6367. assert(!Range.isFullSet());
  6368. assert(!Range.isUpperSignWrapped());
  6369. return Range;
  6370. };
  6371. std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
  6372. while (!Record.empty()) {
  6373. PendingParamAccesses.emplace_back();
  6374. FunctionSummary::ParamAccess &ParamAccess = PendingParamAccesses.back();
  6375. ParamAccess.ParamNo = Record.front();
  6376. Record = Record.drop_front();
  6377. ParamAccess.Use = ReadRange();
  6378. ParamAccess.Calls.resize(Record.front());
  6379. Record = Record.drop_front();
  6380. for (auto &Call : ParamAccess.Calls) {
  6381. Call.ParamNo = Record.front();
  6382. Record = Record.drop_front();
  6383. Call.Callee = std::get<0>(getValueInfoFromValueId(Record.front()));
  6384. Record = Record.drop_front();
  6385. Call.Offsets = ReadRange();
  6386. }
  6387. }
  6388. return PendingParamAccesses;
  6389. }
  6390. void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableInfo(
  6391. ArrayRef<uint64_t> Record, size_t &Slot,
  6392. TypeIdCompatibleVtableInfo &TypeId) {
  6393. uint64_t Offset = Record[Slot++];
  6394. ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[Slot++]));
  6395. TypeId.push_back({Offset, Callee});
  6396. }
  6397. void ModuleSummaryIndexBitcodeReader::parseTypeIdCompatibleVtableSummaryRecord(
  6398. ArrayRef<uint64_t> Record) {
  6399. size_t Slot = 0;
  6400. TypeIdCompatibleVtableInfo &TypeId =
  6401. TheIndex.getOrInsertTypeIdCompatibleVtableSummary(
  6402. {Strtab.data() + Record[Slot],
  6403. static_cast<size_t>(Record[Slot + 1])});
  6404. Slot += 2;
  6405. while (Slot < Record.size())
  6406. parseTypeIdCompatibleVtableInfo(Record, Slot, TypeId);
  6407. }
  6408. static void setSpecialRefs(std::vector<ValueInfo> &Refs, unsigned ROCnt,
  6409. unsigned WOCnt) {
  6410. // Readonly and writeonly refs are in the end of the refs list.
  6411. assert(ROCnt + WOCnt <= Refs.size());
  6412. unsigned FirstWORef = Refs.size() - WOCnt;
  6413. unsigned RefNo = FirstWORef - ROCnt;
  6414. for (; RefNo < FirstWORef; ++RefNo)
  6415. Refs[RefNo].setReadOnly();
  6416. for (; RefNo < Refs.size(); ++RefNo)
  6417. Refs[RefNo].setWriteOnly();
  6418. }
  6419. // Eagerly parse the entire summary block. This populates the GlobalValueSummary
  6420. // objects in the index.
  6421. Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
  6422. if (Error Err = Stream.EnterSubBlock(ID))
  6423. return Err;
  6424. SmallVector<uint64_t, 64> Record;
  6425. // Parse version
  6426. {
  6427. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  6428. if (!MaybeEntry)
  6429. return MaybeEntry.takeError();
  6430. BitstreamEntry Entry = MaybeEntry.get();
  6431. if (Entry.Kind != BitstreamEntry::Record)
  6432. return error("Invalid Summary Block: record for version expected");
  6433. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  6434. if (!MaybeRecord)
  6435. return MaybeRecord.takeError();
  6436. if (MaybeRecord.get() != bitc::FS_VERSION)
  6437. return error("Invalid Summary Block: version expected");
  6438. }
  6439. const uint64_t Version = Record[0];
  6440. const bool IsOldProfileFormat = Version == 1;
  6441. if (Version < 1 || Version > ModuleSummaryIndex::BitcodeSummaryVersion)
  6442. return error("Invalid summary version " + Twine(Version) +
  6443. ". Version should be in the range [1-" +
  6444. Twine(ModuleSummaryIndex::BitcodeSummaryVersion) +
  6445. "].");
  6446. Record.clear();
  6447. // Keep around the last seen summary to be used when we see an optional
  6448. // "OriginalName" attachement.
  6449. GlobalValueSummary *LastSeenSummary = nullptr;
  6450. GlobalValue::GUID LastSeenGUID = 0;
  6451. // We can expect to see any number of type ID information records before
  6452. // each function summary records; these variables store the information
  6453. // collected so far so that it can be used to create the summary object.
  6454. std::vector<GlobalValue::GUID> PendingTypeTests;
  6455. std::vector<FunctionSummary::VFuncId> PendingTypeTestAssumeVCalls,
  6456. PendingTypeCheckedLoadVCalls;
  6457. std::vector<FunctionSummary::ConstVCall> PendingTypeTestAssumeConstVCalls,
  6458. PendingTypeCheckedLoadConstVCalls;
  6459. std::vector<FunctionSummary::ParamAccess> PendingParamAccesses;
  6460. std::vector<CallsiteInfo> PendingCallsites;
  6461. std::vector<AllocInfo> PendingAllocs;
  6462. while (true) {
  6463. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  6464. if (!MaybeEntry)
  6465. return MaybeEntry.takeError();
  6466. BitstreamEntry Entry = MaybeEntry.get();
  6467. switch (Entry.Kind) {
  6468. case BitstreamEntry::SubBlock: // Handled for us already.
  6469. case BitstreamEntry::Error:
  6470. return error("Malformed block");
  6471. case BitstreamEntry::EndBlock:
  6472. return Error::success();
  6473. case BitstreamEntry::Record:
  6474. // The interesting case.
  6475. break;
  6476. }
  6477. // Read a record. The record format depends on whether this
  6478. // is a per-module index or a combined index file. In the per-module
  6479. // case the records contain the associated value's ID for correlation
  6480. // with VST entries. In the combined index the correlation is done
  6481. // via the bitcode offset of the summary records (which were saved
  6482. // in the combined index VST entries). The records also contain
  6483. // information used for ThinLTO renaming and importing.
  6484. Record.clear();
  6485. Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
  6486. if (!MaybeBitCode)
  6487. return MaybeBitCode.takeError();
  6488. switch (unsigned BitCode = MaybeBitCode.get()) {
  6489. default: // Default behavior: ignore.
  6490. break;
  6491. case bitc::FS_FLAGS: { // [flags]
  6492. TheIndex.setFlags(Record[0]);
  6493. break;
  6494. }
  6495. case bitc::FS_VALUE_GUID: { // [valueid, refguid]
  6496. uint64_t ValueID = Record[0];
  6497. GlobalValue::GUID RefGUID = Record[1];
  6498. ValueIdToValueInfoMap[ValueID] = std::make_tuple(
  6499. TheIndex.getOrInsertValueInfo(RefGUID), RefGUID, RefGUID);
  6500. break;
  6501. }
  6502. // FS_PERMODULE: [valueid, flags, instcount, fflags, numrefs,
  6503. // numrefs x valueid, n x (valueid)]
  6504. // FS_PERMODULE_PROFILE: [valueid, flags, instcount, fflags, numrefs,
  6505. // numrefs x valueid,
  6506. // n x (valueid, hotness)]
  6507. // FS_PERMODULE_RELBF: [valueid, flags, instcount, fflags, numrefs,
  6508. // numrefs x valueid,
  6509. // n x (valueid, relblockfreq)]
  6510. case bitc::FS_PERMODULE:
  6511. case bitc::FS_PERMODULE_RELBF:
  6512. case bitc::FS_PERMODULE_PROFILE: {
  6513. unsigned ValueID = Record[0];
  6514. uint64_t RawFlags = Record[1];
  6515. unsigned InstCount = Record[2];
  6516. uint64_t RawFunFlags = 0;
  6517. unsigned NumRefs = Record[3];
  6518. unsigned NumRORefs = 0, NumWORefs = 0;
  6519. int RefListStartIndex = 4;
  6520. if (Version >= 4) {
  6521. RawFunFlags = Record[3];
  6522. NumRefs = Record[4];
  6523. RefListStartIndex = 5;
  6524. if (Version >= 5) {
  6525. NumRORefs = Record[5];
  6526. RefListStartIndex = 6;
  6527. if (Version >= 7) {
  6528. NumWORefs = Record[6];
  6529. RefListStartIndex = 7;
  6530. }
  6531. }
  6532. }
  6533. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  6534. // The module path string ref set in the summary must be owned by the
  6535. // index's module string table. Since we don't have a module path
  6536. // string table section in the per-module index, we create a single
  6537. // module path string table entry with an empty (0) ID to take
  6538. // ownership.
  6539. int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
  6540. assert(Record.size() >= RefListStartIndex + NumRefs &&
  6541. "Record size inconsistent with number of references");
  6542. std::vector<ValueInfo> Refs = makeRefList(
  6543. ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
  6544. bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
  6545. bool HasRelBF = (BitCode == bitc::FS_PERMODULE_RELBF);
  6546. std::vector<FunctionSummary::EdgeTy> Calls = makeCallList(
  6547. ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
  6548. IsOldProfileFormat, HasProfile, HasRelBF);
  6549. setSpecialRefs(Refs, NumRORefs, NumWORefs);
  6550. auto VIAndOriginalGUID = getValueInfoFromValueId(ValueID);
  6551. // In order to save memory, only record the memprof summaries if this is
  6552. // the prevailing copy of a symbol. The linker doesn't resolve local
  6553. // linkage values so don't check whether those are prevailing.
  6554. auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
  6555. if (IsPrevailing &&
  6556. !GlobalValue::isLocalLinkage(LT) &&
  6557. !IsPrevailing(std::get<2>(VIAndOriginalGUID))) {
  6558. PendingCallsites.clear();
  6559. PendingAllocs.clear();
  6560. }
  6561. auto FS = std::make_unique<FunctionSummary>(
  6562. Flags, InstCount, getDecodedFFlags(RawFunFlags), /*EntryCount=*/0,
  6563. std::move(Refs), std::move(Calls), std::move(PendingTypeTests),
  6564. std::move(PendingTypeTestAssumeVCalls),
  6565. std::move(PendingTypeCheckedLoadVCalls),
  6566. std::move(PendingTypeTestAssumeConstVCalls),
  6567. std::move(PendingTypeCheckedLoadConstVCalls),
  6568. std::move(PendingParamAccesses), std::move(PendingCallsites),
  6569. std::move(PendingAllocs));
  6570. FS->setModulePath(getThisModule()->first());
  6571. FS->setOriginalName(std::get<1>(VIAndOriginalGUID));
  6572. TheIndex.addGlobalValueSummary(std::get<0>(VIAndOriginalGUID),
  6573. std::move(FS));
  6574. break;
  6575. }
  6576. // FS_ALIAS: [valueid, flags, valueid]
  6577. // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
  6578. // they expect all aliasee summaries to be available.
  6579. case bitc::FS_ALIAS: {
  6580. unsigned ValueID = Record[0];
  6581. uint64_t RawFlags = Record[1];
  6582. unsigned AliaseeID = Record[2];
  6583. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  6584. auto AS = std::make_unique<AliasSummary>(Flags);
  6585. // The module path string ref set in the summary must be owned by the
  6586. // index's module string table. Since we don't have a module path
  6587. // string table section in the per-module index, we create a single
  6588. // module path string table entry with an empty (0) ID to take
  6589. // ownership.
  6590. AS->setModulePath(getThisModule()->first());
  6591. auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeID));
  6592. auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, ModulePath);
  6593. if (!AliaseeInModule)
  6594. return error("Alias expects aliasee summary to be parsed");
  6595. AS->setAliasee(AliaseeVI, AliaseeInModule);
  6596. auto GUID = getValueInfoFromValueId(ValueID);
  6597. AS->setOriginalName(std::get<1>(GUID));
  6598. TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(AS));
  6599. break;
  6600. }
  6601. // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags, n x valueid]
  6602. case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
  6603. unsigned ValueID = Record[0];
  6604. uint64_t RawFlags = Record[1];
  6605. unsigned RefArrayStart = 2;
  6606. GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
  6607. /* WriteOnly */ false,
  6608. /* Constant */ false,
  6609. GlobalObject::VCallVisibilityPublic);
  6610. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  6611. if (Version >= 5) {
  6612. GVF = getDecodedGVarFlags(Record[2]);
  6613. RefArrayStart = 3;
  6614. }
  6615. std::vector<ValueInfo> Refs =
  6616. makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
  6617. auto FS =
  6618. std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
  6619. FS->setModulePath(getThisModule()->first());
  6620. auto GUID = getValueInfoFromValueId(ValueID);
  6621. FS->setOriginalName(std::get<1>(GUID));
  6622. TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(FS));
  6623. break;
  6624. }
  6625. // FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: [valueid, flags, varflags,
  6626. // numrefs, numrefs x valueid,
  6627. // n x (valueid, offset)]
  6628. case bitc::FS_PERMODULE_VTABLE_GLOBALVAR_INIT_REFS: {
  6629. unsigned ValueID = Record[0];
  6630. uint64_t RawFlags = Record[1];
  6631. GlobalVarSummary::GVarFlags GVF = getDecodedGVarFlags(Record[2]);
  6632. unsigned NumRefs = Record[3];
  6633. unsigned RefListStartIndex = 4;
  6634. unsigned VTableListStartIndex = RefListStartIndex + NumRefs;
  6635. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  6636. std::vector<ValueInfo> Refs = makeRefList(
  6637. ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
  6638. VTableFuncList VTableFuncs;
  6639. for (unsigned I = VTableListStartIndex, E = Record.size(); I != E; ++I) {
  6640. ValueInfo Callee = std::get<0>(getValueInfoFromValueId(Record[I]));
  6641. uint64_t Offset = Record[++I];
  6642. VTableFuncs.push_back({Callee, Offset});
  6643. }
  6644. auto VS =
  6645. std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
  6646. VS->setModulePath(getThisModule()->first());
  6647. VS->setVTableFuncs(VTableFuncs);
  6648. auto GUID = getValueInfoFromValueId(ValueID);
  6649. VS->setOriginalName(std::get<1>(GUID));
  6650. TheIndex.addGlobalValueSummary(std::get<0>(GUID), std::move(VS));
  6651. break;
  6652. }
  6653. // FS_COMBINED: [valueid, modid, flags, instcount, fflags, numrefs,
  6654. // numrefs x valueid, n x (valueid)]
  6655. // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, fflags, numrefs,
  6656. // numrefs x valueid, n x (valueid, hotness)]
  6657. case bitc::FS_COMBINED:
  6658. case bitc::FS_COMBINED_PROFILE: {
  6659. unsigned ValueID = Record[0];
  6660. uint64_t ModuleId = Record[1];
  6661. uint64_t RawFlags = Record[2];
  6662. unsigned InstCount = Record[3];
  6663. uint64_t RawFunFlags = 0;
  6664. uint64_t EntryCount = 0;
  6665. unsigned NumRefs = Record[4];
  6666. unsigned NumRORefs = 0, NumWORefs = 0;
  6667. int RefListStartIndex = 5;
  6668. if (Version >= 4) {
  6669. RawFunFlags = Record[4];
  6670. RefListStartIndex = 6;
  6671. size_t NumRefsIndex = 5;
  6672. if (Version >= 5) {
  6673. unsigned NumRORefsOffset = 1;
  6674. RefListStartIndex = 7;
  6675. if (Version >= 6) {
  6676. NumRefsIndex = 6;
  6677. EntryCount = Record[5];
  6678. RefListStartIndex = 8;
  6679. if (Version >= 7) {
  6680. RefListStartIndex = 9;
  6681. NumWORefs = Record[8];
  6682. NumRORefsOffset = 2;
  6683. }
  6684. }
  6685. NumRORefs = Record[RefListStartIndex - NumRORefsOffset];
  6686. }
  6687. NumRefs = Record[NumRefsIndex];
  6688. }
  6689. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  6690. int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
  6691. assert(Record.size() >= RefListStartIndex + NumRefs &&
  6692. "Record size inconsistent with number of references");
  6693. std::vector<ValueInfo> Refs = makeRefList(
  6694. ArrayRef<uint64_t>(Record).slice(RefListStartIndex, NumRefs));
  6695. bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
  6696. std::vector<FunctionSummary::EdgeTy> Edges = makeCallList(
  6697. ArrayRef<uint64_t>(Record).slice(CallGraphEdgeStartIndex),
  6698. IsOldProfileFormat, HasProfile, false);
  6699. ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
  6700. setSpecialRefs(Refs, NumRORefs, NumWORefs);
  6701. auto FS = std::make_unique<FunctionSummary>(
  6702. Flags, InstCount, getDecodedFFlags(RawFunFlags), EntryCount,
  6703. std::move(Refs), std::move(Edges), std::move(PendingTypeTests),
  6704. std::move(PendingTypeTestAssumeVCalls),
  6705. std::move(PendingTypeCheckedLoadVCalls),
  6706. std::move(PendingTypeTestAssumeConstVCalls),
  6707. std::move(PendingTypeCheckedLoadConstVCalls),
  6708. std::move(PendingParamAccesses), std::move(PendingCallsites),
  6709. std::move(PendingAllocs));
  6710. LastSeenSummary = FS.get();
  6711. LastSeenGUID = VI.getGUID();
  6712. FS->setModulePath(ModuleIdMap[ModuleId]);
  6713. TheIndex.addGlobalValueSummary(VI, std::move(FS));
  6714. break;
  6715. }
  6716. // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
  6717. // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
  6718. // they expect all aliasee summaries to be available.
  6719. case bitc::FS_COMBINED_ALIAS: {
  6720. unsigned ValueID = Record[0];
  6721. uint64_t ModuleId = Record[1];
  6722. uint64_t RawFlags = Record[2];
  6723. unsigned AliaseeValueId = Record[3];
  6724. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  6725. auto AS = std::make_unique<AliasSummary>(Flags);
  6726. LastSeenSummary = AS.get();
  6727. AS->setModulePath(ModuleIdMap[ModuleId]);
  6728. auto AliaseeVI = std::get<0>(getValueInfoFromValueId(AliaseeValueId));
  6729. auto AliaseeInModule = TheIndex.findSummaryInModule(AliaseeVI, AS->modulePath());
  6730. AS->setAliasee(AliaseeVI, AliaseeInModule);
  6731. ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
  6732. LastSeenGUID = VI.getGUID();
  6733. TheIndex.addGlobalValueSummary(VI, std::move(AS));
  6734. break;
  6735. }
  6736. // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
  6737. case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
  6738. unsigned ValueID = Record[0];
  6739. uint64_t ModuleId = Record[1];
  6740. uint64_t RawFlags = Record[2];
  6741. unsigned RefArrayStart = 3;
  6742. GlobalVarSummary::GVarFlags GVF(/* ReadOnly */ false,
  6743. /* WriteOnly */ false,
  6744. /* Constant */ false,
  6745. GlobalObject::VCallVisibilityPublic);
  6746. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  6747. if (Version >= 5) {
  6748. GVF = getDecodedGVarFlags(Record[3]);
  6749. RefArrayStart = 4;
  6750. }
  6751. std::vector<ValueInfo> Refs =
  6752. makeRefList(ArrayRef<uint64_t>(Record).slice(RefArrayStart));
  6753. auto FS =
  6754. std::make_unique<GlobalVarSummary>(Flags, GVF, std::move(Refs));
  6755. LastSeenSummary = FS.get();
  6756. FS->setModulePath(ModuleIdMap[ModuleId]);
  6757. ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
  6758. LastSeenGUID = VI.getGUID();
  6759. TheIndex.addGlobalValueSummary(VI, std::move(FS));
  6760. break;
  6761. }
  6762. // FS_COMBINED_ORIGINAL_NAME: [original_name]
  6763. case bitc::FS_COMBINED_ORIGINAL_NAME: {
  6764. uint64_t OriginalName = Record[0];
  6765. if (!LastSeenSummary)
  6766. return error("Name attachment that does not follow a combined record");
  6767. LastSeenSummary->setOriginalName(OriginalName);
  6768. TheIndex.addOriginalName(LastSeenGUID, OriginalName);
  6769. // Reset the LastSeenSummary
  6770. LastSeenSummary = nullptr;
  6771. LastSeenGUID = 0;
  6772. break;
  6773. }
  6774. case bitc::FS_TYPE_TESTS:
  6775. assert(PendingTypeTests.empty());
  6776. llvm::append_range(PendingTypeTests, Record);
  6777. break;
  6778. case bitc::FS_TYPE_TEST_ASSUME_VCALLS:
  6779. assert(PendingTypeTestAssumeVCalls.empty());
  6780. for (unsigned I = 0; I != Record.size(); I += 2)
  6781. PendingTypeTestAssumeVCalls.push_back({Record[I], Record[I+1]});
  6782. break;
  6783. case bitc::FS_TYPE_CHECKED_LOAD_VCALLS:
  6784. assert(PendingTypeCheckedLoadVCalls.empty());
  6785. for (unsigned I = 0; I != Record.size(); I += 2)
  6786. PendingTypeCheckedLoadVCalls.push_back({Record[I], Record[I+1]});
  6787. break;
  6788. case bitc::FS_TYPE_TEST_ASSUME_CONST_VCALL:
  6789. PendingTypeTestAssumeConstVCalls.push_back(
  6790. {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
  6791. break;
  6792. case bitc::FS_TYPE_CHECKED_LOAD_CONST_VCALL:
  6793. PendingTypeCheckedLoadConstVCalls.push_back(
  6794. {{Record[0], Record[1]}, {Record.begin() + 2, Record.end()}});
  6795. break;
  6796. case bitc::FS_CFI_FUNCTION_DEFS: {
  6797. std::set<std::string> &CfiFunctionDefs = TheIndex.cfiFunctionDefs();
  6798. for (unsigned I = 0; I != Record.size(); I += 2)
  6799. CfiFunctionDefs.insert(
  6800. {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
  6801. break;
  6802. }
  6803. case bitc::FS_CFI_FUNCTION_DECLS: {
  6804. std::set<std::string> &CfiFunctionDecls = TheIndex.cfiFunctionDecls();
  6805. for (unsigned I = 0; I != Record.size(); I += 2)
  6806. CfiFunctionDecls.insert(
  6807. {Strtab.data() + Record[I], static_cast<size_t>(Record[I + 1])});
  6808. break;
  6809. }
  6810. case bitc::FS_TYPE_ID:
  6811. parseTypeIdSummaryRecord(Record, Strtab, TheIndex);
  6812. break;
  6813. case bitc::FS_TYPE_ID_METADATA:
  6814. parseTypeIdCompatibleVtableSummaryRecord(Record);
  6815. break;
  6816. case bitc::FS_BLOCK_COUNT:
  6817. TheIndex.addBlockCount(Record[0]);
  6818. break;
  6819. case bitc::FS_PARAM_ACCESS: {
  6820. PendingParamAccesses = parseParamAccesses(Record);
  6821. break;
  6822. }
  6823. case bitc::FS_STACK_IDS: { // [n x stackid]
  6824. // Save stack ids in the reader to consult when adding stack ids from the
  6825. // lists in the stack node and alloc node entries.
  6826. StackIds = ArrayRef<uint64_t>(Record);
  6827. break;
  6828. }
  6829. case bitc::FS_PERMODULE_CALLSITE_INFO: {
  6830. unsigned ValueID = Record[0];
  6831. SmallVector<unsigned> StackIdList;
  6832. for (auto R = Record.begin() + 1; R != Record.end(); R++) {
  6833. assert(*R < StackIds.size());
  6834. StackIdList.push_back(TheIndex.addOrGetStackIdIndex(StackIds[*R]));
  6835. }
  6836. ValueInfo VI = std::get<0>(getValueInfoFromValueId(ValueID));
  6837. PendingCallsites.push_back(CallsiteInfo({VI, std::move(StackIdList)}));
  6838. break;
  6839. }
  6840. case bitc::FS_COMBINED_CALLSITE_INFO: {
  6841. auto RecordIter = Record.begin();
  6842. unsigned ValueID = *RecordIter++;
  6843. unsigned NumStackIds = *RecordIter++;
  6844. unsigned NumVersions = *RecordIter++;
  6845. assert(Record.size() == 3 + NumStackIds + NumVersions);
  6846. SmallVector<unsigned> StackIdList;
  6847. for (unsigned J = 0; J < NumStackIds; J++) {
  6848. assert(*RecordIter < StackIds.size());
  6849. StackIdList.push_back(
  6850. TheIndex.addOrGetStackIdIndex(StackIds[*RecordIter++]));
  6851. }
  6852. SmallVector<unsigned> Versions;
  6853. for (unsigned J = 0; J < NumVersions; J++)
  6854. Versions.push_back(*RecordIter++);
  6855. ValueInfo VI = std::get<0>(
  6856. getValueInfoFromValueId</*AllowNullValueInfo*/ true>(ValueID));
  6857. PendingCallsites.push_back(
  6858. CallsiteInfo({VI, std::move(Versions), std::move(StackIdList)}));
  6859. break;
  6860. }
  6861. case bitc::FS_PERMODULE_ALLOC_INFO: {
  6862. unsigned I = 0;
  6863. std::vector<MIBInfo> MIBs;
  6864. while (I < Record.size()) {
  6865. assert(Record.size() - I >= 2);
  6866. AllocationType AllocType = (AllocationType)Record[I++];
  6867. unsigned NumStackEntries = Record[I++];
  6868. assert(Record.size() - I >= NumStackEntries);
  6869. SmallVector<unsigned> StackIdList;
  6870. for (unsigned J = 0; J < NumStackEntries; J++) {
  6871. assert(Record[I] < StackIds.size());
  6872. StackIdList.push_back(
  6873. TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
  6874. }
  6875. MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
  6876. }
  6877. PendingAllocs.push_back(AllocInfo(std::move(MIBs)));
  6878. break;
  6879. }
  6880. case bitc::FS_COMBINED_ALLOC_INFO: {
  6881. unsigned I = 0;
  6882. std::vector<MIBInfo> MIBs;
  6883. unsigned NumMIBs = Record[I++];
  6884. unsigned NumVersions = Record[I++];
  6885. unsigned MIBsRead = 0;
  6886. while (MIBsRead++ < NumMIBs) {
  6887. assert(Record.size() - I >= 2);
  6888. AllocationType AllocType = (AllocationType)Record[I++];
  6889. unsigned NumStackEntries = Record[I++];
  6890. assert(Record.size() - I >= NumStackEntries);
  6891. SmallVector<unsigned> StackIdList;
  6892. for (unsigned J = 0; J < NumStackEntries; J++) {
  6893. assert(Record[I] < StackIds.size());
  6894. StackIdList.push_back(
  6895. TheIndex.addOrGetStackIdIndex(StackIds[Record[I++]]));
  6896. }
  6897. MIBs.push_back(MIBInfo(AllocType, std::move(StackIdList)));
  6898. }
  6899. assert(Record.size() - I >= NumVersions);
  6900. SmallVector<uint8_t> Versions;
  6901. for (unsigned J = 0; J < NumVersions; J++)
  6902. Versions.push_back(Record[I++]);
  6903. PendingAllocs.push_back(
  6904. AllocInfo(std::move(Versions), std::move(MIBs)));
  6905. break;
  6906. }
  6907. }
  6908. }
  6909. llvm_unreachable("Exit infinite loop");
  6910. }
  6911. // Parse the module string table block into the Index.
  6912. // This populates the ModulePathStringTable map in the index.
  6913. Error ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
  6914. if (Error Err = Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
  6915. return Err;
  6916. SmallVector<uint64_t, 64> Record;
  6917. SmallString<128> ModulePath;
  6918. ModuleSummaryIndex::ModuleInfo *LastSeenModule = nullptr;
  6919. while (true) {
  6920. Expected<BitstreamEntry> MaybeEntry = Stream.advanceSkippingSubblocks();
  6921. if (!MaybeEntry)
  6922. return MaybeEntry.takeError();
  6923. BitstreamEntry Entry = MaybeEntry.get();
  6924. switch (Entry.Kind) {
  6925. case BitstreamEntry::SubBlock: // Handled for us already.
  6926. case BitstreamEntry::Error:
  6927. return error("Malformed block");
  6928. case BitstreamEntry::EndBlock:
  6929. return Error::success();
  6930. case BitstreamEntry::Record:
  6931. // The interesting case.
  6932. break;
  6933. }
  6934. Record.clear();
  6935. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record);
  6936. if (!MaybeRecord)
  6937. return MaybeRecord.takeError();
  6938. switch (MaybeRecord.get()) {
  6939. default: // Default behavior: ignore.
  6940. break;
  6941. case bitc::MST_CODE_ENTRY: {
  6942. // MST_ENTRY: [modid, namechar x N]
  6943. uint64_t ModuleId = Record[0];
  6944. if (convertToString(Record, 1, ModulePath))
  6945. return error("Invalid record");
  6946. LastSeenModule = TheIndex.addModule(ModulePath, ModuleId);
  6947. ModuleIdMap[ModuleId] = LastSeenModule->first();
  6948. ModulePath.clear();
  6949. break;
  6950. }
  6951. /// MST_CODE_HASH: [5*i32]
  6952. case bitc::MST_CODE_HASH: {
  6953. if (Record.size() != 5)
  6954. return error("Invalid hash length " + Twine(Record.size()).str());
  6955. if (!LastSeenModule)
  6956. return error("Invalid hash that does not follow a module path");
  6957. int Pos = 0;
  6958. for (auto &Val : Record) {
  6959. assert(!(Val >> 32) && "Unexpected high bits set");
  6960. LastSeenModule->second.second[Pos++] = Val;
  6961. }
  6962. // Reset LastSeenModule to avoid overriding the hash unexpectedly.
  6963. LastSeenModule = nullptr;
  6964. break;
  6965. }
  6966. }
  6967. }
  6968. llvm_unreachable("Exit infinite loop");
  6969. }
  6970. namespace {
  6971. // FIXME: This class is only here to support the transition to llvm::Error. It
  6972. // will be removed once this transition is complete. Clients should prefer to
  6973. // deal with the Error value directly, rather than converting to error_code.
  6974. class BitcodeErrorCategoryType : public std::error_category {
  6975. const char *name() const noexcept override {
  6976. return "llvm.bitcode";
  6977. }
  6978. std::string message(int IE) const override {
  6979. BitcodeError E = static_cast<BitcodeError>(IE);
  6980. switch (E) {
  6981. case BitcodeError::CorruptedBitcode:
  6982. return "Corrupted bitcode";
  6983. }
  6984. llvm_unreachable("Unknown error type!");
  6985. }
  6986. };
  6987. } // end anonymous namespace
  6988. const std::error_category &llvm::BitcodeErrorCategory() {
  6989. static BitcodeErrorCategoryType ErrorCategory;
  6990. return ErrorCategory;
  6991. }
  6992. static Expected<StringRef> readBlobInRecord(BitstreamCursor &Stream,
  6993. unsigned Block, unsigned RecordID) {
  6994. if (Error Err = Stream.EnterSubBlock(Block))
  6995. return std::move(Err);
  6996. StringRef Strtab;
  6997. while (true) {
  6998. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  6999. if (!MaybeEntry)
  7000. return MaybeEntry.takeError();
  7001. llvm::BitstreamEntry Entry = MaybeEntry.get();
  7002. switch (Entry.Kind) {
  7003. case BitstreamEntry::EndBlock:
  7004. return Strtab;
  7005. case BitstreamEntry::Error:
  7006. return error("Malformed block");
  7007. case BitstreamEntry::SubBlock:
  7008. if (Error Err = Stream.SkipBlock())
  7009. return std::move(Err);
  7010. break;
  7011. case BitstreamEntry::Record:
  7012. StringRef Blob;
  7013. SmallVector<uint64_t, 1> Record;
  7014. Expected<unsigned> MaybeRecord =
  7015. Stream.readRecord(Entry.ID, Record, &Blob);
  7016. if (!MaybeRecord)
  7017. return MaybeRecord.takeError();
  7018. if (MaybeRecord.get() == RecordID)
  7019. Strtab = Blob;
  7020. break;
  7021. }
  7022. }
  7023. }
  7024. //===----------------------------------------------------------------------===//
  7025. // External interface
  7026. //===----------------------------------------------------------------------===//
  7027. Expected<std::vector<BitcodeModule>>
  7028. llvm::getBitcodeModuleList(MemoryBufferRef Buffer) {
  7029. auto FOrErr = getBitcodeFileContents(Buffer);
  7030. if (!FOrErr)
  7031. return FOrErr.takeError();
  7032. return std::move(FOrErr->Mods);
  7033. }
  7034. Expected<BitcodeFileContents>
  7035. llvm::getBitcodeFileContents(MemoryBufferRef Buffer) {
  7036. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  7037. if (!StreamOrErr)
  7038. return StreamOrErr.takeError();
  7039. BitstreamCursor &Stream = *StreamOrErr;
  7040. BitcodeFileContents F;
  7041. while (true) {
  7042. uint64_t BCBegin = Stream.getCurrentByteNo();
  7043. // We may be consuming bitcode from a client that leaves garbage at the end
  7044. // of the bitcode stream (e.g. Apple's ar tool). If we are close enough to
  7045. // the end that there cannot possibly be another module, stop looking.
  7046. if (BCBegin + 8 >= Stream.getBitcodeBytes().size())
  7047. return F;
  7048. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  7049. if (!MaybeEntry)
  7050. return MaybeEntry.takeError();
  7051. llvm::BitstreamEntry Entry = MaybeEntry.get();
  7052. switch (Entry.Kind) {
  7053. case BitstreamEntry::EndBlock:
  7054. case BitstreamEntry::Error:
  7055. return error("Malformed block");
  7056. case BitstreamEntry::SubBlock: {
  7057. uint64_t IdentificationBit = -1ull;
  7058. if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
  7059. IdentificationBit = Stream.GetCurrentBitNo() - BCBegin * 8;
  7060. if (Error Err = Stream.SkipBlock())
  7061. return std::move(Err);
  7062. {
  7063. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  7064. if (!MaybeEntry)
  7065. return MaybeEntry.takeError();
  7066. Entry = MaybeEntry.get();
  7067. }
  7068. if (Entry.Kind != BitstreamEntry::SubBlock ||
  7069. Entry.ID != bitc::MODULE_BLOCK_ID)
  7070. return error("Malformed block");
  7071. }
  7072. if (Entry.ID == bitc::MODULE_BLOCK_ID) {
  7073. uint64_t ModuleBit = Stream.GetCurrentBitNo() - BCBegin * 8;
  7074. if (Error Err = Stream.SkipBlock())
  7075. return std::move(Err);
  7076. F.Mods.push_back({Stream.getBitcodeBytes().slice(
  7077. BCBegin, Stream.getCurrentByteNo() - BCBegin),
  7078. Buffer.getBufferIdentifier(), IdentificationBit,
  7079. ModuleBit});
  7080. continue;
  7081. }
  7082. if (Entry.ID == bitc::STRTAB_BLOCK_ID) {
  7083. Expected<StringRef> Strtab =
  7084. readBlobInRecord(Stream, bitc::STRTAB_BLOCK_ID, bitc::STRTAB_BLOB);
  7085. if (!Strtab)
  7086. return Strtab.takeError();
  7087. // This string table is used by every preceding bitcode module that does
  7088. // not have its own string table. A bitcode file may have multiple
  7089. // string tables if it was created by binary concatenation, for example
  7090. // with "llvm-cat -b".
  7091. for (BitcodeModule &I : llvm::reverse(F.Mods)) {
  7092. if (!I.Strtab.empty())
  7093. break;
  7094. I.Strtab = *Strtab;
  7095. }
  7096. // Similarly, the string table is used by every preceding symbol table;
  7097. // normally there will be just one unless the bitcode file was created
  7098. // by binary concatenation.
  7099. if (!F.Symtab.empty() && F.StrtabForSymtab.empty())
  7100. F.StrtabForSymtab = *Strtab;
  7101. continue;
  7102. }
  7103. if (Entry.ID == bitc::SYMTAB_BLOCK_ID) {
  7104. Expected<StringRef> SymtabOrErr =
  7105. readBlobInRecord(Stream, bitc::SYMTAB_BLOCK_ID, bitc::SYMTAB_BLOB);
  7106. if (!SymtabOrErr)
  7107. return SymtabOrErr.takeError();
  7108. // We can expect the bitcode file to have multiple symbol tables if it
  7109. // was created by binary concatenation. In that case we silently
  7110. // ignore any subsequent symbol tables, which is fine because this is a
  7111. // low level function. The client is expected to notice that the number
  7112. // of modules in the symbol table does not match the number of modules
  7113. // in the input file and regenerate the symbol table.
  7114. if (F.Symtab.empty())
  7115. F.Symtab = *SymtabOrErr;
  7116. continue;
  7117. }
  7118. if (Error Err = Stream.SkipBlock())
  7119. return std::move(Err);
  7120. continue;
  7121. }
  7122. case BitstreamEntry::Record:
  7123. if (Error E = Stream.skipRecord(Entry.ID).takeError())
  7124. return std::move(E);
  7125. continue;
  7126. }
  7127. }
  7128. }
  7129. /// Get a lazy one-at-time loading module from bitcode.
  7130. ///
  7131. /// This isn't always used in a lazy context. In particular, it's also used by
  7132. /// \a parseModule(). If this is truly lazy, then we need to eagerly pull
  7133. /// in forward-referenced functions from block address references.
  7134. ///
  7135. /// \param[in] MaterializeAll Set to \c true if we should materialize
  7136. /// everything.
  7137. Expected<std::unique_ptr<Module>>
  7138. BitcodeModule::getModuleImpl(LLVMContext &Context, bool MaterializeAll,
  7139. bool ShouldLazyLoadMetadata, bool IsImporting,
  7140. ParserCallbacks Callbacks) {
  7141. BitstreamCursor Stream(Buffer);
  7142. std::string ProducerIdentification;
  7143. if (IdentificationBit != -1ull) {
  7144. if (Error JumpFailed = Stream.JumpToBit(IdentificationBit))
  7145. return std::move(JumpFailed);
  7146. if (Error E =
  7147. readIdentificationBlock(Stream).moveInto(ProducerIdentification))
  7148. return std::move(E);
  7149. }
  7150. if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
  7151. return std::move(JumpFailed);
  7152. auto *R = new BitcodeReader(std::move(Stream), Strtab, ProducerIdentification,
  7153. Context);
  7154. std::unique_ptr<Module> M =
  7155. std::make_unique<Module>(ModuleIdentifier, Context);
  7156. M->setMaterializer(R);
  7157. // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
  7158. if (Error Err = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata,
  7159. IsImporting, Callbacks))
  7160. return std::move(Err);
  7161. if (MaterializeAll) {
  7162. // Read in the entire module, and destroy the BitcodeReader.
  7163. if (Error Err = M->materializeAll())
  7164. return std::move(Err);
  7165. } else {
  7166. // Resolve forward references from blockaddresses.
  7167. if (Error Err = R->materializeForwardReferencedFunctions())
  7168. return std::move(Err);
  7169. }
  7170. return std::move(M);
  7171. }
  7172. Expected<std::unique_ptr<Module>>
  7173. BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
  7174. bool IsImporting, ParserCallbacks Callbacks) {
  7175. return getModuleImpl(Context, false, ShouldLazyLoadMetadata, IsImporting,
  7176. Callbacks);
  7177. }
  7178. // Parse the specified bitcode buffer and merge the index into CombinedIndex.
  7179. // We don't use ModuleIdentifier here because the client may need to control the
  7180. // module path used in the combined summary (e.g. when reading summaries for
  7181. // regular LTO modules).
  7182. Error BitcodeModule::readSummary(
  7183. ModuleSummaryIndex &CombinedIndex, StringRef ModulePath, uint64_t ModuleId,
  7184. std::function<bool(GlobalValue::GUID)> IsPrevailing) {
  7185. BitstreamCursor Stream(Buffer);
  7186. if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
  7187. return JumpFailed;
  7188. ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
  7189. ModulePath, ModuleId, IsPrevailing);
  7190. return R.parseModule();
  7191. }
  7192. // Parse the specified bitcode buffer, returning the function info index.
  7193. Expected<std::unique_ptr<ModuleSummaryIndex>> BitcodeModule::getSummary() {
  7194. BitstreamCursor Stream(Buffer);
  7195. if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
  7196. return std::move(JumpFailed);
  7197. auto Index = std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
  7198. ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, *Index,
  7199. ModuleIdentifier, 0);
  7200. if (Error Err = R.parseModule())
  7201. return std::move(Err);
  7202. return std::move(Index);
  7203. }
  7204. static Expected<bool> getEnableSplitLTOUnitFlag(BitstreamCursor &Stream,
  7205. unsigned ID) {
  7206. if (Error Err = Stream.EnterSubBlock(ID))
  7207. return std::move(Err);
  7208. SmallVector<uint64_t, 64> Record;
  7209. while (true) {
  7210. BitstreamEntry Entry;
  7211. if (Error E = Stream.advanceSkippingSubblocks().moveInto(Entry))
  7212. return std::move(E);
  7213. switch (Entry.Kind) {
  7214. case BitstreamEntry::SubBlock: // Handled for us already.
  7215. case BitstreamEntry::Error:
  7216. return error("Malformed block");
  7217. case BitstreamEntry::EndBlock:
  7218. // If no flags record found, conservatively return true to mimic
  7219. // behavior before this flag was added.
  7220. return true;
  7221. case BitstreamEntry::Record:
  7222. // The interesting case.
  7223. break;
  7224. }
  7225. // Look for the FS_FLAGS record.
  7226. Record.clear();
  7227. Expected<unsigned> MaybeBitCode = Stream.readRecord(Entry.ID, Record);
  7228. if (!MaybeBitCode)
  7229. return MaybeBitCode.takeError();
  7230. switch (MaybeBitCode.get()) {
  7231. default: // Default behavior: ignore.
  7232. break;
  7233. case bitc::FS_FLAGS: { // [flags]
  7234. uint64_t Flags = Record[0];
  7235. // Scan flags.
  7236. assert(Flags <= 0xff && "Unexpected bits in flag");
  7237. return Flags & 0x8;
  7238. }
  7239. }
  7240. }
  7241. llvm_unreachable("Exit infinite loop");
  7242. }
  7243. // Check if the given bitcode buffer contains a global value summary block.
  7244. Expected<BitcodeLTOInfo> BitcodeModule::getLTOInfo() {
  7245. BitstreamCursor Stream(Buffer);
  7246. if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
  7247. return std::move(JumpFailed);
  7248. if (Error Err = Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  7249. return std::move(Err);
  7250. while (true) {
  7251. llvm::BitstreamEntry Entry;
  7252. if (Error E = Stream.advance().moveInto(Entry))
  7253. return std::move(E);
  7254. switch (Entry.Kind) {
  7255. case BitstreamEntry::Error:
  7256. return error("Malformed block");
  7257. case BitstreamEntry::EndBlock:
  7258. return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/false,
  7259. /*EnableSplitLTOUnit=*/false};
  7260. case BitstreamEntry::SubBlock:
  7261. if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
  7262. Expected<bool> EnableSplitLTOUnit =
  7263. getEnableSplitLTOUnitFlag(Stream, Entry.ID);
  7264. if (!EnableSplitLTOUnit)
  7265. return EnableSplitLTOUnit.takeError();
  7266. return BitcodeLTOInfo{/*IsThinLTO=*/true, /*HasSummary=*/true,
  7267. *EnableSplitLTOUnit};
  7268. }
  7269. if (Entry.ID == bitc::FULL_LTO_GLOBALVAL_SUMMARY_BLOCK_ID) {
  7270. Expected<bool> EnableSplitLTOUnit =
  7271. getEnableSplitLTOUnitFlag(Stream, Entry.ID);
  7272. if (!EnableSplitLTOUnit)
  7273. return EnableSplitLTOUnit.takeError();
  7274. return BitcodeLTOInfo{/*IsThinLTO=*/false, /*HasSummary=*/true,
  7275. *EnableSplitLTOUnit};
  7276. }
  7277. // Ignore other sub-blocks.
  7278. if (Error Err = Stream.SkipBlock())
  7279. return std::move(Err);
  7280. continue;
  7281. case BitstreamEntry::Record:
  7282. if (Expected<unsigned> StreamFailed = Stream.skipRecord(Entry.ID))
  7283. continue;
  7284. else
  7285. return StreamFailed.takeError();
  7286. }
  7287. }
  7288. }
  7289. static Expected<BitcodeModule> getSingleModule(MemoryBufferRef Buffer) {
  7290. Expected<std::vector<BitcodeModule>> MsOrErr = getBitcodeModuleList(Buffer);
  7291. if (!MsOrErr)
  7292. return MsOrErr.takeError();
  7293. if (MsOrErr->size() != 1)
  7294. return error("Expected a single module");
  7295. return (*MsOrErr)[0];
  7296. }
  7297. Expected<std::unique_ptr<Module>>
  7298. llvm::getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context,
  7299. bool ShouldLazyLoadMetadata, bool IsImporting,
  7300. ParserCallbacks Callbacks) {
  7301. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  7302. if (!BM)
  7303. return BM.takeError();
  7304. return BM->getLazyModule(Context, ShouldLazyLoadMetadata, IsImporting,
  7305. Callbacks);
  7306. }
  7307. Expected<std::unique_ptr<Module>> llvm::getOwningLazyBitcodeModule(
  7308. std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
  7309. bool ShouldLazyLoadMetadata, bool IsImporting, ParserCallbacks Callbacks) {
  7310. auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata,
  7311. IsImporting, Callbacks);
  7312. if (MOrErr)
  7313. (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
  7314. return MOrErr;
  7315. }
  7316. Expected<std::unique_ptr<Module>>
  7317. BitcodeModule::parseModule(LLVMContext &Context, ParserCallbacks Callbacks) {
  7318. return getModuleImpl(Context, true, false, false, Callbacks);
  7319. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  7320. // written. We must defer until the Module has been fully materialized.
  7321. }
  7322. Expected<std::unique_ptr<Module>>
  7323. llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
  7324. ParserCallbacks Callbacks) {
  7325. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  7326. if (!BM)
  7327. return BM.takeError();
  7328. return BM->parseModule(Context, Callbacks);
  7329. }
  7330. Expected<std::string> llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer) {
  7331. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  7332. if (!StreamOrErr)
  7333. return StreamOrErr.takeError();
  7334. return readTriple(*StreamOrErr);
  7335. }
  7336. Expected<bool> llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer) {
  7337. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  7338. if (!StreamOrErr)
  7339. return StreamOrErr.takeError();
  7340. return hasObjCCategory(*StreamOrErr);
  7341. }
  7342. Expected<std::string> llvm::getBitcodeProducerString(MemoryBufferRef Buffer) {
  7343. Expected<BitstreamCursor> StreamOrErr = initStream(Buffer);
  7344. if (!StreamOrErr)
  7345. return StreamOrErr.takeError();
  7346. return readIdentificationCode(*StreamOrErr);
  7347. }
  7348. Error llvm::readModuleSummaryIndex(MemoryBufferRef Buffer,
  7349. ModuleSummaryIndex &CombinedIndex,
  7350. uint64_t ModuleId) {
  7351. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  7352. if (!BM)
  7353. return BM.takeError();
  7354. return BM->readSummary(CombinedIndex, BM->getModuleIdentifier(), ModuleId);
  7355. }
  7356. Expected<std::unique_ptr<ModuleSummaryIndex>>
  7357. llvm::getModuleSummaryIndex(MemoryBufferRef Buffer) {
  7358. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  7359. if (!BM)
  7360. return BM.takeError();
  7361. return BM->getSummary();
  7362. }
  7363. Expected<BitcodeLTOInfo> llvm::getBitcodeLTOInfo(MemoryBufferRef Buffer) {
  7364. Expected<BitcodeModule> BM = getSingleModule(Buffer);
  7365. if (!BM)
  7366. return BM.takeError();
  7367. return BM->getLTOInfo();
  7368. }
  7369. Expected<std::unique_ptr<ModuleSummaryIndex>>
  7370. llvm::getModuleSummaryIndexForFile(StringRef Path,
  7371. bool IgnoreEmptyThinLTOIndexFile) {
  7372. ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
  7373. MemoryBuffer::getFileOrSTDIN(Path);
  7374. if (!FileOrErr)
  7375. return errorCodeToError(FileOrErr.getError());
  7376. if (IgnoreEmptyThinLTOIndexFile && !(*FileOrErr)->getBufferSize())
  7377. return nullptr;
  7378. return getModuleSummaryIndex(**FileOrErr);
  7379. }