BitcodeReader.cpp 170 KB

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