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