BitcodeReader.cpp 212 KB

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