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 ~PlaceholderQueue() { 362 assert(empty() && "PlaceholderQueue hasn't been flushed before being destroyed"); 363 } 364 bool empty() { return PHs.empty(); } 365 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID); 366 void flush(BitcodeReaderMetadataList &MetadataList); 367 368 /// Return the list of temporaries nodes in the queue, these need to be 369 /// loaded before we can flush the queue. 370 void getTemporaries(BitcodeReaderMetadataList &MetadataList, 371 DenseSet<unsigned> &Temporaries) { 372 for (auto &PH : PHs) { 373 auto ID = PH.getID(); 374 auto *MD = MetadataList.lookup(ID); 375 if (!MD) { 376 Temporaries.insert(ID); 377 continue; 378 } 379 auto *N = dyn_cast_or_null<MDNode>(MD); 380 if (N && N->isTemporary()) 381 Temporaries.insert(ID); 382 } 383 } 384 }; 385 386 } // end anonymous namespace 387 388 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) { 389 PHs.emplace_back(ID); 390 return PHs.back(); 391 } 392 393 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) { 394 while (!PHs.empty()) { 395 auto *MD = MetadataList.lookup(PHs.front().getID()); 396 assert(MD && "Flushing placeholder on unassigned MD"); 397 #ifndef NDEBUG 398 if (auto *MDN = dyn_cast<MDNode>(MD)) 399 assert(MDN->isResolved() && 400 "Flushing Placeholder while cycles aren't resolved"); 401 #endif 402 PHs.front().replaceUseWith(MD); 403 PHs.pop_front(); 404 } 405 } 406 407 } // anonynous namespace 408 409 class MetadataLoader::MetadataLoaderImpl { 410 BitcodeReaderMetadataList MetadataList; 411 BitcodeReaderValueList &ValueList; 412 BitstreamCursor &Stream; 413 LLVMContext &Context; 414 Module &TheModule; 415 std::function<Type *(unsigned)> getTypeByID; 416 417 /// Cursor associated with the lazy-loading of Metadata. This is the easy way 418 /// to keep around the right "context" (Abbrev list) to be able to jump in 419 /// the middle of the metadata block and load any record. 420 BitstreamCursor IndexCursor; 421 422 /// Index that keeps track of MDString values. 423 std::vector<StringRef> MDStringRef; 424 425 /// On-demand loading of a single MDString. Requires the index above to be 426 /// populated. 427 MDString *lazyLoadOneMDString(unsigned Idx); 428 429 /// Index that keeps track of where to find a metadata record in the stream. 430 std::vector<uint64_t> GlobalMetadataBitPosIndex; 431 432 /// Populate the index above to enable lazily loading of metadata, and load 433 /// the named metadata as well as the transitively referenced global 434 /// Metadata. 435 Expected<bool> lazyLoadModuleMetadataBlock(); 436 437 /// On-demand loading of a single metadata. Requires the index above to be 438 /// populated. 439 void lazyLoadOneMetadata(unsigned Idx, PlaceholderQueue &Placeholders); 440 441 // Keep mapping of seens pair of old-style CU <-> SP, and update pointers to 442 // point from SP to CU after a block is completly parsed. 443 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms; 444 445 /// Functions that need to be matched with subprograms when upgrading old 446 /// metadata. 447 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs; 448 449 // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 450 DenseMap<unsigned, unsigned> MDKindMap; 451 452 bool StripTBAA = false; 453 bool HasSeenOldLoopTags = false; 454 455 /// True if metadata is being parsed for a module being ThinLTO imported. 456 bool IsImporting = false; 457 458 Error parseOneMetadata(SmallVectorImpl<uint64_t> &Record, unsigned Code, 459 PlaceholderQueue &Placeholders, StringRef Blob, 460 unsigned &NextMetadataNo); 461 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob, 462 function_ref<void(StringRef)> CallBack); 463 Error parseGlobalObjectAttachment(GlobalObject &GO, 464 ArrayRef<uint64_t> Record); 465 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record); 466 467 void resolveForwardRefsAndPlaceholders(PlaceholderQueue &Placeholders); 468 469 /// Upgrade old-style CU <-> SP pointers to point from SP to CU. 470 void upgradeCUSubprograms() { 471 for (auto CU_SP : CUSubprograms) 472 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second)) 473 for (auto &Op : SPs->operands()) 474 if (auto *SP = dyn_cast_or_null<MDNode>(Op)) 475 SP->replaceOperandWith(7, CU_SP.first); 476 CUSubprograms.clear(); 477 } 478 479 public: 480 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule, 481 BitcodeReaderValueList &ValueList, 482 std::function<Type *(unsigned)> getTypeByID, 483 bool IsImporting) 484 : MetadataList(TheModule.getContext()), ValueList(ValueList), 485 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule), 486 getTypeByID(std::move(getTypeByID)), IsImporting(IsImporting) {} 487 488 Error parseMetadata(bool ModuleLevel); 489 490 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); } 491 492 Metadata *getMetadataFwdRefOrLoad(unsigned ID) { 493 if (ID < MDStringRef.size()) 494 return lazyLoadOneMDString(ID); 495 if (auto *MD = MetadataList.lookup(ID)) 496 return MD; 497 // If lazy-loading is enabled, we try recursively to load the operand 498 // instead of creating a temporary. 499 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) { 500 PlaceholderQueue Placeholders; 501 lazyLoadOneMetadata(ID, Placeholders); 502 resolveForwardRefsAndPlaceholders(Placeholders); 503 return MetadataList.lookup(ID); 504 } 505 return MetadataList.getMetadataFwdRef(ID); 506 } 507 508 MDNode *getMDNodeFwdRefOrNull(unsigned Idx) { 509 return MetadataList.getMDNodeFwdRefOrNull(Idx); 510 } 511 512 DISubprogram *lookupSubprogramForFunction(Function *F) { 513 return FunctionsWithSPs.lookup(F); 514 } 515 516 bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; } 517 518 Error parseMetadataAttachment( 519 Function &F, const SmallVectorImpl<Instruction *> &InstructionList); 520 521 Error parseMetadataKinds(); 522 523 void setStripTBAA(bool Value) { StripTBAA = Value; } 524 bool isStrippingTBAA() { return StripTBAA; } 525 526 unsigned size() const { return MetadataList.size(); } 527 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); } 528 }; 529 530 Error error(const Twine &Message) { 531 return make_error<StringError>( 532 Message, make_error_code(BitcodeError::CorruptedBitcode)); 533 } 534 535 Expected<bool> 536 MetadataLoader::MetadataLoaderImpl::lazyLoadModuleMetadataBlock() { 537 IndexCursor = Stream; 538 SmallVector<uint64_t, 64> Record; 539 // Get the abbrevs, and preload record positions to make them lazy-loadable. 540 while (true) { 541 BitstreamEntry Entry = IndexCursor.advanceSkippingSubblocks( 542 BitstreamCursor::AF_DontPopBlockAtEnd); 543 switch (Entry.Kind) { 544 case BitstreamEntry::SubBlock: // Handled for us already. 545 case BitstreamEntry::Error: 546 return error("Malformed block"); 547 case BitstreamEntry::EndBlock: { 548 return true; 549 } 550 case BitstreamEntry::Record: { 551 // The interesting case. 552 ++NumMDRecordLoaded; 553 uint64_t CurrentPos = IndexCursor.GetCurrentBitNo(); 554 auto Code = IndexCursor.skipRecord(Entry.ID); 555 switch (Code) { 556 case bitc::METADATA_STRINGS: { 557 // Rewind and parse the strings. 558 IndexCursor.JumpToBit(CurrentPos); 559 StringRef Blob; 560 Record.clear(); 561 IndexCursor.readRecord(Entry.ID, Record, &Blob); 562 unsigned NumStrings = Record[0]; 563 MDStringRef.reserve(NumStrings); 564 auto IndexNextMDString = [&](StringRef Str) { 565 MDStringRef.push_back(Str); 566 }; 567 if (auto Err = parseMetadataStrings(Record, Blob, IndexNextMDString)) 568 return std::move(Err); 569 break; 570 } 571 case bitc::METADATA_INDEX_OFFSET: { 572 // This is the offset to the index, when we see this we skip all the 573 // records and load only an index to these. 574 IndexCursor.JumpToBit(CurrentPos); 575 Record.clear(); 576 IndexCursor.readRecord(Entry.ID, Record); 577 if (Record.size() != 2) 578 return error("Invalid record"); 579 auto Offset = Record[0] + (Record[1] << 32); 580 auto BeginPos = IndexCursor.GetCurrentBitNo(); 581 IndexCursor.JumpToBit(BeginPos + Offset); 582 Entry = IndexCursor.advanceSkippingSubblocks( 583 BitstreamCursor::AF_DontPopBlockAtEnd); 584 assert(Entry.Kind == BitstreamEntry::Record && 585 "Corrupted bitcode: Expected `Record` when trying to find the " 586 "Metadata index"); 587 Record.clear(); 588 auto Code = IndexCursor.readRecord(Entry.ID, Record); 589 (void)Code; 590 assert(Code == bitc::METADATA_INDEX && "Corrupted bitcode: Expected " 591 "`METADATA_INDEX` when trying " 592 "to find the Metadata index"); 593 594 // Delta unpack 595 auto CurrentValue = BeginPos; 596 GlobalMetadataBitPosIndex.reserve(Record.size()); 597 for (auto &Elt : Record) { 598 CurrentValue += Elt; 599 GlobalMetadataBitPosIndex.push_back(CurrentValue); 600 } 601 break; 602 } 603 case bitc::METADATA_INDEX: 604 // We don't expect to get there, the Index is loaded when we encounter 605 // the offset. 606 return error("Corrupted Metadata block"); 607 case bitc::METADATA_NAME: { 608 // Named metadata need to be materialized now and aren't deferred. 609 IndexCursor.JumpToBit(CurrentPos); 610 Record.clear(); 611 unsigned Code = IndexCursor.readRecord(Entry.ID, Record); 612 assert(Code == bitc::METADATA_NAME); 613 614 // Read name of the named metadata. 615 SmallString<8> Name(Record.begin(), Record.end()); 616 Code = IndexCursor.ReadCode(); 617 618 // Named Metadata comes in two parts, we expect the name to be followed 619 // by the node 620 Record.clear(); 621 unsigned NextBitCode = IndexCursor.readRecord(Code, Record); 622 assert(NextBitCode == bitc::METADATA_NAMED_NODE); 623 (void)NextBitCode; 624 625 // Read named metadata elements. 626 unsigned Size = Record.size(); 627 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name); 628 for (unsigned i = 0; i != Size; ++i) { 629 // FIXME: We could use a placeholder here, however NamedMDNode are 630 // taking MDNode as operand and not using the Metadata infrastructure. 631 // It is acknowledged by 'TODO: Inherit from Metadata' in the 632 // NamedMDNode class definition. 633 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]); 634 assert(MD && "Invalid record"); 635 NMD->addOperand(MD); 636 } 637 break; 638 } 639 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 640 // FIXME: we need to do this early because we don't materialize global 641 // value explicitly. 642 IndexCursor.JumpToBit(CurrentPos); 643 Record.clear(); 644 IndexCursor.readRecord(Entry.ID, Record); 645 if (Record.size() % 2 == 0) 646 return error("Invalid record"); 647 unsigned ValueID = Record[0]; 648 if (ValueID >= ValueList.size()) 649 return error("Invalid record"); 650 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) 651 if (Error Err = parseGlobalObjectAttachment( 652 *GO, ArrayRef<uint64_t>(Record).slice(1))) 653 return std::move(Err); 654 break; 655 } 656 case bitc::METADATA_KIND: 657 case bitc::METADATA_STRING_OLD: 658 case bitc::METADATA_OLD_FN_NODE: 659 case bitc::METADATA_OLD_NODE: 660 case bitc::METADATA_VALUE: 661 case bitc::METADATA_DISTINCT_NODE: 662 case bitc::METADATA_NODE: 663 case bitc::METADATA_LOCATION: 664 case bitc::METADATA_GENERIC_DEBUG: 665 case bitc::METADATA_SUBRANGE: 666 case bitc::METADATA_ENUMERATOR: 667 case bitc::METADATA_BASIC_TYPE: 668 case bitc::METADATA_DERIVED_TYPE: 669 case bitc::METADATA_COMPOSITE_TYPE: 670 case bitc::METADATA_SUBROUTINE_TYPE: 671 case bitc::METADATA_MODULE: 672 case bitc::METADATA_FILE: 673 case bitc::METADATA_COMPILE_UNIT: 674 case bitc::METADATA_SUBPROGRAM: 675 case bitc::METADATA_LEXICAL_BLOCK: 676 case bitc::METADATA_LEXICAL_BLOCK_FILE: 677 case bitc::METADATA_NAMESPACE: 678 case bitc::METADATA_MACRO: 679 case bitc::METADATA_MACRO_FILE: 680 case bitc::METADATA_TEMPLATE_TYPE: 681 case bitc::METADATA_TEMPLATE_VALUE: 682 case bitc::METADATA_GLOBAL_VAR: 683 case bitc::METADATA_LOCAL_VAR: 684 case bitc::METADATA_EXPRESSION: 685 case bitc::METADATA_OBJC_PROPERTY: 686 case bitc::METADATA_IMPORTED_ENTITY: 687 case bitc::METADATA_GLOBAL_VAR_EXPR: 688 // We don't expect to see any of these, if we see one, give up on 689 // lazy-loading and fallback. 690 MDStringRef.clear(); 691 GlobalMetadataBitPosIndex.clear(); 692 return false; 693 } 694 break; 695 } 696 } 697 } 698 } 699 700 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing 701 /// module level metadata. 702 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) { 703 if (!ModuleLevel && MetadataList.hasFwdRefs()) 704 return error("Invalid metadata: fwd refs into function blocks"); 705 706 // Record the entry position so that we can jump back here and efficiently 707 // skip the whole block in case we lazy-load. 708 auto EntryPos = Stream.GetCurrentBitNo(); 709 710 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 711 return error("Invalid record"); 712 713 SmallVector<uint64_t, 64> Record; 714 PlaceholderQueue Placeholders; 715 716 // We lazy-load module-level metadata: we build an index for each record, and 717 // then load individual record as needed, starting with the named metadata. 718 if (ModuleLevel && IsImporting && MetadataList.empty() && 719 !DisableLazyLoading) { 720 auto SuccessOrErr = lazyLoadModuleMetadataBlock(); 721 if (!SuccessOrErr) 722 return SuccessOrErr.takeError(); 723 if (SuccessOrErr.get()) { 724 // An index was successfully created and we will be able to load metadata 725 // on-demand. 726 MetadataList.resize(MDStringRef.size() + 727 GlobalMetadataBitPosIndex.size()); 728 729 // Reading the named metadata created forward references and/or 730 // placeholders, that we flush here. 731 resolveForwardRefsAndPlaceholders(Placeholders); 732 upgradeCUSubprograms(); 733 // Return at the beginning of the block, since it is easy to skip it 734 // entirely from there. 735 Stream.ReadBlockEnd(); // Pop the abbrev block context. 736 Stream.JumpToBit(EntryPos); 737 if (Stream.SkipBlock()) 738 return error("Invalid record"); 739 return Error::success(); 740 } 741 // Couldn't load an index, fallback to loading all the block "old-style". 742 } 743 744 unsigned NextMetadataNo = MetadataList.size(); 745 746 // Read all the records. 747 while (true) { 748 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 749 750 switch (Entry.Kind) { 751 case BitstreamEntry::SubBlock: // Handled for us already. 752 case BitstreamEntry::Error: 753 return error("Malformed block"); 754 case BitstreamEntry::EndBlock: 755 resolveForwardRefsAndPlaceholders(Placeholders); 756 upgradeCUSubprograms(); 757 return Error::success(); 758 case BitstreamEntry::Record: 759 // The interesting case. 760 break; 761 } 762 763 // Read a record. 764 Record.clear(); 765 StringRef Blob; 766 ++NumMDRecordLoaded; 767 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob); 768 if (Error Err = 769 parseOneMetadata(Record, Code, Placeholders, Blob, NextMetadataNo)) 770 return Err; 771 } 772 } 773 774 MDString *MetadataLoader::MetadataLoaderImpl::lazyLoadOneMDString(unsigned ID) { 775 ++NumMDStringLoaded; 776 if (Metadata *MD = MetadataList.lookup(ID)) 777 return cast<MDString>(MD); 778 auto MDS = MDString::get(Context, MDStringRef[ID]); 779 MetadataList.assignValue(MDS, ID); 780 return MDS; 781 } 782 783 void MetadataLoader::MetadataLoaderImpl::lazyLoadOneMetadata( 784 unsigned ID, PlaceholderQueue &Placeholders) { 785 assert(ID < (MDStringRef.size()) + GlobalMetadataBitPosIndex.size()); 786 assert(ID >= MDStringRef.size() && "Unexpected lazy-loading of MDString"); 787 // Lookup first if the metadata hasn't already been loaded. 788 if (auto *MD = MetadataList.lookup(ID)) { 789 auto *N = dyn_cast_or_null<MDNode>(MD); 790 if (!N->isTemporary()) 791 return; 792 } 793 SmallVector<uint64_t, 64> Record; 794 StringRef Blob; 795 IndexCursor.JumpToBit(GlobalMetadataBitPosIndex[ID - MDStringRef.size()]); 796 auto Entry = IndexCursor.advanceSkippingSubblocks(); 797 ++NumMDRecordLoaded; 798 unsigned Code = IndexCursor.readRecord(Entry.ID, Record, &Blob); 799 if (Error Err = parseOneMetadata(Record, Code, Placeholders, Blob, ID)) 800 report_fatal_error("Can't lazyload MD"); 801 } 802 803 /// Ensure that all forward-references and placeholders are resolved. 804 /// Iteratively lazy-loading metadata on-demand if needed. 805 void MetadataLoader::MetadataLoaderImpl::resolveForwardRefsAndPlaceholders( 806 PlaceholderQueue &Placeholders) { 807 DenseSet<unsigned> Temporaries; 808 while (1) { 809 // Populate Temporaries with the placeholders that haven't been loaded yet. 810 Placeholders.getTemporaries(MetadataList, Temporaries); 811 812 // If we don't have any temporary, or FwdReference, we're done! 813 if (Temporaries.empty() && !MetadataList.hasFwdRefs()) 814 break; 815 816 // First, load all the temporaries. This can add new placeholders or 817 // forward references. 818 for (auto ID : Temporaries) 819 lazyLoadOneMetadata(ID, Placeholders); 820 Temporaries.clear(); 821 822 // Second, load the forward-references. This can also add new placeholders 823 // or forward references. 824 while (MetadataList.hasFwdRefs()) 825 lazyLoadOneMetadata(MetadataList.getNextFwdRef(), Placeholders); 826 } 827 // At this point we don't have any forward reference remaining, or temporary 828 // that haven't been loaded. We can safely drop RAUW support and mark cycles 829 // as resolved. 830 MetadataList.tryToResolveCycles(); 831 832 // Finally, everything is in place, we can replace the placeholders operands 833 // with the final node they refer to. 834 Placeholders.flush(MetadataList); 835 } 836 837 Error MetadataLoader::MetadataLoaderImpl::parseOneMetadata( 838 SmallVectorImpl<uint64_t> &Record, unsigned Code, 839 PlaceholderQueue &Placeholders, StringRef Blob, unsigned &NextMetadataNo) { 840 841 bool IsDistinct = false; 842 auto getMD = [&](unsigned ID) -> Metadata * { 843 if (ID < MDStringRef.size()) 844 return lazyLoadOneMDString(ID); 845 if (!IsDistinct) { 846 if (auto *MD = MetadataList.lookup(ID)) 847 return MD; 848 // If lazy-loading is enabled, we try recursively to load the operand 849 // instead of creating a temporary. 850 if (ID < (MDStringRef.size() + GlobalMetadataBitPosIndex.size())) { 851 // Create a temporary for the node that is referencing the operand we 852 // will lazy-load. It is needed before recursing in case there are 853 // uniquing cycles. 854 MetadataList.getMetadataFwdRef(NextMetadataNo); 855 lazyLoadOneMetadata(ID, Placeholders); 856 return MetadataList.lookup(ID); 857 } 858 // Return a temporary. 859 return MetadataList.getMetadataFwdRef(ID); 860 } 861 if (auto *MD = MetadataList.getMetadataIfResolved(ID)) 862 return MD; 863 return &Placeholders.getPlaceholderOp(ID); 864 }; 865 auto getMDOrNull = [&](unsigned ID) -> Metadata * { 866 if (ID) 867 return getMD(ID - 1); 868 return nullptr; 869 }; 870 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * { 871 if (ID) 872 return MetadataList.getMetadataFwdRef(ID - 1); 873 return nullptr; 874 }; 875 auto getMDString = [&](unsigned ID) -> MDString * { 876 // This requires that the ID is not really a forward reference. In 877 // particular, the MDString must already have been resolved. 878 auto MDS = getMDOrNull(ID); 879 return cast_or_null<MDString>(MDS); 880 }; 881 882 // Support for old type refs. 883 auto getDITypeRefOrNull = [&](unsigned ID) { 884 return MetadataList.upgradeTypeRef(getMDOrNull(ID)); 885 }; 886 887 #define GET_OR_DISTINCT(CLASS, ARGS) \ 888 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 889 890 switch (Code) { 891 default: // Default behavior: ignore. 892 break; 893 case bitc::METADATA_NAME: { 894 // Read name of the named metadata. 895 SmallString<8> Name(Record.begin(), Record.end()); 896 Record.clear(); 897 Code = Stream.ReadCode(); 898 899 ++NumMDRecordLoaded; 900 unsigned NextBitCode = Stream.readRecord(Code, Record); 901 if (NextBitCode != bitc::METADATA_NAMED_NODE) 902 return error("METADATA_NAME not followed by METADATA_NAMED_NODE"); 903 904 // Read named metadata elements. 905 unsigned Size = Record.size(); 906 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name); 907 for (unsigned i = 0; i != Size; ++i) { 908 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]); 909 if (!MD) 910 return error("Invalid record"); 911 NMD->addOperand(MD); 912 } 913 break; 914 } 915 case bitc::METADATA_OLD_FN_NODE: { 916 // FIXME: Remove in 4.0. 917 // This is a LocalAsMetadata record, the only type of function-local 918 // metadata. 919 if (Record.size() % 2 == 1) 920 return error("Invalid record"); 921 922 // If this isn't a LocalAsMetadata record, we're dropping it. This used 923 // to be legal, but there's no upgrade path. 924 auto dropRecord = [&] { 925 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo); 926 NextMetadataNo++; 927 }; 928 if (Record.size() != 2) { 929 dropRecord(); 930 break; 931 } 932 933 Type *Ty = getTypeByID(Record[0]); 934 if (Ty->isMetadataTy() || Ty->isVoidTy()) { 935 dropRecord(); 936 break; 937 } 938 939 MetadataList.assignValue( 940 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 941 NextMetadataNo); 942 NextMetadataNo++; 943 break; 944 } 945 case bitc::METADATA_OLD_NODE: { 946 // FIXME: Remove in 4.0. 947 if (Record.size() % 2 == 1) 948 return error("Invalid record"); 949 950 unsigned Size = Record.size(); 951 SmallVector<Metadata *, 8> Elts; 952 for (unsigned i = 0; i != Size; i += 2) { 953 Type *Ty = getTypeByID(Record[i]); 954 if (!Ty) 955 return error("Invalid record"); 956 if (Ty->isMetadataTy()) 957 Elts.push_back(getMD(Record[i + 1])); 958 else if (!Ty->isVoidTy()) { 959 auto *MD = 960 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 961 assert(isa<ConstantAsMetadata>(MD) && 962 "Expected non-function-local metadata"); 963 Elts.push_back(MD); 964 } else 965 Elts.push_back(nullptr); 966 } 967 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo); 968 NextMetadataNo++; 969 break; 970 } 971 case bitc::METADATA_VALUE: { 972 if (Record.size() != 2) 973 return error("Invalid record"); 974 975 Type *Ty = getTypeByID(Record[0]); 976 if (Ty->isMetadataTy() || Ty->isVoidTy()) 977 return error("Invalid record"); 978 979 MetadataList.assignValue( 980 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 981 NextMetadataNo); 982 NextMetadataNo++; 983 break; 984 } 985 case bitc::METADATA_DISTINCT_NODE: 986 IsDistinct = true; 987 LLVM_FALLTHROUGH; 988 case bitc::METADATA_NODE: { 989 SmallVector<Metadata *, 8> Elts; 990 Elts.reserve(Record.size()); 991 for (unsigned ID : Record) 992 Elts.push_back(getMDOrNull(ID)); 993 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 994 : MDNode::get(Context, Elts), 995 NextMetadataNo); 996 NextMetadataNo++; 997 break; 998 } 999 case bitc::METADATA_LOCATION: { 1000 if (Record.size() != 5) 1001 return error("Invalid record"); 1002 1003 IsDistinct = Record[0]; 1004 unsigned Line = Record[1]; 1005 unsigned Column = Record[2]; 1006 Metadata *Scope = getMD(Record[3]); 1007 Metadata *InlinedAt = getMDOrNull(Record[4]); 1008 MetadataList.assignValue( 1009 GET_OR_DISTINCT(DILocation, (Context, Line, Column, Scope, InlinedAt)), 1010 NextMetadataNo); 1011 NextMetadataNo++; 1012 break; 1013 } 1014 case bitc::METADATA_GENERIC_DEBUG: { 1015 if (Record.size() < 4) 1016 return error("Invalid record"); 1017 1018 IsDistinct = Record[0]; 1019 unsigned Tag = Record[1]; 1020 unsigned Version = Record[2]; 1021 1022 if (Tag >= 1u << 16 || Version != 0) 1023 return error("Invalid record"); 1024 1025 auto *Header = getMDString(Record[3]); 1026 SmallVector<Metadata *, 8> DwarfOps; 1027 for (unsigned I = 4, E = Record.size(); I != E; ++I) 1028 DwarfOps.push_back(getMDOrNull(Record[I])); 1029 MetadataList.assignValue( 1030 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)), 1031 NextMetadataNo); 1032 NextMetadataNo++; 1033 break; 1034 } 1035 case bitc::METADATA_SUBRANGE: { 1036 if (Record.size() != 3) 1037 return error("Invalid record"); 1038 1039 IsDistinct = Record[0]; 1040 MetadataList.assignValue( 1041 GET_OR_DISTINCT(DISubrange, 1042 (Context, Record[1], unrotateSign(Record[2]))), 1043 NextMetadataNo); 1044 NextMetadataNo++; 1045 break; 1046 } 1047 case bitc::METADATA_ENUMERATOR: { 1048 if (Record.size() != 3) 1049 return error("Invalid record"); 1050 1051 IsDistinct = Record[0]; 1052 MetadataList.assignValue( 1053 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]), 1054 getMDString(Record[2]))), 1055 NextMetadataNo); 1056 NextMetadataNo++; 1057 break; 1058 } 1059 case bitc::METADATA_BASIC_TYPE: { 1060 if (Record.size() != 6) 1061 return error("Invalid record"); 1062 1063 IsDistinct = Record[0]; 1064 MetadataList.assignValue( 1065 GET_OR_DISTINCT(DIBasicType, 1066 (Context, Record[1], getMDString(Record[2]), Record[3], 1067 Record[4], Record[5])), 1068 NextMetadataNo); 1069 NextMetadataNo++; 1070 break; 1071 } 1072 case bitc::METADATA_DERIVED_TYPE: { 1073 if (Record.size() != 12) 1074 return error("Invalid record"); 1075 1076 IsDistinct = Record[0]; 1077 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 1078 MetadataList.assignValue( 1079 GET_OR_DISTINCT(DIDerivedType, 1080 (Context, Record[1], getMDString(Record[2]), 1081 getMDOrNull(Record[3]), Record[4], 1082 getDITypeRefOrNull(Record[5]), 1083 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1084 Record[9], Flags, getDITypeRefOrNull(Record[11]))), 1085 NextMetadataNo); 1086 NextMetadataNo++; 1087 break; 1088 } 1089 case bitc::METADATA_COMPOSITE_TYPE: { 1090 if (Record.size() != 16) 1091 return error("Invalid record"); 1092 1093 // If we have a UUID and this is not a forward declaration, lookup the 1094 // mapping. 1095 IsDistinct = Record[0] & 0x1; 1096 bool IsNotUsedInTypeRef = Record[0] >= 2; 1097 unsigned Tag = Record[1]; 1098 MDString *Name = getMDString(Record[2]); 1099 Metadata *File = getMDOrNull(Record[3]); 1100 unsigned Line = Record[4]; 1101 Metadata *Scope = getDITypeRefOrNull(Record[5]); 1102 Metadata *BaseType = nullptr; 1103 uint64_t SizeInBits = Record[7]; 1104 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1105 return error("Alignment value is too large"); 1106 uint32_t AlignInBits = Record[8]; 1107 uint64_t OffsetInBits = 0; 1108 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 1109 Metadata *Elements = nullptr; 1110 unsigned RuntimeLang = Record[12]; 1111 Metadata *VTableHolder = nullptr; 1112 Metadata *TemplateParams = nullptr; 1113 auto *Identifier = getMDString(Record[15]); 1114 // If this module is being parsed so that it can be ThinLTO imported 1115 // into another module, composite types only need to be imported 1116 // as type declarations (unless full type definitions requested). 1117 // Create type declarations up front to save memory. Also, buildODRType 1118 // handles the case where this is type ODRed with a definition needed 1119 // by the importing module, in which case the existing definition is 1120 // used. 1121 if (IsImporting && !ImportFullTypeDefinitions && Identifier && 1122 (Tag == dwarf::DW_TAG_enumeration_type || 1123 Tag == dwarf::DW_TAG_class_type || 1124 Tag == dwarf::DW_TAG_structure_type || 1125 Tag == dwarf::DW_TAG_union_type)) { 1126 Flags = Flags | DINode::FlagFwdDecl; 1127 } else { 1128 BaseType = getDITypeRefOrNull(Record[6]); 1129 OffsetInBits = Record[9]; 1130 Elements = getMDOrNull(Record[11]); 1131 VTableHolder = getDITypeRefOrNull(Record[13]); 1132 TemplateParams = getMDOrNull(Record[14]); 1133 } 1134 DICompositeType *CT = nullptr; 1135 if (Identifier) 1136 CT = DICompositeType::buildODRType( 1137 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType, 1138 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 1139 VTableHolder, TemplateParams); 1140 1141 // Create a node if we didn't get a lazy ODR type. 1142 if (!CT) 1143 CT = GET_OR_DISTINCT(DICompositeType, 1144 (Context, Tag, Name, File, Line, Scope, BaseType, 1145 SizeInBits, AlignInBits, OffsetInBits, Flags, 1146 Elements, RuntimeLang, VTableHolder, TemplateParams, 1147 Identifier)); 1148 if (!IsNotUsedInTypeRef && Identifier) 1149 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT)); 1150 1151 MetadataList.assignValue(CT, NextMetadataNo); 1152 NextMetadataNo++; 1153 break; 1154 } 1155 case bitc::METADATA_SUBROUTINE_TYPE: { 1156 if (Record.size() < 3 || Record.size() > 4) 1157 return error("Invalid record"); 1158 bool IsOldTypeRefArray = Record[0] < 2; 1159 unsigned CC = (Record.size() > 3) ? Record[3] : 0; 1160 1161 IsDistinct = Record[0] & 0x1; 1162 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]); 1163 Metadata *Types = getMDOrNull(Record[2]); 1164 if (LLVM_UNLIKELY(IsOldTypeRefArray)) 1165 Types = MetadataList.upgradeTypeRefArray(Types); 1166 1167 MetadataList.assignValue( 1168 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)), 1169 NextMetadataNo); 1170 NextMetadataNo++; 1171 break; 1172 } 1173 1174 case bitc::METADATA_MODULE: { 1175 if (Record.size() != 6) 1176 return error("Invalid record"); 1177 1178 IsDistinct = Record[0]; 1179 MetadataList.assignValue( 1180 GET_OR_DISTINCT(DIModule, 1181 (Context, getMDOrNull(Record[1]), 1182 getMDString(Record[2]), getMDString(Record[3]), 1183 getMDString(Record[4]), getMDString(Record[5]))), 1184 NextMetadataNo); 1185 NextMetadataNo++; 1186 break; 1187 } 1188 1189 case bitc::METADATA_FILE: { 1190 if (Record.size() != 3 && Record.size() != 5) 1191 return error("Invalid record"); 1192 1193 IsDistinct = Record[0]; 1194 MetadataList.assignValue( 1195 GET_OR_DISTINCT( 1196 DIFile, 1197 (Context, getMDString(Record[1]), getMDString(Record[2]), 1198 Record.size() == 3 ? DIFile::CSK_None 1199 : static_cast<DIFile::ChecksumKind>(Record[3]), 1200 Record.size() == 3 ? nullptr : getMDString(Record[4]))), 1201 NextMetadataNo); 1202 NextMetadataNo++; 1203 break; 1204 } 1205 case bitc::METADATA_COMPILE_UNIT: { 1206 if (Record.size() < 14 || Record.size() > 18) 1207 return error("Invalid record"); 1208 1209 // Ignore Record[0], which indicates whether this compile unit is 1210 // distinct. It's always distinct. 1211 IsDistinct = true; 1212 auto *CU = DICompileUnit::getDistinct( 1213 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]), 1214 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]), 1215 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]), 1216 getMDOrNull(Record[12]), getMDOrNull(Record[13]), 1217 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]), 1218 Record.size() <= 14 ? 0 : Record[14], 1219 Record.size() <= 16 ? true : Record[16], 1220 Record.size() <= 17 ? false : Record[17]); 1221 1222 MetadataList.assignValue(CU, NextMetadataNo); 1223 NextMetadataNo++; 1224 1225 // Move the Upgrade the list of subprograms. 1226 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11])) 1227 CUSubprograms.push_back({CU, SPs}); 1228 break; 1229 } 1230 case bitc::METADATA_SUBPROGRAM: { 1231 if (Record.size() < 18 || Record.size() > 20) 1232 return error("Invalid record"); 1233 1234 IsDistinct = 1235 (Record[0] & 1) || Record[8]; // All definitions should be distinct. 1236 // Version 1 has a Function as Record[15]. 1237 // Version 2 has removed Record[15]. 1238 // Version 3 has the Unit as Record[15]. 1239 // Version 4 added thisAdjustment. 1240 bool HasUnit = Record[0] >= 2; 1241 if (HasUnit && Record.size() < 19) 1242 return error("Invalid record"); 1243 Metadata *CUorFn = getMDOrNull(Record[15]); 1244 unsigned Offset = Record.size() >= 19 ? 1 : 0; 1245 bool HasFn = Offset && !HasUnit; 1246 bool HasThisAdj = Record.size() >= 20; 1247 DISubprogram *SP = GET_OR_DISTINCT( 1248 DISubprogram, (Context, 1249 getDITypeRefOrNull(Record[1]), // scope 1250 getMDString(Record[2]), // name 1251 getMDString(Record[3]), // linkageName 1252 getMDOrNull(Record[4]), // file 1253 Record[5], // line 1254 getMDOrNull(Record[6]), // type 1255 Record[7], // isLocal 1256 Record[8], // isDefinition 1257 Record[9], // scopeLine 1258 getDITypeRefOrNull(Record[10]), // containingType 1259 Record[11], // virtuality 1260 Record[12], // virtualIndex 1261 HasThisAdj ? Record[19] : 0, // thisAdjustment 1262 static_cast<DINode::DIFlags>(Record[13] // flags 1263 ), 1264 Record[14], // isOptimized 1265 HasUnit ? CUorFn : nullptr, // unit 1266 getMDOrNull(Record[15 + Offset]), // templateParams 1267 getMDOrNull(Record[16 + Offset]), // declaration 1268 getMDOrNull(Record[17 + Offset]) // variables 1269 )); 1270 MetadataList.assignValue(SP, NextMetadataNo); 1271 NextMetadataNo++; 1272 1273 // Upgrade sp->function mapping to function->sp mapping. 1274 if (HasFn) { 1275 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn)) 1276 if (auto *F = dyn_cast<Function>(CMD->getValue())) { 1277 if (F->isMaterializable()) 1278 // Defer until materialized; unmaterialized functions may not have 1279 // metadata. 1280 FunctionsWithSPs[F] = SP; 1281 else if (!F->empty()) 1282 F->setSubprogram(SP); 1283 } 1284 } 1285 break; 1286 } 1287 case bitc::METADATA_LEXICAL_BLOCK: { 1288 if (Record.size() != 5) 1289 return error("Invalid record"); 1290 1291 IsDistinct = Record[0]; 1292 MetadataList.assignValue( 1293 GET_OR_DISTINCT(DILexicalBlock, 1294 (Context, getMDOrNull(Record[1]), 1295 getMDOrNull(Record[2]), Record[3], Record[4])), 1296 NextMetadataNo); 1297 NextMetadataNo++; 1298 break; 1299 } 1300 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 1301 if (Record.size() != 4) 1302 return error("Invalid record"); 1303 1304 IsDistinct = Record[0]; 1305 MetadataList.assignValue( 1306 GET_OR_DISTINCT(DILexicalBlockFile, 1307 (Context, getMDOrNull(Record[1]), 1308 getMDOrNull(Record[2]), Record[3])), 1309 NextMetadataNo); 1310 NextMetadataNo++; 1311 break; 1312 } 1313 case bitc::METADATA_NAMESPACE: { 1314 if (Record.size() != 5) 1315 return error("Invalid record"); 1316 1317 IsDistinct = Record[0] & 1; 1318 bool ExportSymbols = Record[0] & 2; 1319 MetadataList.assignValue( 1320 GET_OR_DISTINCT(DINamespace, 1321 (Context, getMDOrNull(Record[1]), 1322 getMDOrNull(Record[2]), getMDString(Record[3]), 1323 Record[4], ExportSymbols)), 1324 NextMetadataNo); 1325 NextMetadataNo++; 1326 break; 1327 } 1328 case bitc::METADATA_MACRO: { 1329 if (Record.size() != 5) 1330 return error("Invalid record"); 1331 1332 IsDistinct = Record[0]; 1333 MetadataList.assignValue( 1334 GET_OR_DISTINCT(DIMacro, 1335 (Context, Record[1], Record[2], getMDString(Record[3]), 1336 getMDString(Record[4]))), 1337 NextMetadataNo); 1338 NextMetadataNo++; 1339 break; 1340 } 1341 case bitc::METADATA_MACRO_FILE: { 1342 if (Record.size() != 5) 1343 return error("Invalid record"); 1344 1345 IsDistinct = Record[0]; 1346 MetadataList.assignValue( 1347 GET_OR_DISTINCT(DIMacroFile, 1348 (Context, Record[1], Record[2], getMDOrNull(Record[3]), 1349 getMDOrNull(Record[4]))), 1350 NextMetadataNo); 1351 NextMetadataNo++; 1352 break; 1353 } 1354 case bitc::METADATA_TEMPLATE_TYPE: { 1355 if (Record.size() != 3) 1356 return error("Invalid record"); 1357 1358 IsDistinct = Record[0]; 1359 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 1360 (Context, getMDString(Record[1]), 1361 getDITypeRefOrNull(Record[2]))), 1362 NextMetadataNo); 1363 NextMetadataNo++; 1364 break; 1365 } 1366 case bitc::METADATA_TEMPLATE_VALUE: { 1367 if (Record.size() != 5) 1368 return error("Invalid record"); 1369 1370 IsDistinct = Record[0]; 1371 MetadataList.assignValue( 1372 GET_OR_DISTINCT(DITemplateValueParameter, 1373 (Context, Record[1], getMDString(Record[2]), 1374 getDITypeRefOrNull(Record[3]), 1375 getMDOrNull(Record[4]))), 1376 NextMetadataNo); 1377 NextMetadataNo++; 1378 break; 1379 } 1380 case bitc::METADATA_GLOBAL_VAR: { 1381 if (Record.size() < 11 || Record.size() > 12) 1382 return error("Invalid record"); 1383 1384 IsDistinct = Record[0] & 1; 1385 unsigned Version = Record[0] >> 1; 1386 1387 if (Version == 1) { 1388 MetadataList.assignValue( 1389 GET_OR_DISTINCT(DIGlobalVariable, 1390 (Context, getMDOrNull(Record[1]), 1391 getMDString(Record[2]), getMDString(Record[3]), 1392 getMDOrNull(Record[4]), Record[5], 1393 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1394 getMDOrNull(Record[10]), Record[11])), 1395 NextMetadataNo); 1396 NextMetadataNo++; 1397 } else if (Version == 0) { 1398 // Upgrade old metadata, which stored a global variable reference or a 1399 // ConstantInt here. 1400 Metadata *Expr = getMDOrNull(Record[9]); 1401 uint32_t AlignInBits = 0; 1402 if (Record.size() > 11) { 1403 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1404 return error("Alignment value is too large"); 1405 AlignInBits = Record[11]; 1406 } 1407 GlobalVariable *Attach = nullptr; 1408 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) { 1409 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) { 1410 Attach = GV; 1411 Expr = nullptr; 1412 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) { 1413 Expr = DIExpression::get(Context, 1414 {dwarf::DW_OP_constu, CI->getZExtValue(), 1415 dwarf::DW_OP_stack_value}); 1416 } else { 1417 Expr = nullptr; 1418 } 1419 } 1420 DIGlobalVariable *DGV = GET_OR_DISTINCT( 1421 DIGlobalVariable, 1422 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 1423 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 1424 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1425 getMDOrNull(Record[10]), AlignInBits)); 1426 1427 auto *DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr); 1428 MetadataList.assignValue(DGVE, NextMetadataNo); 1429 NextMetadataNo++; 1430 if (Attach) 1431 Attach->addDebugInfo(DGVE); 1432 } else 1433 return error("Invalid record"); 1434 1435 break; 1436 } 1437 case bitc::METADATA_LOCAL_VAR: { 1438 // 10th field is for the obseleted 'inlinedAt:' field. 1439 if (Record.size() < 8 || Record.size() > 10) 1440 return error("Invalid record"); 1441 1442 IsDistinct = Record[0] & 1; 1443 bool HasAlignment = Record[0] & 2; 1444 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 1445 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that 1446 // this is newer version of record which doesn't have artifical tag. 1447 bool HasTag = !HasAlignment && Record.size() > 8; 1448 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]); 1449 uint32_t AlignInBits = 0; 1450 if (HasAlignment) { 1451 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1452 return error("Alignment value is too large"); 1453 AlignInBits = Record[8 + HasTag]; 1454 } 1455 MetadataList.assignValue( 1456 GET_OR_DISTINCT(DILocalVariable, 1457 (Context, getMDOrNull(Record[1 + HasTag]), 1458 getMDString(Record[2 + HasTag]), 1459 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 1460 getDITypeRefOrNull(Record[5 + HasTag]), 1461 Record[6 + HasTag], Flags, AlignInBits)), 1462 NextMetadataNo); 1463 NextMetadataNo++; 1464 break; 1465 } 1466 case bitc::METADATA_EXPRESSION: { 1467 if (Record.size() < 1) 1468 return error("Invalid record"); 1469 1470 IsDistinct = Record[0] & 1; 1471 bool HasOpFragment = Record[0] & 2; 1472 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1); 1473 if (!HasOpFragment) 1474 if (unsigned N = Elts.size()) 1475 if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece) 1476 Elts[N - 3] = dwarf::DW_OP_LLVM_fragment; 1477 1478 MetadataList.assignValue( 1479 GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))), 1480 NextMetadataNo); 1481 NextMetadataNo++; 1482 break; 1483 } 1484 case bitc::METADATA_GLOBAL_VAR_EXPR: { 1485 if (Record.size() != 3) 1486 return error("Invalid record"); 1487 1488 IsDistinct = Record[0]; 1489 MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression, 1490 (Context, getMDOrNull(Record[1]), 1491 getMDOrNull(Record[2]))), 1492 NextMetadataNo); 1493 NextMetadataNo++; 1494 break; 1495 } 1496 case bitc::METADATA_OBJC_PROPERTY: { 1497 if (Record.size() != 8) 1498 return error("Invalid record"); 1499 1500 IsDistinct = Record[0]; 1501 MetadataList.assignValue( 1502 GET_OR_DISTINCT(DIObjCProperty, 1503 (Context, getMDString(Record[1]), 1504 getMDOrNull(Record[2]), Record[3], 1505 getMDString(Record[4]), getMDString(Record[5]), 1506 Record[6], getDITypeRefOrNull(Record[7]))), 1507 NextMetadataNo); 1508 NextMetadataNo++; 1509 break; 1510 } 1511 case bitc::METADATA_IMPORTED_ENTITY: { 1512 if (Record.size() != 6) 1513 return error("Invalid record"); 1514 1515 IsDistinct = Record[0]; 1516 MetadataList.assignValue( 1517 GET_OR_DISTINCT(DIImportedEntity, 1518 (Context, Record[1], getMDOrNull(Record[2]), 1519 getDITypeRefOrNull(Record[3]), Record[4], 1520 getMDString(Record[5]))), 1521 NextMetadataNo); 1522 NextMetadataNo++; 1523 break; 1524 } 1525 case bitc::METADATA_STRING_OLD: { 1526 std::string String(Record.begin(), Record.end()); 1527 1528 // Test for upgrading !llvm.loop. 1529 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String); 1530 ++NumMDStringLoaded; 1531 Metadata *MD = MDString::get(Context, String); 1532 MetadataList.assignValue(MD, NextMetadataNo); 1533 NextMetadataNo++; 1534 break; 1535 } 1536 case bitc::METADATA_STRINGS: { 1537 auto CreateNextMDString = [&](StringRef Str) { 1538 ++NumMDStringLoaded; 1539 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo); 1540 NextMetadataNo++; 1541 }; 1542 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString)) 1543 return Err; 1544 break; 1545 } 1546 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 1547 if (Record.size() % 2 == 0) 1548 return error("Invalid record"); 1549 unsigned ValueID = Record[0]; 1550 if (ValueID >= ValueList.size()) 1551 return error("Invalid record"); 1552 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) 1553 if (Error Err = parseGlobalObjectAttachment( 1554 *GO, ArrayRef<uint64_t>(Record).slice(1))) 1555 return Err; 1556 break; 1557 } 1558 case bitc::METADATA_KIND: { 1559 // Support older bitcode files that had METADATA_KIND records in a 1560 // block with METADATA_BLOCK_ID. 1561 if (Error Err = parseMetadataKindRecord(Record)) 1562 return Err; 1563 break; 1564 } 1565 } 1566 return Error::success(); 1567 #undef GET_OR_DISTINCT 1568 } 1569 1570 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings( 1571 ArrayRef<uint64_t> Record, StringRef Blob, 1572 function_ref<void(StringRef)> CallBack) { 1573 // All the MDStrings in the block are emitted together in a single 1574 // record. The strings are concatenated and stored in a blob along with 1575 // their sizes. 1576 if (Record.size() != 2) 1577 return error("Invalid record: metadata strings layout"); 1578 1579 unsigned NumStrings = Record[0]; 1580 unsigned StringsOffset = Record[1]; 1581 if (!NumStrings) 1582 return error("Invalid record: metadata strings with no strings"); 1583 if (StringsOffset > Blob.size()) 1584 return error("Invalid record: metadata strings corrupt offset"); 1585 1586 StringRef Lengths = Blob.slice(0, StringsOffset); 1587 SimpleBitstreamCursor R(Lengths); 1588 1589 StringRef Strings = Blob.drop_front(StringsOffset); 1590 do { 1591 if (R.AtEndOfStream()) 1592 return error("Invalid record: metadata strings bad length"); 1593 1594 unsigned Size = R.ReadVBR(6); 1595 if (Strings.size() < Size) 1596 return error("Invalid record: metadata strings truncated chars"); 1597 1598 CallBack(Strings.slice(0, Size)); 1599 Strings = Strings.drop_front(Size); 1600 } while (--NumStrings); 1601 1602 return Error::success(); 1603 } 1604 1605 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment( 1606 GlobalObject &GO, ArrayRef<uint64_t> Record) { 1607 assert(Record.size() % 2 == 0); 1608 for (unsigned I = 0, E = Record.size(); I != E; I += 2) { 1609 auto K = MDKindMap.find(Record[I]); 1610 if (K == MDKindMap.end()) 1611 return error("Invalid ID"); 1612 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]); 1613 if (!MD) 1614 return error("Invalid metadata attachment"); 1615 GO.addMetadata(K->second, *MD); 1616 } 1617 return Error::success(); 1618 } 1619 1620 /// Parse metadata attachments. 1621 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment( 1622 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 1623 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 1624 return error("Invalid record"); 1625 1626 SmallVector<uint64_t, 64> Record; 1627 PlaceholderQueue Placeholders; 1628 1629 while (true) { 1630 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1631 1632 switch (Entry.Kind) { 1633 case BitstreamEntry::SubBlock: // Handled for us already. 1634 case BitstreamEntry::Error: 1635 return error("Malformed block"); 1636 case BitstreamEntry::EndBlock: 1637 resolveForwardRefsAndPlaceholders(Placeholders); 1638 return Error::success(); 1639 case BitstreamEntry::Record: 1640 // The interesting case. 1641 break; 1642 } 1643 1644 // Read a metadata attachment record. 1645 Record.clear(); 1646 ++NumMDRecordLoaded; 1647 switch (Stream.readRecord(Entry.ID, Record)) { 1648 default: // Default behavior: ignore. 1649 break; 1650 case bitc::METADATA_ATTACHMENT: { 1651 unsigned RecordLength = Record.size(); 1652 if (Record.empty()) 1653 return error("Invalid record"); 1654 if (RecordLength % 2 == 0) { 1655 // A function attachment. 1656 if (Error Err = parseGlobalObjectAttachment(F, Record)) 1657 return Err; 1658 continue; 1659 } 1660 1661 // An instruction attachment. 1662 Instruction *Inst = InstructionList[Record[0]]; 1663 for (unsigned i = 1; i != RecordLength; i = i + 2) { 1664 unsigned Kind = Record[i]; 1665 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind); 1666 if (I == MDKindMap.end()) 1667 return error("Invalid ID"); 1668 if (I->second == LLVMContext::MD_tbaa && StripTBAA) 1669 continue; 1670 1671 auto Idx = Record[i + 1]; 1672 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) && 1673 !MetadataList.lookup(Idx)) { 1674 // Load the attachment if it is in the lazy-loadable range and hasn't 1675 // been loaded yet. 1676 lazyLoadOneMetadata(Idx, Placeholders); 1677 resolveForwardRefsAndPlaceholders(Placeholders); 1678 } 1679 1680 Metadata *Node = MetadataList.getMetadataFwdRef(Idx); 1681 if (isa<LocalAsMetadata>(Node)) 1682 // Drop the attachment. This used to be legal, but there's no 1683 // upgrade path. 1684 break; 1685 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 1686 if (!MD) 1687 return error("Invalid metadata attachment"); 1688 1689 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 1690 MD = upgradeInstructionLoopAttachment(*MD); 1691 1692 if (I->second == LLVMContext::MD_tbaa) { 1693 assert(!MD->isTemporary() && "should load MDs before attachments"); 1694 MD = UpgradeTBAANode(*MD); 1695 } 1696 Inst->setMetadata(I->second, MD); 1697 } 1698 break; 1699 } 1700 } 1701 } 1702 } 1703 1704 /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 1705 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord( 1706 SmallVectorImpl<uint64_t> &Record) { 1707 if (Record.size() < 2) 1708 return error("Invalid record"); 1709 1710 unsigned Kind = Record[0]; 1711 SmallString<8> Name(Record.begin() + 1, Record.end()); 1712 1713 unsigned NewKind = TheModule.getMDKindID(Name.str()); 1714 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1715 return error("Conflicting METADATA_KIND records"); 1716 return Error::success(); 1717 } 1718 1719 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 1720 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() { 1721 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 1722 return error("Invalid record"); 1723 1724 SmallVector<uint64_t, 64> Record; 1725 1726 // Read all the records. 1727 while (true) { 1728 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1729 1730 switch (Entry.Kind) { 1731 case BitstreamEntry::SubBlock: // Handled for us already. 1732 case BitstreamEntry::Error: 1733 return error("Malformed block"); 1734 case BitstreamEntry::EndBlock: 1735 return Error::success(); 1736 case BitstreamEntry::Record: 1737 // The interesting case. 1738 break; 1739 } 1740 1741 // Read a record. 1742 Record.clear(); 1743 ++NumMDRecordLoaded; 1744 unsigned Code = Stream.readRecord(Entry.ID, Record); 1745 switch (Code) { 1746 default: // Default behavior: ignore. 1747 break; 1748 case bitc::METADATA_KIND: { 1749 if (Error Err = parseMetadataKindRecord(Record)) 1750 return Err; 1751 break; 1752 } 1753 } 1754 } 1755 } 1756 1757 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) { 1758 Pimpl = std::move(RHS.Pimpl); 1759 return *this; 1760 } 1761 MetadataLoader::MetadataLoader(MetadataLoader &&RHS) 1762 : Pimpl(std::move(RHS.Pimpl)) {} 1763 1764 MetadataLoader::~MetadataLoader() = default; 1765 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule, 1766 BitcodeReaderValueList &ValueList, 1767 bool IsImporting, 1768 std::function<Type *(unsigned)> getTypeByID) 1769 : Pimpl(llvm::make_unique<MetadataLoaderImpl>( 1770 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {} 1771 1772 Error MetadataLoader::parseMetadata(bool ModuleLevel) { 1773 return Pimpl->parseMetadata(ModuleLevel); 1774 } 1775 1776 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); } 1777 1778 /// Return the given metadata, creating a replaceable forward reference if 1779 /// necessary. 1780 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) { 1781 return Pimpl->getMetadataFwdRefOrLoad(Idx); 1782 } 1783 1784 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) { 1785 return Pimpl->getMDNodeFwdRefOrNull(Idx); 1786 } 1787 1788 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) { 1789 return Pimpl->lookupSubprogramForFunction(F); 1790 } 1791 1792 Error MetadataLoader::parseMetadataAttachment( 1793 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 1794 return Pimpl->parseMetadataAttachment(F, InstructionList); 1795 } 1796 1797 Error MetadataLoader::parseMetadataKinds() { 1798 return Pimpl->parseMetadataKinds(); 1799 } 1800 1801 void MetadataLoader::setStripTBAA(bool StripTBAA) { 1802 return Pimpl->setStripTBAA(StripTBAA); 1803 } 1804 1805 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); } 1806 1807 unsigned MetadataLoader::size() const { return Pimpl->size(); } 1808 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); } 1809