BitcodeReader.cpp 254 KB

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