MetadataLoader.cpp 85 KB

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