BitcodeReader.cpp 239 KB

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