BitcodeReader.cpp 207 KB

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