MetadataLoader.cpp 72 KB

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