BitcodeReader.cpp 212 KB

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