BitcodeReader.cpp 170 KB

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