BitcodeReader.cpp 240 KB

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