BitcodeReader.cpp 214 KB

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