MetadataLoader.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807
  1. //===- MetadataLoader.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 "MetadataLoader.h"
  10. #include "ValueList.h"
  11. #include "llvm/ADT/APFloat.h"
  12. #include "llvm/ADT/APInt.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/None.h"
  17. #include "llvm/ADT/STLExtras.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ADT/Triple.h"
  23. #include "llvm/ADT/Twine.h"
  24. #include "llvm/Bitcode/BitcodeReader.h"
  25. #include "llvm/Bitcode/BitstreamReader.h"
  26. #include "llvm/Bitcode/LLVMBitCodes.h"
  27. #include "llvm/IR/Argument.h"
  28. #include "llvm/IR/Attributes.h"
  29. #include "llvm/IR/AutoUpgrade.h"
  30. #include "llvm/IR/BasicBlock.h"
  31. #include "llvm/IR/CallSite.h"
  32. #include "llvm/IR/CallingConv.h"
  33. #include "llvm/IR/Comdat.h"
  34. #include "llvm/IR/Constant.h"
  35. #include "llvm/IR/Constants.h"
  36. #include "llvm/IR/DebugInfo.h"
  37. #include "llvm/IR/DebugInfoMetadata.h"
  38. #include "llvm/IR/DebugLoc.h"
  39. #include "llvm/IR/DerivedTypes.h"
  40. #include "llvm/IR/DiagnosticInfo.h"
  41. #include "llvm/IR/DiagnosticPrinter.h"
  42. #include "llvm/IR/Function.h"
  43. #include "llvm/IR/GVMaterializer.h"
  44. #include "llvm/IR/GlobalAlias.h"
  45. #include "llvm/IR/GlobalIFunc.h"
  46. #include "llvm/IR/GlobalIndirectSymbol.h"
  47. #include "llvm/IR/GlobalObject.h"
  48. #include "llvm/IR/GlobalValue.h"
  49. #include "llvm/IR/GlobalVariable.h"
  50. #include "llvm/IR/InlineAsm.h"
  51. #include "llvm/IR/InstrTypes.h"
  52. #include "llvm/IR/Instruction.h"
  53. #include "llvm/IR/Instructions.h"
  54. #include "llvm/IR/Intrinsics.h"
  55. #include "llvm/IR/LLVMContext.h"
  56. #include "llvm/IR/Module.h"
  57. #include "llvm/IR/ModuleSummaryIndex.h"
  58. #include "llvm/IR/OperandTraits.h"
  59. #include "llvm/IR/Operator.h"
  60. #include "llvm/IR/TrackingMDRef.h"
  61. #include "llvm/IR/Type.h"
  62. #include "llvm/IR/ValueHandle.h"
  63. #include "llvm/Support/AtomicOrdering.h"
  64. #include "llvm/Support/Casting.h"
  65. #include "llvm/Support/CommandLine.h"
  66. #include "llvm/Support/Compiler.h"
  67. #include "llvm/Support/Debug.h"
  68. #include "llvm/Support/Error.h"
  69. #include "llvm/Support/ErrorHandling.h"
  70. #include "llvm/Support/ManagedStatic.h"
  71. #include "llvm/Support/MemoryBuffer.h"
  72. #include "llvm/Support/raw_ostream.h"
  73. #include <algorithm>
  74. #include <cassert>
  75. #include <cstddef>
  76. #include <cstdint>
  77. #include <deque>
  78. #include <limits>
  79. #include <map>
  80. #include <memory>
  81. #include <string>
  82. #include <system_error>
  83. #include <tuple>
  84. #include <utility>
  85. #include <vector>
  86. using namespace llvm;
  87. #define DEBUG_TYPE "bitcode-reader"
  88. STATISTIC(NumMDStringLoaded, "Number of MDStrings loaded");
  89. STATISTIC(NumMDNodeTemporary, "Number of MDNode::Temporary created");
  90. STATISTIC(NumMDRecordLoaded, "Number of Metadata records loaded");
  91. /// Flag whether we need to import full type definitions for ThinLTO.
  92. /// Currently needed for Darwin and LLDB.
  93. static cl::opt<bool> ImportFullTypeDefinitions(
  94. "import-full-type-definitions", cl::init(false), cl::Hidden,
  95. cl::desc("Import full type definitions for ThinLTO."));
  96. static cl::opt<bool> DisableLazyLoading(
  97. "disable-ondemand-mds-loading", cl::init(false), cl::Hidden,
  98. cl::desc("Force disable the lazy-loading on-demand of metadata when "
  99. "loading bitcode for importing."));
  100. namespace {
  101. static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
  102. class BitcodeReaderMetadataList {
  103. /// Array of metadata references.
  104. ///
  105. /// Don't use std::vector here. Some versions of libc++ copy (instead of
  106. /// move) on resize, and TrackingMDRef is very expensive to copy.
  107. SmallVector<TrackingMDRef, 1> MetadataPtrs;
  108. /// The set of indices in MetadataPtrs above of forward references that were
  109. /// generated.
  110. SmallDenseSet<unsigned, 1> ForwardReference;
  111. /// The set of indices in MetadataPtrs above of Metadata that need to be
  112. /// resolved.
  113. SmallDenseSet<unsigned, 1> UnresolvedNodes;
  114. /// Structures for resolving old type refs.
  115. struct {
  116. SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
  117. SmallDenseMap<MDString *, DICompositeType *, 1> Final;
  118. SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
  119. SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
  120. } OldTypeRefs;
  121. LLVMContext &Context;
  122. public:
  123. BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {}
  124. // vector compatibility methods
  125. unsigned size() const { return MetadataPtrs.size(); }
  126. void resize(unsigned N) { MetadataPtrs.resize(N); }
  127. void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
  128. void clear() { MetadataPtrs.clear(); }
  129. Metadata *back() const { return MetadataPtrs.back(); }
  130. void pop_back() { MetadataPtrs.pop_back(); }
  131. bool empty() const { return MetadataPtrs.empty(); }
  132. Metadata *operator[](unsigned i) const {
  133. assert(i < MetadataPtrs.size());
  134. return MetadataPtrs[i];
  135. }
  136. Metadata *lookup(unsigned I) const {
  137. if (I < MetadataPtrs.size())
  138. return MetadataPtrs[I];
  139. return nullptr;
  140. }
  141. void shrinkTo(unsigned N) {
  142. assert(N <= size() && "Invalid shrinkTo request!");
  143. assert(ForwardReference.empty() && "Unexpected forward refs");
  144. assert(UnresolvedNodes.empty() && "Unexpected unresolved node");
  145. MetadataPtrs.resize(N);
  146. }
  147. /// Return the given metadata, creating a replaceable forward reference if
  148. /// necessary.
  149. Metadata *getMetadataFwdRef(unsigned Idx);
  150. /// Return the the given metadata only if it is fully resolved.
  151. ///
  152. /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
  153. /// would give \c false.
  154. Metadata *getMetadataIfResolved(unsigned Idx);
  155. MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
  156. void assignValue(Metadata *MD, unsigned Idx);
  157. void tryToResolveCycles();
  158. bool hasFwdRefs() const { return !ForwardReference.empty(); }
  159. int getNextFwdRef() {
  160. assert(hasFwdRefs());
  161. return *ForwardReference.begin();
  162. }
  163. /// Upgrade a type that had an MDString reference.
  164. void addTypeRef(MDString &UUID, DICompositeType &CT);
  165. /// Upgrade a type that had an MDString reference.
  166. Metadata *upgradeTypeRef(Metadata *MaybeUUID);
  167. /// Upgrade a type ref array that may have MDString references.
  168. Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
  169. private:
  170. Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
  171. };
  172. void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
  173. if (auto *MDN = dyn_cast<MDNode>(MD))
  174. if (!MDN->isResolved())
  175. UnresolvedNodes.insert(Idx);
  176. if (Idx == size()) {
  177. push_back(MD);
  178. return;
  179. }
  180. if (Idx >= size())
  181. resize(Idx + 1);
  182. TrackingMDRef &OldMD = MetadataPtrs[Idx];
  183. if (!OldMD) {
  184. OldMD.reset(MD);
  185. return;
  186. }
  187. // If there was a forward reference to this value, replace it.
  188. TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
  189. PrevMD->replaceAllUsesWith(MD);
  190. ForwardReference.erase(Idx);
  191. }
  192. Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
  193. if (Idx >= size())
  194. resize(Idx + 1);
  195. if (Metadata *MD = MetadataPtrs[Idx])
  196. return MD;
  197. // Track forward refs to be resolved later.
  198. ForwardReference.insert(Idx);
  199. // Create and return a placeholder, which will later be RAUW'd.
  200. ++NumMDNodeTemporary;
  201. Metadata *MD = MDNode::getTemporary(Context, None).release();
  202. MetadataPtrs[Idx].reset(MD);
  203. return MD;
  204. }
  205. Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
  206. Metadata *MD = lookup(Idx);
  207. if (auto *N = dyn_cast_or_null<MDNode>(MD))
  208. if (!N->isResolved())
  209. return nullptr;
  210. return MD;
  211. }
  212. MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
  213. return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
  214. }
  215. void BitcodeReaderMetadataList::tryToResolveCycles() {
  216. if (!ForwardReference.empty())
  217. // Still forward references... can't resolve cycles.
  218. return;
  219. // Give up on finding a full definition for any forward decls that remain.
  220. for (const auto &Ref : OldTypeRefs.FwdDecls)
  221. OldTypeRefs.Final.insert(Ref);
  222. OldTypeRefs.FwdDecls.clear();
  223. // Upgrade from old type ref arrays. In strange cases, this could add to
  224. // OldTypeRefs.Unknown.
  225. for (const auto &Array : OldTypeRefs.Arrays)
  226. Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
  227. OldTypeRefs.Arrays.clear();
  228. // Replace old string-based type refs with the resolved node, if possible.
  229. // If we haven't seen the node, leave it to the verifier to complain about
  230. // the invalid string reference.
  231. for (const auto &Ref : OldTypeRefs.Unknown) {
  232. if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
  233. Ref.second->replaceAllUsesWith(CT);
  234. else
  235. Ref.second->replaceAllUsesWith(Ref.first);
  236. }
  237. OldTypeRefs.Unknown.clear();
  238. if (UnresolvedNodes.empty())
  239. // Nothing to do.
  240. return;
  241. // Resolve any cycles.
  242. for (unsigned I : UnresolvedNodes) {
  243. auto &MD = MetadataPtrs[I];
  244. auto *N = dyn_cast_or_null<MDNode>(MD);
  245. if (!N)
  246. continue;
  247. assert(!N->isTemporary() && "Unexpected forward reference");
  248. N->resolveCycles();
  249. }
  250. // Make sure we return early again until there's another unresolved ref.
  251. UnresolvedNodes.clear();
  252. }
  253. void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
  254. DICompositeType &CT) {
  255. assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
  256. if (CT.isForwardDecl())
  257. OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
  258. else
  259. OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
  260. }
  261. Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
  262. auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
  263. if (LLVM_LIKELY(!UUID))
  264. return MaybeUUID;
  265. if (auto *CT = OldTypeRefs.Final.lookup(UUID))
  266. return CT;
  267. auto &Ref = OldTypeRefs.Unknown[UUID];
  268. if (!Ref)
  269. Ref = MDNode::getTemporary(Context, None);
  270. return Ref.get();
  271. }
  272. Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
  273. auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
  274. if (!Tuple || Tuple->isDistinct())
  275. return MaybeTuple;
  276. // Look through the array immediately if possible.
  277. if (!Tuple->isTemporary())
  278. return resolveTypeRefArray(Tuple);
  279. // Create and return a placeholder to use for now. Eventually
  280. // resolveTypeRefArrays() will be resolve this forward reference.
  281. OldTypeRefs.Arrays.emplace_back(
  282. std::piecewise_construct, std::forward_as_tuple(Tuple),
  283. std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
  284. return OldTypeRefs.Arrays.back().second.get();
  285. }
  286. Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
  287. auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
  288. if (!Tuple || Tuple->isDistinct())
  289. return MaybeTuple;
  290. // Look through the DITypeRefArray, upgrading each DITypeRef.
  291. SmallVector<Metadata *, 32> Ops;
  292. Ops.reserve(Tuple->getNumOperands());
  293. for (Metadata *MD : Tuple->operands())
  294. Ops.push_back(upgradeTypeRef(MD));
  295. return MDTuple::get(Context, Ops);
  296. }
  297. namespace {
  298. class PlaceholderQueue {
  299. // Placeholders would thrash around when moved, so store in a std::deque
  300. // instead of some sort of vector.
  301. std::deque<DistinctMDOperandPlaceholder> PHs;
  302. public:
  303. ~PlaceholderQueue() {
  304. assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed");
  305. }
  306. bool empty() { return PHs.empty(); }
  307. DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
  308. void flush(BitcodeReaderMetadataList &MetadataList);
  309. /// Return the list of temporaries nodes in the queue, these need to be
  310. /// loaded before we can flush the queue.
  311. void getTemporaries(BitcodeReaderMetadataList &MetadataList,
  312. DenseSet<unsigned> &Temporaries) {
  313. for (auto &PH : PHs) {
  314. auto ID = PH.getID();
  315. auto *MD = MetadataList.lookup(ID);
  316. if (!MD) {
  317. Temporaries.insert(ID);
  318. continue;
  319. }
  320. auto *N = dyn_cast_or_null<MDNode>(MD);
  321. if (N && N->isTemporary())
  322. Temporaries.insert(ID);
  323. }
  324. }
  325. };
  326. } // end anonymous namespace
  327. DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
  328. PHs.emplace_back(ID);
  329. return PHs.back();
  330. }
  331. void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
  332. while (!PHs.empty()) {
  333. auto *MD = MetadataList.lookup(PHs.front().getID());
  334. assert(MD && "Flushing placeholder on unassigned MD");
  335. #ifndef NDEBUG
  336. if (auto *MDN = dyn_cast<MDNode>(MD))
  337. assert(MDN->isResolved() &&
  338. "Flushing Placeholder while cycles aren't resolved");
  339. #endif
  340. PHs.front().replaceUseWith(MD);
  341. PHs.pop_front();
  342. }
  343. }
  344. } // anonynous namespace
  345. class MetadataLoader::MetadataLoaderImpl {
  346. BitcodeReaderMetadataList MetadataList;
  347. BitcodeReaderValueList &ValueList;
  348. BitstreamCursor &Stream;
  349. LLVMContext &Context;
  350. Module &TheModule;
  351. std::function<Type *(unsigned)> getTypeByID;
  352. /// Cursor associated with the lazy-loading of Metadata. This is the easy way
  353. /// to keep around the right "context" (Abbrev list) to be able to jump in
  354. /// the middle of the metadata block and load any record.
  355. BitstreamCursor IndexCursor;
  356. /// Index that keeps track of MDString values.
  357. std::vector<StringRef> MDStringRef;
  358. /// On-demand loading of a single MDString. Requires the index above to be
  359. /// populated.
  360. MDString *lazyLoadOneMDString(unsigned Idx);
  361. /// Index that keeps track of where to find a metadata record in the stream.
  362. std::vector<uint64_t> GlobalMetadataBitPosIndex;
  363. /// Populate the index above to enable lazily loading of metadata, and load
  364. /// the named metadata as well as the transitively referenced global
  365. /// Metadata.
  366. Expected<bool> lazyLoadModuleMetadataBlock();
  367. /// On-demand loading of a single metadata. Requires the index above to be
  368. /// populated.
  369. void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders);
  370. // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to
  371. // point from SP to CU after a block is completly parsed.
  372. std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
  373. /// Functions that need to be matched with subprograms when upgrading old
  374. /// metadata.
  375. SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
  376. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  377. DenseMap<unsigned, unsigned> MDKindMap;
  378. bool StripTBAA = false;
  379. bool HasSeenOldLoopTags = false;
  380. /// True if metadata is being parsed for a module being ThinLTO imported.
  381. bool IsImporting = false;
  382. Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code,
  383. PlaceholderQueue &Placeholders, StringRef Blob,
  384. unsigned &NextMetadataNo);
  385. Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob,
  386. function_ref<void(StringRef)> CallBack);
  387. Error parseGlobalObjectAttachment(GlobalObject &GO,
  388. ArrayRef<uint64_t> Record);
  389. Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
  390. void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders);
  391. /// Upgrade old-style CU <-> SP pointers to point from SP to CU.
  392. void upgradeCUSubprograms() {
  393. for (auto CU_SP : CUSubprograms)
  394. if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
  395. for (auto &Op : SPs->operands())
  396. if (auto *SP = dyn_cast_or_null<MDNode>(Op))
  397. SP->replaceOperandWith(7, CU_SP.first);
  398. CUSubprograms.clear();
  399. }
  400. public:
  401. MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule,
  402. BitcodeReaderValueList &ValueList,
  403. std::function<Type *(unsigned)> getTypeByID,
  404. bool IsImporting)
  405. : MetadataList(TheModule.getContext()), ValueList(ValueList),
  406. Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule),
  407. getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {}
  408. Error parseMetadata(bool ModuleLevel);
  409. bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); }
  410. Metadata *getMetadataFwdRefOrLoad(unsigned ID) {
  411. if (ID < MDStringRef.size())
  412. return lazyLoadOneMDString(ID);
  413. if (auto *MD = MetadataList.lookup(ID))
  414. return MD;
  415. // If lazy-loading is enabled, we try recursively to load the operand
  416. // instead of creating a temporary.
  417. if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
  418. PlaceholderQueue Placeholders;
  419. lazyLoadOneMetadata(ID, Placeholders);
  420. resolveForwardRefsAndPlaceholders(Placeholders);
  421. return MetadataList.lookup(ID);
  422. }
  423. return MetadataList.getMetadataFwdRef(ID);
  424. }
  425. MDNode *getMDNodeFwdRefOrNull(unsigned Idx) {
  426. return MetadataList.getMDNodeFwdRefOrNull(Idx);
  427. }
  428. DISubprogram *lookupSubprogramForFunction(Function *F) {
  429. return FunctionsWithSPs.lookup(F);
  430. }
  431. bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; }
  432. Error parseMetadataAttachment(
  433. Function &F, const SmallVectorImpl<Instruction *> &InstructionList);
  434. Error parseMetadataKinds();
  435. void setStripTBAA(bool Value) { StripTBAA = Value; }
  436. bool isStrippingTBAA() { return StripTBAA; }
  437. unsigned size() const { return MetadataList.size(); }
  438. void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); }
  439. };
  440. Error error(const Twine &Message) {
  441. return make_error<StringError>(
  442. Message, make_error_code(BitcodeError::CorruptedBitcode));
  443. }
  444. Expected<bool>
  445. MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() {
  446. IndexCursor = Stream;
  447. SmallVector<uint64_t, 64> Record;
  448. // Get the abbrevs, and preload record positions to make them lazy-loadable.
  449. while (true) {
  450. BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks(
  451. BitstreamCursor::AF_DontPopBlockAtEnd);
  452. switch (Entry.Kind) {
  453. case BitstreamEntry::SubBlock: // Handled for us already.
  454. case BitstreamEntry::Error:
  455. return error("Malformed block");
  456. case BitstreamEntry::EndBlock: {
  457. return true;
  458. }
  459. case BitstreamEntry::Record: {
  460. // The interesting case.
  461. ++NumMDRecordLoaded;
  462. uint64_t CurrentPos = IndexCursor.GetCurrentBitNo();
  463. auto Code = IndexCursor.skipRecord(Entry.ID);
  464. switch (Code) {
  465. case bitc::METADATA_STRINGS: {
  466. // Rewind and parse the strings.
  467. IndexCursor.JumpToBit(CurrentPos);
  468. StringRef Blob;
  469. Record.clear();
  470. IndexCursor.readRecord(Entry.ID, Record, &Blob);
  471. unsigned NumStrings = Record[0];
  472. MDStringRef.reserve(NumStrings);
  473. auto IndexNextMDString = [&](StringRef Str) {
  474. MDStringRef.push_back(Str);
  475. };
  476. if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString))
  477. return std::move(Err);
  478. break;
  479. }
  480. case bitc::METADATA_INDEX_OFFSET: {
  481. // This is the offset to the index, when we see this we skip all the
  482. // records and load only an index to these.
  483. IndexCursor.JumpToBit(CurrentPos);
  484. Record.clear();
  485. IndexCursor.readRecord(Entry.ID, Record);
  486. if (Record.size() != 2)
  487. return error("Invalid record");
  488. auto Offset = Record[0] + (Record[1] << 32);
  489. auto BeginPos = IndexCursor.GetCurrentBitNo();
  490. IndexCursor.JumpToBit(BeginPos + Offset);
  491. Entry = IndexCursor.advanceSkippingSubblocks(
  492. BitstreamCursor::AF_DontPopBlockAtEnd);
  493. assert(Entry.Kind == BitstreamEntry::Record &&
  494. "Corrupted bitcode: Expected `Record` when trying to find the "
  495. "Metadata index");
  496. Record.clear();
  497. auto Code = IndexCursor.readRecord(Entry.ID, Record);
  498. (void)Code;
  499. assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected "
  500. "`METADATA_INDEX` when trying "
  501. "to find the Metadata index");
  502. // Delta unpack
  503. auto CurrentValue = BeginPos;
  504. GlobalMetadataBitPosIndex.reserve(Record.size());
  505. for (auto &Elt : Record) {
  506. CurrentValue += Elt;
  507. GlobalMetadataBitPosIndex.push_back(CurrentValue);
  508. }
  509. break;
  510. }
  511. case bitc::METADATA_INDEX:
  512. // We don't expect to get there, the Index is loaded when we encounter
  513. // the offset.
  514. return error("Corrupted Metadata block");
  515. case bitc::METADATA_NAME: {
  516. // Named metadata need to be materialized now and aren't deferred.
  517. IndexCursor.JumpToBit(CurrentPos);
  518. Record.clear();
  519. unsigned Code = IndexCursor.readRecord(Entry.ID, Record);
  520. assert(Code == bitc::METADATA_NAME);
  521. // Read name of the named metadata.
  522. SmallString<8> Name(Record.begin(), Record.end());
  523. Code = IndexCursor.ReadCode();
  524. // Named Metadata comes in two parts, we expect the name to be followed
  525. // by the node
  526. Record.clear();
  527. unsigned NextBitCode = IndexCursor.readRecord(Code, Record);
  528. assert(NextBitCode == bitc::METADATA_NAMED_NODE);
  529. (void)NextBitCode;
  530. // Read named metadata elements.
  531. unsigned Size = Record.size();
  532. NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
  533. for (unsigned i = 0; i != Size; ++i) {
  534. // FIXME: We could use a placeholder here, however NamedMDNode are
  535. // taking MDNode as operand and not using the Metadata infrastructure.
  536. // It is acknowledged by 'TODO: Inherit from Metadata' in the
  537. // NamedMDNode class definition.
  538. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
  539. assert(MD && "Invalid record");
  540. NMD->addOperand(MD);
  541. }
  542. break;
  543. }
  544. case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
  545. // FIXME: we need to do this early because we don't materialize global
  546. // value explicitly.
  547. IndexCursor.JumpToBit(CurrentPos);
  548. Record.clear();
  549. IndexCursor.readRecord(Entry.ID, Record);
  550. if (Record.size() % 2 == 0)
  551. return error("Invalid record");
  552. unsigned ValueID = Record[0];
  553. if (ValueID >= ValueList.size())
  554. return error("Invalid record");
  555. if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
  556. if (Error Err = parseGlobalObjectAttachment(
  557. *GO, ArrayRef<uint64_t>(Record).slice(1)))
  558. return std::move(Err);
  559. break;
  560. }
  561. case bitc::METADATA_KIND:
  562. case bitc::METADATA_STRING_OLD:
  563. case bitc::METADATA_OLD_FN_NODE:
  564. case bitc::METADATA_OLD_NODE:
  565. case bitc::METADATA_VALUE:
  566. case bitc::METADATA_DISTINCT_NODE:
  567. case bitc::METADATA_NODE:
  568. case bitc::METADATA_LOCATION:
  569. case bitc::METADATA_GENERIC_DEBUG:
  570. case bitc::METADATA_SUBRANGE:
  571. case bitc::METADATA_ENUMERATOR:
  572. case bitc::METADATA_BASIC_TYPE:
  573. case bitc::METADATA_DERIVED_TYPE:
  574. case bitc::METADATA_COMPOSITE_TYPE:
  575. case bitc::METADATA_SUBROUTINE_TYPE:
  576. case bitc::METADATA_MODULE:
  577. case bitc::METADATA_FILE:
  578. case bitc::METADATA_COMPILE_UNIT:
  579. case bitc::METADATA_SUBPROGRAM:
  580. case bitc::METADATA_LEXICAL_BLOCK:
  581. case bitc::METADATA_LEXICAL_BLOCK_FILE:
  582. case bitc::METADATA_NAMESPACE:
  583. case bitc::METADATA_MACRO:
  584. case bitc::METADATA_MACRO_FILE:
  585. case bitc::METADATA_TEMPLATE_TYPE:
  586. case bitc::METADATA_TEMPLATE_VALUE:
  587. case bitc::METADATA_GLOBAL_VAR:
  588. case bitc::METADATA_LOCAL_VAR:
  589. case bitc::METADATA_EXPRESSION:
  590. case bitc::METADATA_OBJC_PROPERTY:
  591. case bitc::METADATA_IMPORTED_ENTITY:
  592. case bitc::METADATA_GLOBAL_VAR_EXPR:
  593. // We don't expect to see any of these, if we see one, give up on
  594. // lazy-loading and fallback.
  595. MDStringRef.clear();
  596. GlobalMetadataBitPosIndex.clear();
  597. return false;
  598. }
  599. break;
  600. }
  601. }
  602. }
  603. }
  604. /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
  605. /// module level metadata.
  606. Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) {
  607. if (!ModuleLevel && MetadataList.hasFwdRefs())
  608. return error("Invalid metadata: fwd refs into function blocks");
  609. // Record the entry position so that we can jump back here and efficiently
  610. // skip the whole block in case we lazy-load.
  611. auto EntryPos = Stream.GetCurrentBitNo();
  612. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  613. return error("Invalid record");
  614. SmallVector<uint64_t, 64> Record;
  615. PlaceholderQueue Placeholders;
  616. // We lazy-load module-level metadata: we build an index for each record, and
  617. // then load individual record as needed, starting with the named metadata.
  618. if (ModuleLevel && IsImporting && MetadataList.empty() &&
  619. !DisableLazyLoading) {
  620. auto SuccessOrErr = lazyLoadModuleMetadataBlock();
  621. if (!SuccessOrErr)
  622. return SuccessOrErr.takeError();
  623. if (SuccessOrErr.get()) {
  624. // An index was successfully created and we will be able to load metadata
  625. // on-demand.
  626. MetadataList.resize(MDStringRef.size() +
  627. GlobalMetadataBitPosIndex.size());
  628. // Reading the named metadata created forward references and/or
  629. // placeholders, that we flush here.
  630. resolveForwardRefsAndPlaceholders(Placeholders);
  631. upgradeCUSubprograms();
  632. // Return at the beginning of the block, since it is easy to skip it
  633. // entirely from there.
  634. Stream.ReadBlockEnd(); // Pop the abbrev block context.
  635. Stream.JumpToBit(EntryPos);
  636. if (Stream.SkipBlock())
  637. return error("Invalid record");
  638. return Error::success();
  639. }
  640. // Couldn't load an index, fallback to loading all the block "old-style".
  641. }
  642. unsigned NextMetadataNo = MetadataList.size();
  643. // Read all the records.
  644. while (true) {
  645. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  646. switch (Entry.Kind) {
  647. case BitstreamEntry::SubBlock: // Handled for us already.
  648. case BitstreamEntry::Error:
  649. return error("Malformed block");
  650. case BitstreamEntry::EndBlock:
  651. resolveForwardRefsAndPlaceholders(Placeholders);
  652. upgradeCUSubprograms();
  653. return Error::success();
  654. case BitstreamEntry::Record:
  655. // The interesting case.
  656. break;
  657. }
  658. // Read a record.
  659. Record.clear();
  660. StringRef Blob;
  661. ++NumMDRecordLoaded;
  662. unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
  663. if (Error Err =
  664. parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo))
  665. return Err;
  666. }
  667. }
  668. MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) {
  669. ++NumMDStringLoaded;
  670. if (Metadata *MD = MetadataList.lookup(ID))
  671. return cast<MDString>(MD);
  672. auto MDS = MDString::get(Context, MDStringRef[ID]);
  673. MetadataList.assignValue(MDS, ID);
  674. return MDS;
  675. }
  676. void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata(
  677. unsigned ID, PlaceholderQueue &Placeholders) {
  678. assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size());
  679. assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString");
  680. // Lookup first if the metadata hasn't already been loaded.
  681. if (auto *MD = MetadataList.lookup(ID)) {
  682. auto *N = dyn_cast_or_null<MDNode>(MD);
  683. if (!N->isTemporary())
  684. return;
  685. }
  686. SmallVector<uint64_t, 64> Record;
  687. StringRef Blob;
  688. IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]);
  689. auto Entry = IndexCursor.advanceSkippingSubblocks();
  690. ++NumMDRecordLoaded;
  691. unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob);
  692. if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID))
  693. report_fatal_error("Can't lazyload MD");
  694. }
  695. /// Ensure that all forward-references and placeholders are resolved.
  696. /// Iteratively lazy-loading metadata on-demand if needed.
  697. void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders(
  698. PlaceholderQueue &Placeholders) {
  699. DenseSet<unsigned> Temporaries;
  700. while (1) {
  701. // Populate Temporaries with the placeholders that haven't been loaded yet.
  702. Placeholders.getTemporaries(MetadataList, Temporaries);
  703. // If we don't have any temporary, or FwdReference, we're done!
  704. if (Temporaries.empty() && !MetadataList.hasFwdRefs())
  705. break;
  706. // First, load all the temporaries. This can add new placeholders or
  707. // forward references.
  708. for (auto ID : Temporaries)
  709. lazyLoadOneMetadata(ID, Placeholders);
  710. Temporaries.clear();
  711. // Second, load the forward-references. This can also add new placeholders
  712. // or forward references.
  713. while (MetadataList.hasFwdRefs())
  714. lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders);
  715. }
  716. // At this point we don't have any forward reference remaining, or temporary
  717. // that haven't been loaded. We can safely drop RAUW support and mark cycles
  718. // as resolved.
  719. MetadataList.tryToResolveCycles();
  720. // Finally, everything is in place, we can replace the placeholders operands
  721. // with the final node they refer to.
  722. Placeholders.flush(MetadataList);
  723. }
  724. Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata(
  725. SmallVectorImpl<uint64_t> &Record, unsigned Code,
  726. PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) {
  727. bool IsDistinct = false;
  728. auto getMD = [&](unsigned ID) -> Metadata * {
  729. if (ID < MDStringRef.size())
  730. return lazyLoadOneMDString(ID);
  731. if (!IsDistinct) {
  732. if (auto *MD = MetadataList.lookup(ID))
  733. return MD;
  734. // If lazy-loading is enabled, we try recursively to load the operand
  735. // instead of creating a temporary.
  736. if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) {
  737. // Create a temporary for the node that is referencing the operand we
  738. // will lazy-load. It is needed before recursing in case there are
  739. // uniquing cycles.
  740. MetadataList.getMetadataFwdRef(NextMetadataNo);
  741. lazyLoadOneMetadata(ID, Placeholders);
  742. return MetadataList.lookup(ID);
  743. }
  744. // Return a temporary.
  745. return MetadataList.getMetadataFwdRef(ID);
  746. }
  747. if (auto *MD = MetadataList.getMetadataIfResolved(ID))
  748. return MD;
  749. return &Placeholders.getPlaceholderOp(ID);
  750. };
  751. auto getMDOrNull = [&](unsigned ID) -> Metadata * {
  752. if (ID)
  753. return getMD(ID - 1);
  754. return nullptr;
  755. };
  756. auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
  757. if (ID)
  758. return MetadataList.getMetadataFwdRef(ID - 1);
  759. return nullptr;
  760. };
  761. auto getMDString = [&](unsigned ID) -> MDString * {
  762. // This requires that the ID is not really a forward reference. In
  763. // particular, the MDString must already have been resolved.
  764. auto MDS = getMDOrNull(ID);
  765. return cast_or_null<MDString>(MDS);
  766. };
  767. // Support for old type refs.
  768. auto getDITypeRefOrNull = [&](unsigned ID) {
  769. return MetadataList.upgradeTypeRef(getMDOrNull(ID));
  770. };
  771. #define GET_OR_DISTINCT(CLASS, ARGS) \
  772. (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  773. switch (Code) {
  774. default: // Default behavior: ignore.
  775. break;
  776. case bitc::METADATA_NAME: {
  777. // Read name of the named metadata.
  778. SmallString<8> Name(Record.begin(), Record.end());
  779. Record.clear();
  780. Code = Stream.ReadCode();
  781. ++NumMDRecordLoaded;
  782. unsigned NextBitCode = Stream.readRecord(Code, Record);
  783. if (NextBitCode != bitc::METADATA_NAMED_NODE)
  784. return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
  785. // Read named metadata elements.
  786. unsigned Size = Record.size();
  787. NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name);
  788. for (unsigned i = 0; i != Size; ++i) {
  789. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
  790. if (!MD)
  791. return error("Invalid record");
  792. NMD->addOperand(MD);
  793. }
  794. break;
  795. }
  796. case bitc::METADATA_OLD_FN_NODE: {
  797. // FIXME: Remove in 4.0.
  798. // This is a LocalAsMetadata record, the only type of function-local
  799. // metadata.
  800. if (Record.size() % 2 == 1)
  801. return error("Invalid record");
  802. // If this isn't a LocalAsMetadata record, we're dropping it. This used
  803. // to be legal, but there's no upgrade path.
  804. auto dropRecord = [&] {
  805. MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo);
  806. NextMetadataNo++;
  807. };
  808. if (Record.size() != 2) {
  809. dropRecord();
  810. break;
  811. }
  812. Type *Ty = getTypeByID(Record[0]);
  813. if (Ty->isMetadataTy() || Ty->isVoidTy()) {
  814. dropRecord();
  815. break;
  816. }
  817. MetadataList.assignValue(
  818. LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  819. NextMetadataNo);
  820. NextMetadataNo++;
  821. break;
  822. }
  823. case bitc::METADATA_OLD_NODE: {
  824. // FIXME: Remove in 4.0.
  825. if (Record.size() % 2 == 1)
  826. return error("Invalid record");
  827. unsigned Size = Record.size();
  828. SmallVector<Metadata *, 8> Elts;
  829. for (unsigned i = 0; i != Size; i += 2) {
  830. Type *Ty = getTypeByID(Record[i]);
  831. if (!Ty)
  832. return error("Invalid record");
  833. if (Ty->isMetadataTy())
  834. Elts.push_back(getMD(Record[i + 1]));
  835. else if (!Ty->isVoidTy()) {
  836. auto *MD =
  837. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
  838. assert(isa<ConstantAsMetadata>(MD) &&
  839. "Expected non-function-local metadata");
  840. Elts.push_back(MD);
  841. } else
  842. Elts.push_back(nullptr);
  843. }
  844. MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo);
  845. NextMetadataNo++;
  846. break;
  847. }
  848. case bitc::METADATA_VALUE: {
  849. if (Record.size() != 2)
  850. return error("Invalid record");
  851. Type *Ty = getTypeByID(Record[0]);
  852. if (Ty->isMetadataTy() || Ty->isVoidTy())
  853. return error("Invalid record");
  854. MetadataList.assignValue(
  855. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  856. NextMetadataNo);
  857. NextMetadataNo++;
  858. break;
  859. }
  860. case bitc::METADATA_DISTINCT_NODE:
  861. IsDistinct = true;
  862. LLVM_FALLTHROUGH;
  863. case bitc::METADATA_NODE: {
  864. SmallVector<Metadata *, 8> Elts;
  865. Elts.reserve(Record.size());
  866. for (unsigned ID : Record)
  867. Elts.push_back(getMDOrNull(ID));
  868. MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
  869. : MDNode::get(Context, Elts),
  870. NextMetadataNo);
  871. NextMetadataNo++;
  872. break;
  873. }
  874. case bitc::METADATA_LOCATION: {
  875. if (Record.size() != 5)
  876. return error("Invalid record");
  877. IsDistinct = Record[0];
  878. unsigned Line = Record[1];
  879. unsigned Column = Record[2];
  880. Metadata *Scope = getMD(Record[3]);
  881. Metadata *InlinedAt = getMDOrNull(Record[4]);
  882. MetadataList.assignValue(
  883. GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)),
  884. NextMetadataNo);
  885. NextMetadataNo++;
  886. break;
  887. }
  888. case bitc::METADATA_GENERIC_DEBUG: {
  889. if (Record.size() < 4)
  890. return error("Invalid record");
  891. IsDistinct = Record[0];
  892. unsigned Tag = Record[1];
  893. unsigned Version = Record[2];
  894. if (Tag >= 1u << 16 || Version != 0)
  895. return error("Invalid record");
  896. auto *Header = getMDString(Record[3]);
  897. SmallVector<Metadata *, 8> DwarfOps;
  898. for (unsigned I = 4, E = Record.size(); I != E; ++I)
  899. DwarfOps.push_back(getMDOrNull(Record[I]));
  900. MetadataList.assignValue(
  901. GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
  902. NextMetadataNo);
  903. NextMetadataNo++;
  904. break;
  905. }
  906. case bitc::METADATA_SUBRANGE: {
  907. if (Record.size() != 3)
  908. return error("Invalid record");
  909. IsDistinct = Record[0];
  910. MetadataList.assignValue(
  911. GET_OR_DISTINCT(DISubrange,
  912. (Context, Record[1], unrotateSign(Record[2]))),
  913. NextMetadataNo);
  914. NextMetadataNo++;
  915. break;
  916. }
  917. case bitc::METADATA_ENUMERATOR: {
  918. if (Record.size() != 3)
  919. return error("Invalid record");
  920. IsDistinct = Record[0];
  921. MetadataList.assignValue(
  922. GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
  923. getMDString(Record[2]))),
  924. NextMetadataNo);
  925. NextMetadataNo++;
  926. break;
  927. }
  928. case bitc::METADATA_BASIC_TYPE: {
  929. if (Record.size() != 6)
  930. return error("Invalid record");
  931. IsDistinct = Record[0];
  932. MetadataList.assignValue(
  933. GET_OR_DISTINCT(DIBasicType,
  934. (Context, Record[1], getMDString(Record[2]), Record[3],
  935. Record[4], Record[5])),
  936. NextMetadataNo);
  937. NextMetadataNo++;
  938. break;
  939. }
  940. case bitc::METADATA_DERIVED_TYPE: {
  941. if (Record.size() != 12)
  942. return error("Invalid record");
  943. IsDistinct = Record[0];
  944. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  945. MetadataList.assignValue(
  946. GET_OR_DISTINCT(DIDerivedType,
  947. (Context, Record[1], getMDString(Record[2]),
  948. getMDOrNull(Record[3]), Record[4],
  949. getDITypeRefOrNull(Record[5]),
  950. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  951. Record[9], Flags, getDITypeRefOrNull(Record[11]))),
  952. NextMetadataNo);
  953. NextMetadataNo++;
  954. break;
  955. }
  956. case bitc::METADATA_COMPOSITE_TYPE: {
  957. if (Record.size() != 16)
  958. return error("Invalid record");
  959. // If we have a UUID and this is not a forward declaration, lookup the
  960. // mapping.
  961. IsDistinct = Record[0] & 0x1;
  962. bool IsNotUsedInTypeRef = Record[0] >= 2;
  963. unsigned Tag = Record[1];
  964. MDString *Name = getMDString(Record[2]);
  965. Metadata *File = getMDOrNull(Record[3]);
  966. unsigned Line = Record[4];
  967. Metadata *Scope = getDITypeRefOrNull(Record[5]);
  968. Metadata *BaseType = nullptr;
  969. uint64_t SizeInBits = Record[7];
  970. if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
  971. return error("Alignment value is too large");
  972. uint32_t AlignInBits = Record[8];
  973. uint64_t OffsetInBits = 0;
  974. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  975. Metadata *Elements = nullptr;
  976. unsigned RuntimeLang = Record[12];
  977. Metadata *VTableHolder = nullptr;
  978. Metadata *TemplateParams = nullptr;
  979. auto *Identifier = getMDString(Record[15]);
  980. // If this module is being parsed so that it can be ThinLTO imported
  981. // into another module, composite types only need to be imported
  982. // as type declarations (unless full type definitions requested).
  983. // Create type declarations up front to save memory. Also, buildODRType
  984. // handles the case where this is type ODRed with a definition needed
  985. // by the importing module, in which case the existing definition is
  986. // used.
  987. if (IsImporting && !ImportFullTypeDefinitions && Identifier &&
  988. (Tag == dwarf::DW_TAG_enumeration_type ||
  989. Tag == dwarf::DW_TAG_class_type ||
  990. Tag == dwarf::DW_TAG_structure_type ||
  991. Tag == dwarf::DW_TAG_union_type)) {
  992. Flags = Flags | DINode::FlagFwdDecl;
  993. } else {
  994. BaseType = getDITypeRefOrNull(Record[6]);
  995. OffsetInBits = Record[9];
  996. Elements = getMDOrNull(Record[11]);
  997. VTableHolder = getDITypeRefOrNull(Record[13]);
  998. TemplateParams = getMDOrNull(Record[14]);
  999. }
  1000. DICompositeType *CT = nullptr;
  1001. if (Identifier)
  1002. CT = DICompositeType::buildODRType(
  1003. Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
  1004. SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  1005. VTableHolder, TemplateParams);
  1006. // Create a node if we didn't get a lazy ODR type.
  1007. if (!CT)
  1008. CT = GET_OR_DISTINCT(DICompositeType,
  1009. (Context, Tag, Name, File, Line, Scope, BaseType,
  1010. SizeInBits, AlignInBits, OffsetInBits, Flags,
  1011. Elements, RuntimeLang, VTableHolder, TemplateParams,
  1012. Identifier));
  1013. if (!IsNotUsedInTypeRef && Identifier)
  1014. MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
  1015. MetadataList.assignValue(CT, NextMetadataNo);
  1016. NextMetadataNo++;
  1017. break;
  1018. }
  1019. case bitc::METADATA_SUBROUTINE_TYPE: {
  1020. if (Record.size() < 3 || Record.size() > 4)
  1021. return error("Invalid record");
  1022. bool IsOldTypeRefArray = Record[0] < 2;
  1023. unsigned CC = (Record.size() > 3) ? Record[3] : 0;
  1024. IsDistinct = Record[0] & 0x1;
  1025. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
  1026. Metadata *Types = getMDOrNull(Record[2]);
  1027. if (LLVM_UNLIKELY(IsOldTypeRefArray))
  1028. Types = MetadataList.upgradeTypeRefArray(Types);
  1029. MetadataList.assignValue(
  1030. GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
  1031. NextMetadataNo);
  1032. NextMetadataNo++;
  1033. break;
  1034. }
  1035. case bitc::METADATA_MODULE: {
  1036. if (Record.size() != 6)
  1037. return error("Invalid record");
  1038. IsDistinct = Record[0];
  1039. MetadataList.assignValue(
  1040. GET_OR_DISTINCT(DIModule,
  1041. (Context, getMDOrNull(Record[1]),
  1042. getMDString(Record[2]), getMDString(Record[3]),
  1043. getMDString(Record[4]), getMDString(Record[5]))),
  1044. NextMetadataNo);
  1045. NextMetadataNo++;
  1046. break;
  1047. }
  1048. case bitc::METADATA_FILE: {
  1049. if (Record.size() != 3 && Record.size() != 5)
  1050. return error("Invalid record");
  1051. IsDistinct = Record[0];
  1052. MetadataList.assignValue(
  1053. GET_OR_DISTINCT(
  1054. DIFile,
  1055. (Context, getMDString(Record[1]), getMDString(Record[2]),
  1056. Record.size() == 3 ? DIFile::CSK_None
  1057. : static_cast<DIFile::ChecksumKind>(Record[3]),
  1058. Record.size() == 3 ? nullptr : getMDString(Record[4]))),
  1059. NextMetadataNo);
  1060. NextMetadataNo++;
  1061. break;
  1062. }
  1063. case bitc::METADATA_COMPILE_UNIT: {
  1064. if (Record.size() < 14 || Record.size() > 17)
  1065. return error("Invalid record");
  1066. // Ignore Record[0], which indicates whether this compile unit is
  1067. // distinct. It's always distinct.
  1068. IsDistinct = true;
  1069. auto *CU = DICompileUnit::getDistinct(
  1070. Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
  1071. Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
  1072. Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  1073. getMDOrNull(Record[12]), getMDOrNull(Record[13]),
  1074. Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
  1075. Record.size() <= 14 ? 0 : Record[14],
  1076. Record.size() <= 16 ? true : Record[16]);
  1077. MetadataList.assignValue(CU, NextMetadataNo);
  1078. NextMetadataNo++;
  1079. // Move the Upgrade the list of subprograms.
  1080. if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
  1081. CUSubprograms.push_back({CU, SPs});
  1082. break;
  1083. }
  1084. case bitc::METADATA_SUBPROGRAM: {
  1085. if (Record.size() < 18 || Record.size() > 20)
  1086. return error("Invalid record");
  1087. IsDistinct =
  1088. (Record[0] & 1) || Record[8]; // All definitions should be distinct.
  1089. // Version 1 has a Function as Record[15].
  1090. // Version 2 has removed Record[15].
  1091. // Version 3 has the Unit as Record[15].
  1092. // Version 4 added thisAdjustment.
  1093. bool HasUnit = Record[0] >= 2;
  1094. if (HasUnit && Record.size() < 19)
  1095. return error("Invalid record");
  1096. Metadata *CUorFn = getMDOrNull(Record[15]);
  1097. unsigned Offset = Record.size() >= 19 ? 1 : 0;
  1098. bool HasFn = Offset && !HasUnit;
  1099. bool HasThisAdj = Record.size() >= 20;
  1100. DISubprogram *SP = GET_OR_DISTINCT(
  1101. DISubprogram, (Context,
  1102. getDITypeRefOrNull(Record[1]), // scope
  1103. getMDString(Record[2]), // name
  1104. getMDString(Record[3]), // linkageName
  1105. getMDOrNull(Record[4]), // file
  1106. Record[5], // line
  1107. getMDOrNull(Record[6]), // type
  1108. Record[7], // isLocal
  1109. Record[8], // isDefinition
  1110. Record[9], // scopeLine
  1111. getDITypeRefOrNull(Record[10]), // containingType
  1112. Record[11], // virtuality
  1113. Record[12], // virtualIndex
  1114. HasThisAdj ? Record[19] : 0, // thisAdjustment
  1115. static_cast<DINode::DIFlags>(Record[13] // flags
  1116. ),
  1117. Record[14], // isOptimized
  1118. HasUnit ? CUorFn : nullptr, // unit
  1119. getMDOrNull(Record[15 + Offset]), // templateParams
  1120. getMDOrNull(Record[16 + Offset]), // declaration
  1121. getMDOrNull(Record[17 + Offset]) // variables
  1122. ));
  1123. MetadataList.assignValue(SP, NextMetadataNo);
  1124. NextMetadataNo++;
  1125. // Upgrade sp->function mapping to function->sp mapping.
  1126. if (HasFn) {
  1127. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
  1128. if (auto *F = dyn_cast<Function>(CMD->getValue())) {
  1129. if (F->isMaterializable())
  1130. // Defer until materialized; unmaterialized functions may not have
  1131. // metadata.
  1132. FunctionsWithSPs[F] = SP;
  1133. else if (!F->empty())
  1134. F->setSubprogram(SP);
  1135. }
  1136. }
  1137. break;
  1138. }
  1139. case bitc::METADATA_LEXICAL_BLOCK: {
  1140. if (Record.size() != 5)
  1141. return error("Invalid record");
  1142. IsDistinct = Record[0];
  1143. MetadataList.assignValue(
  1144. GET_OR_DISTINCT(DILexicalBlock,
  1145. (Context, getMDOrNull(Record[1]),
  1146. getMDOrNull(Record[2]), Record[3], Record[4])),
  1147. NextMetadataNo);
  1148. NextMetadataNo++;
  1149. break;
  1150. }
  1151. case bitc::METADATA_LEXICAL_BLOCK_FILE: {
  1152. if (Record.size() != 4)
  1153. return error("Invalid record");
  1154. IsDistinct = Record[0];
  1155. MetadataList.assignValue(
  1156. GET_OR_DISTINCT(DILexicalBlockFile,
  1157. (Context, getMDOrNull(Record[1]),
  1158. getMDOrNull(Record[2]), Record[3])),
  1159. NextMetadataNo);
  1160. NextMetadataNo++;
  1161. break;
  1162. }
  1163. case bitc::METADATA_NAMESPACE: {
  1164. if (Record.size() != 5)
  1165. return error("Invalid record");
  1166. IsDistinct = Record[0] & 1;
  1167. bool ExportSymbols = Record[0] & 2;
  1168. MetadataList.assignValue(
  1169. GET_OR_DISTINCT(DINamespace,
  1170. (Context, getMDOrNull(Record[1]),
  1171. getMDOrNull(Record[2]), getMDString(Record[3]),
  1172. Record[4], ExportSymbols)),
  1173. NextMetadataNo);
  1174. NextMetadataNo++;
  1175. break;
  1176. }
  1177. case bitc::METADATA_MACRO: {
  1178. if (Record.size() != 5)
  1179. return error("Invalid record");
  1180. IsDistinct = Record[0];
  1181. MetadataList.assignValue(
  1182. GET_OR_DISTINCT(DIMacro,
  1183. (Context, Record[1], Record[2], getMDString(Record[3]),
  1184. getMDString(Record[4]))),
  1185. NextMetadataNo);
  1186. NextMetadataNo++;
  1187. break;
  1188. }
  1189. case bitc::METADATA_MACRO_FILE: {
  1190. if (Record.size() != 5)
  1191. return error("Invalid record");
  1192. IsDistinct = Record[0];
  1193. MetadataList.assignValue(
  1194. GET_OR_DISTINCT(DIMacroFile,
  1195. (Context, Record[1], Record[2], getMDOrNull(Record[3]),
  1196. getMDOrNull(Record[4]))),
  1197. NextMetadataNo);
  1198. NextMetadataNo++;
  1199. break;
  1200. }
  1201. case bitc::METADATA_TEMPLATE_TYPE: {
  1202. if (Record.size() != 3)
  1203. return error("Invalid record");
  1204. IsDistinct = Record[0];
  1205. MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
  1206. (Context, getMDString(Record[1]),
  1207. getDITypeRefOrNull(Record[2]))),
  1208. NextMetadataNo);
  1209. NextMetadataNo++;
  1210. break;
  1211. }
  1212. case bitc::METADATA_TEMPLATE_VALUE: {
  1213. if (Record.size() != 5)
  1214. return error("Invalid record");
  1215. IsDistinct = Record[0];
  1216. MetadataList.assignValue(
  1217. GET_OR_DISTINCT(DITemplateValueParameter,
  1218. (Context, Record[1], getMDString(Record[2]),
  1219. getDITypeRefOrNull(Record[3]),
  1220. getMDOrNull(Record[4]))),
  1221. NextMetadataNo);
  1222. NextMetadataNo++;
  1223. break;
  1224. }
  1225. case bitc::METADATA_GLOBAL_VAR: {
  1226. if (Record.size() < 11 || Record.size() > 12)
  1227. return error("Invalid record");
  1228. IsDistinct = Record[0] & 1;
  1229. unsigned Version = Record[0] >> 1;
  1230. if (Version == 1) {
  1231. MetadataList.assignValue(
  1232. GET_OR_DISTINCT(DIGlobalVariable,
  1233. (Context, getMDOrNull(Record[1]),
  1234. getMDString(Record[2]), getMDString(Record[3]),
  1235. getMDOrNull(Record[4]), Record[5],
  1236. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1237. getMDOrNull(Record[10]), Record[11])),
  1238. NextMetadataNo);
  1239. NextMetadataNo++;
  1240. } else if (Version == 0) {
  1241. // Upgrade old metadata, which stored a global variable reference or a
  1242. // ConstantInt here.
  1243. Metadata *Expr = getMDOrNull(Record[9]);
  1244. uint32_t AlignInBits = 0;
  1245. if (Record.size() > 11) {
  1246. if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1247. return error("Alignment value is too large");
  1248. AlignInBits = Record[11];
  1249. }
  1250. GlobalVariable *Attach = nullptr;
  1251. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
  1252. if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
  1253. Attach = GV;
  1254. Expr = nullptr;
  1255. } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
  1256. Expr = DIExpression::get(Context,
  1257. {dwarf::DW_OP_constu, CI->getZExtValue(),
  1258. dwarf::DW_OP_stack_value});
  1259. } else {
  1260. Expr = nullptr;
  1261. }
  1262. }
  1263. DIGlobalVariable *DGV = GET_OR_DISTINCT(
  1264. DIGlobalVariable,
  1265. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  1266. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  1267. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  1268. getMDOrNull(Record[10]), AlignInBits));
  1269. auto *DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr);
  1270. MetadataList.assignValue(DGVE, NextMetadataNo);
  1271. NextMetadataNo++;
  1272. if (Attach)
  1273. Attach->addDebugInfo(DGVE);
  1274. } else
  1275. return error("Invalid record");
  1276. break;
  1277. }
  1278. case bitc::METADATA_LOCAL_VAR: {
  1279. // 10th field is for the obseleted 'inlinedAt:' field.
  1280. if (Record.size() < 8 || Record.size() > 10)
  1281. return error("Invalid record");
  1282. IsDistinct = Record[0] & 1;
  1283. bool HasAlignment = Record[0] & 2;
  1284. // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
  1285. // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
  1286. // this is newer version of record which doesn't have artifical tag.
  1287. bool HasTag = !HasAlignment && Record.size() > 8;
  1288. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
  1289. uint32_t AlignInBits = 0;
  1290. if (HasAlignment) {
  1291. if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max())
  1292. return error("Alignment value is too large");
  1293. AlignInBits = Record[8 + HasTag];
  1294. }
  1295. MetadataList.assignValue(
  1296. GET_OR_DISTINCT(DILocalVariable,
  1297. (Context, getMDOrNull(Record[1 + HasTag]),
  1298. getMDString(Record[2 + HasTag]),
  1299. getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
  1300. getDITypeRefOrNull(Record[5 + HasTag]),
  1301. Record[6 + HasTag], Flags, AlignInBits)),
  1302. NextMetadataNo);
  1303. NextMetadataNo++;
  1304. break;
  1305. }
  1306. case bitc::METADATA_EXPRESSION: {
  1307. if (Record.size() < 1)
  1308. return error("Invalid record");
  1309. IsDistinct = Record[0] & 1;
  1310. bool HasOpFragment = Record[0] & 2;
  1311. auto Elts = MutableArrayRef<uint64_t>(Record).slice(1);
  1312. if (!HasOpFragment)
  1313. if (unsigned N = Elts.size())
  1314. if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece)
  1315. Elts[N - 3] = dwarf::DW_OP_LLVM_fragment;
  1316. MetadataList.assignValue(
  1317. GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))),
  1318. NextMetadataNo);
  1319. NextMetadataNo++;
  1320. break;
  1321. }
  1322. case bitc::METADATA_GLOBAL_VAR_EXPR: {
  1323. if (Record.size() != 3)
  1324. return error("Invalid record");
  1325. IsDistinct = Record[0];
  1326. MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression,
  1327. (Context, getMDOrNull(Record[1]),
  1328. getMDOrNull(Record[2]))),
  1329. NextMetadataNo);
  1330. NextMetadataNo++;
  1331. break;
  1332. }
  1333. case bitc::METADATA_OBJC_PROPERTY: {
  1334. if (Record.size() != 8)
  1335. return error("Invalid record");
  1336. IsDistinct = Record[0];
  1337. MetadataList.assignValue(
  1338. GET_OR_DISTINCT(DIObjCProperty,
  1339. (Context, getMDString(Record[1]),
  1340. getMDOrNull(Record[2]), Record[3],
  1341. getMDString(Record[4]), getMDString(Record[5]),
  1342. Record[6], getDITypeRefOrNull(Record[7]))),
  1343. NextMetadataNo);
  1344. NextMetadataNo++;
  1345. break;
  1346. }
  1347. case bitc::METADATA_IMPORTED_ENTITY: {
  1348. if (Record.size() != 6)
  1349. return error("Invalid record");
  1350. IsDistinct = Record[0];
  1351. MetadataList.assignValue(
  1352. GET_OR_DISTINCT(DIImportedEntity,
  1353. (Context, Record[1], getMDOrNull(Record[2]),
  1354. getDITypeRefOrNull(Record[3]), Record[4],
  1355. getMDString(Record[5]))),
  1356. NextMetadataNo);
  1357. NextMetadataNo++;
  1358. break;
  1359. }
  1360. case bitc::METADATA_STRING_OLD: {
  1361. std::string String(Record.begin(), Record.end());
  1362. // Test for upgrading !llvm.loop.
  1363. HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
  1364. ++NumMDStringLoaded;
  1365. Metadata *MD = MDString::get(Context, String);
  1366. MetadataList.assignValue(MD, NextMetadataNo);
  1367. NextMetadataNo++;
  1368. break;
  1369. }
  1370. case bitc::METADATA_STRINGS: {
  1371. auto CreateNextMDString = [&](StringRef Str) {
  1372. ++NumMDStringLoaded;
  1373. MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo);
  1374. NextMetadataNo++;
  1375. };
  1376. if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString))
  1377. return Err;
  1378. break;
  1379. }
  1380. case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
  1381. if (Record.size() % 2 == 0)
  1382. return error("Invalid record");
  1383. unsigned ValueID = Record[0];
  1384. if (ValueID >= ValueList.size())
  1385. return error("Invalid record");
  1386. if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
  1387. if (Error Err = parseGlobalObjectAttachment(
  1388. *GO, ArrayRef<uint64_t>(Record).slice(1)))
  1389. return Err;
  1390. break;
  1391. }
  1392. case bitc::METADATA_KIND: {
  1393. // Support older bitcode files that had METADATA_KIND records in a
  1394. // block with METADATA_BLOCK_ID.
  1395. if (Error Err = parseMetadataKindRecord(Record))
  1396. return Err;
  1397. break;
  1398. }
  1399. }
  1400. return Error::success();
  1401. #undef GET_OR_DISTINCT
  1402. }
  1403. Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings(
  1404. ArrayRef<uint64_t> Record, StringRef Blob,
  1405. function_ref<void(StringRef)> CallBack) {
  1406. // All the MDStrings in the block are emitted together in a single
  1407. // record. The strings are concatenated and stored in a blob along with
  1408. // their sizes.
  1409. if (Record.size() != 2)
  1410. return error("Invalid record: metadata strings layout");
  1411. unsigned NumStrings = Record[0];
  1412. unsigned StringsOffset = Record[1];
  1413. if (!NumStrings)
  1414. return error("Invalid record: metadata strings with no strings");
  1415. if (StringsOffset > Blob.size())
  1416. return error("Invalid record: metadata strings corrupt offset");
  1417. StringRef Lengths = Blob.slice(0, StringsOffset);
  1418. SimpleBitstreamCursor R(Lengths);
  1419. StringRef Strings = Blob.drop_front(StringsOffset);
  1420. do {
  1421. if (R.AtEndOfStream())
  1422. return error("Invalid record: metadata strings bad length");
  1423. unsigned Size = R.ReadVBR(6);
  1424. if (Strings.size() < Size)
  1425. return error("Invalid record: metadata strings truncated chars");
  1426. CallBack(Strings.slice(0, Size));
  1427. Strings = Strings.drop_front(Size);
  1428. } while (--NumStrings);
  1429. return Error::success();
  1430. }
  1431. Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment(
  1432. GlobalObject &GO, ArrayRef<uint64_t> Record) {
  1433. assert(Record.size() % 2 == 0);
  1434. for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
  1435. auto K = MDKindMap.find(Record[I]);
  1436. if (K == MDKindMap.end())
  1437. return error("Invalid ID");
  1438. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
  1439. if (!MD)
  1440. return error("Invalid metadata attachment");
  1441. GO.addMetadata(K->second, *MD);
  1442. }
  1443. return Error::success();
  1444. }
  1445. /// Parse metadata attachments.
  1446. Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment(
  1447. Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
  1448. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  1449. return error("Invalid record");
  1450. SmallVector<uint64_t, 64> Record;
  1451. PlaceholderQueue Placeholders;
  1452. while (true) {
  1453. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1454. switch (Entry.Kind) {
  1455. case BitstreamEntry::SubBlock: // Handled for us already.
  1456. case BitstreamEntry::Error:
  1457. return error("Malformed block");
  1458. case BitstreamEntry::EndBlock:
  1459. resolveForwardRefsAndPlaceholders(Placeholders);
  1460. return Error::success();
  1461. case BitstreamEntry::Record:
  1462. // The interesting case.
  1463. break;
  1464. }
  1465. // Read a metadata attachment record.
  1466. Record.clear();
  1467. ++NumMDRecordLoaded;
  1468. switch (Stream.readRecord(Entry.ID, Record)) {
  1469. default: // Default behavior: ignore.
  1470. break;
  1471. case bitc::METADATA_ATTACHMENT: {
  1472. unsigned RecordLength = Record.size();
  1473. if (Record.empty())
  1474. return error("Invalid record");
  1475. if (RecordLength % 2 == 0) {
  1476. // A function attachment.
  1477. if (Error Err = parseGlobalObjectAttachment(F, Record))
  1478. return Err;
  1479. continue;
  1480. }
  1481. // An instruction attachment.
  1482. Instruction *Inst = InstructionList[Record[0]];
  1483. for (unsigned i = 1; i != RecordLength; i = i + 2) {
  1484. unsigned Kind = Record[i];
  1485. DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind);
  1486. if (I == MDKindMap.end())
  1487. return error("Invalid ID");
  1488. if (I->second == LLVMContext::MD_tbaa && StripTBAA)
  1489. continue;
  1490. auto Idx = Record[i + 1];
  1491. if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) &&
  1492. !MetadataList.lookup(Idx)) {
  1493. // Load the attachment if it is in the lazy-loadable range and hasn't
  1494. // been loaded yet.
  1495. lazyLoadOneMetadata(Idx, Placeholders);
  1496. resolveForwardRefsAndPlaceholders(Placeholders);
  1497. }
  1498. Metadata *Node = MetadataList.getMetadataFwdRef(Idx);
  1499. if (isa<LocalAsMetadata>(Node))
  1500. // Drop the attachment. This used to be legal, but there's no
  1501. // upgrade path.
  1502. break;
  1503. MDNode *MD = dyn_cast_or_null<MDNode>(Node);
  1504. if (!MD)
  1505. return error("Invalid metadata attachment");
  1506. if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
  1507. MD = upgradeInstructionLoopAttachment(*MD);
  1508. if (I->second == LLVMContext::MD_tbaa) {
  1509. assert(!MD->isTemporary() && "should load MDs before attachments");
  1510. MD = UpgradeTBAANode(*MD);
  1511. }
  1512. Inst->setMetadata(I->second, MD);
  1513. }
  1514. break;
  1515. }
  1516. }
  1517. }
  1518. }
  1519. /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
  1520. Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord(
  1521. SmallVectorImpl<uint64_t> &Record) {
  1522. if (Record.size() < 2)
  1523. return error("Invalid record");
  1524. unsigned Kind = Record[0];
  1525. SmallString<8> Name(Record.begin() + 1, Record.end());
  1526. unsigned NewKind = TheModule.getMDKindID(Name.str());
  1527. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  1528. return error("Conflicting METADATA_KIND records");
  1529. return Error::success();
  1530. }
  1531. /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
  1532. Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() {
  1533. if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
  1534. return error("Invalid record");
  1535. SmallVector<uint64_t, 64> Record;
  1536. // Read all the records.
  1537. while (true) {
  1538. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1539. switch (Entry.Kind) {
  1540. case BitstreamEntry::SubBlock: // Handled for us already.
  1541. case BitstreamEntry::Error:
  1542. return error("Malformed block");
  1543. case BitstreamEntry::EndBlock:
  1544. return Error::success();
  1545. case BitstreamEntry::Record:
  1546. // The interesting case.
  1547. break;
  1548. }
  1549. // Read a record.
  1550. Record.clear();
  1551. ++NumMDRecordLoaded;
  1552. unsigned Code = Stream.readRecord(Entry.ID, Record);
  1553. switch (Code) {
  1554. default: // Default behavior: ignore.
  1555. break;
  1556. case bitc::METADATA_KIND: {
  1557. if (Error Err = parseMetadataKindRecord(Record))
  1558. return Err;
  1559. break;
  1560. }
  1561. }
  1562. }
  1563. }
  1564. MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) {
  1565. Pimpl = std::move(RHS.Pimpl);
  1566. return *this;
  1567. }
  1568. MetadataLoader::MetadataLoader(MetadataLoader &&RHS)
  1569. : Pimpl(std::move(RHS.Pimpl)) {}
  1570. MetadataLoader::~MetadataLoader() = default;
  1571. MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule,
  1572. BitcodeReaderValueList &ValueList,
  1573. bool IsImporting,
  1574. std::function<Type *(unsigned)> getTypeByID)
  1575. : Pimpl(llvm::make_unique<MetadataLoaderImpl>(
  1576. Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {}
  1577. Error MetadataLoader::parseMetadata(bool ModuleLevel) {
  1578. return Pimpl->parseMetadata(ModuleLevel);
  1579. }
  1580. bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); }
  1581. /// Return the given metadata, creating a replaceable forward reference if
  1582. /// necessary.
  1583. Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) {
  1584. return Pimpl->getMetadataFwdRefOrLoad(Idx);
  1585. }
  1586. MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) {
  1587. return Pimpl->getMDNodeFwdRefOrNull(Idx);
  1588. }
  1589. DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) {
  1590. return Pimpl->lookupSubprogramForFunction(F);
  1591. }
  1592. Error MetadataLoader::parseMetadataAttachment(
  1593. Function &F, const SmallVectorImpl<Instruction *> &InstructionList) {
  1594. return Pimpl->parseMetadataAttachment(F, InstructionList);
  1595. }
  1596. Error MetadataLoader::parseMetadataKinds() {
  1597. return Pimpl->parseMetadataKinds();
  1598. }
  1599. void MetadataLoader::setStripTBAA(bool StripTBAA) {
  1600. return Pimpl->setStripTBAA(StripTBAA);
  1601. }
  1602. bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); }
  1603. unsigned MetadataLoader::size() const { return Pimpl->size(); }
  1604. void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); }