BitcodeReader.cpp 140 KB

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