BitcodeReader.cpp 160 KB

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