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() > 17) 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 1221 MetadataList.assignValue(CU, NextMetadataNo); 1222 NextMetadataNo++; 1223 1224 // Move the Upgrade the list of subprograms. 1225 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11])) 1226 CUSubprograms.push_back({CU, SPs}); 1227 break; 1228 } 1229 case bitc::METADATA_SUBPROGRAM: { 1230 if (Record.size() < 18 || Record.size() > 20) 1231 return error("Invalid record"); 1232 1233 IsDistinct = 1234 (Record[0] & 1) || Record[8]; // All definitions should be distinct. 1235 // Version 1 has a Function as Record[15]. 1236 // Version 2 has removed Record[15]. 1237 // Version 3 has the Unit as Record[15]. 1238 // Version 4 added thisAdjustment. 1239 bool HasUnit = Record[0] >= 2; 1240 if (HasUnit && Record.size() < 19) 1241 return error("Invalid record"); 1242 Metadata *CUorFn = getMDOrNull(Record[15]); 1243 unsigned Offset = Record.size() >= 19 ? 1 : 0; 1244 bool HasFn = Offset && !HasUnit; 1245 bool HasThisAdj = Record.size() >= 20; 1246 DISubprogram *SP = GET_OR_DISTINCT( 1247 DISubprogram, (Context, 1248 getDITypeRefOrNull(Record[1]), // scope 1249 getMDString(Record[2]), // name 1250 getMDString(Record[3]), // linkageName 1251 getMDOrNull(Record[4]), // file 1252 Record[5], // line 1253 getMDOrNull(Record[6]), // type 1254 Record[7], // isLocal 1255 Record[8], // isDefinition 1256 Record[9], // scopeLine 1257 getDITypeRefOrNull(Record[10]), // containingType 1258 Record[11], // virtuality 1259 Record[12], // virtualIndex 1260 HasThisAdj ? Record[19] : 0, // thisAdjustment 1261 static_cast<DINode::DIFlags>(Record[13] // flags 1262 ), 1263 Record[14], // isOptimized 1264 HasUnit ? CUorFn : nullptr, // unit 1265 getMDOrNull(Record[15 + Offset]), // templateParams 1266 getMDOrNull(Record[16 + Offset]), // declaration 1267 getMDOrNull(Record[17 + Offset]) // variables 1268 )); 1269 MetadataList.assignValue(SP, NextMetadataNo); 1270 NextMetadataNo++; 1271 1272 // Upgrade sp->function mapping to function->sp mapping. 1273 if (HasFn) { 1274 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn)) 1275 if (auto *F = dyn_cast<Function>(CMD->getValue())) { 1276 if (F->isMaterializable()) 1277 // Defer until materialized; unmaterialized functions may not have 1278 // metadata. 1279 FunctionsWithSPs[F] = SP; 1280 else if (!F->empty()) 1281 F->setSubprogram(SP); 1282 } 1283 } 1284 break; 1285 } 1286 case bitc::METADATA_LEXICAL_BLOCK: { 1287 if (Record.size() != 5) 1288 return error("Invalid record"); 1289 1290 IsDistinct = Record[0]; 1291 MetadataList.assignValue( 1292 GET_OR_DISTINCT(DILexicalBlock, 1293 (Context, getMDOrNull(Record[1]), 1294 getMDOrNull(Record[2]), Record[3], Record[4])), 1295 NextMetadataNo); 1296 NextMetadataNo++; 1297 break; 1298 } 1299 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 1300 if (Record.size() != 4) 1301 return error("Invalid record"); 1302 1303 IsDistinct = Record[0]; 1304 MetadataList.assignValue( 1305 GET_OR_DISTINCT(DILexicalBlockFile, 1306 (Context, getMDOrNull(Record[1]), 1307 getMDOrNull(Record[2]), Record[3])), 1308 NextMetadataNo); 1309 NextMetadataNo++; 1310 break; 1311 } 1312 case bitc::METADATA_NAMESPACE: { 1313 if (Record.size() != 5) 1314 return error("Invalid record"); 1315 1316 IsDistinct = Record[0] & 1; 1317 bool ExportSymbols = Record[0] & 2; 1318 MetadataList.assignValue( 1319 GET_OR_DISTINCT(DINamespace, 1320 (Context, getMDOrNull(Record[1]), 1321 getMDOrNull(Record[2]), getMDString(Record[3]), 1322 Record[4], ExportSymbols)), 1323 NextMetadataNo); 1324 NextMetadataNo++; 1325 break; 1326 } 1327 case bitc::METADATA_MACRO: { 1328 if (Record.size() != 5) 1329 return error("Invalid record"); 1330 1331 IsDistinct = Record[0]; 1332 MetadataList.assignValue( 1333 GET_OR_DISTINCT(DIMacro, 1334 (Context, Record[1], Record[2], getMDString(Record[3]), 1335 getMDString(Record[4]))), 1336 NextMetadataNo); 1337 NextMetadataNo++; 1338 break; 1339 } 1340 case bitc::METADATA_MACRO_FILE: { 1341 if (Record.size() != 5) 1342 return error("Invalid record"); 1343 1344 IsDistinct = Record[0]; 1345 MetadataList.assignValue( 1346 GET_OR_DISTINCT(DIMacroFile, 1347 (Context, Record[1], Record[2], getMDOrNull(Record[3]), 1348 getMDOrNull(Record[4]))), 1349 NextMetadataNo); 1350 NextMetadataNo++; 1351 break; 1352 } 1353 case bitc::METADATA_TEMPLATE_TYPE: { 1354 if (Record.size() != 3) 1355 return error("Invalid record"); 1356 1357 IsDistinct = Record[0]; 1358 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 1359 (Context, getMDString(Record[1]), 1360 getDITypeRefOrNull(Record[2]))), 1361 NextMetadataNo); 1362 NextMetadataNo++; 1363 break; 1364 } 1365 case bitc::METADATA_TEMPLATE_VALUE: { 1366 if (Record.size() != 5) 1367 return error("Invalid record"); 1368 1369 IsDistinct = Record[0]; 1370 MetadataList.assignValue( 1371 GET_OR_DISTINCT(DITemplateValueParameter, 1372 (Context, Record[1], getMDString(Record[2]), 1373 getDITypeRefOrNull(Record[3]), 1374 getMDOrNull(Record[4]))), 1375 NextMetadataNo); 1376 NextMetadataNo++; 1377 break; 1378 } 1379 case bitc::METADATA_GLOBAL_VAR: { 1380 if (Record.size() < 11 || Record.size() > 12) 1381 return error("Invalid record"); 1382 1383 IsDistinct = Record[0] & 1; 1384 unsigned Version = Record[0] >> 1; 1385 1386 if (Version == 1) { 1387 MetadataList.assignValue( 1388 GET_OR_DISTINCT(DIGlobalVariable, 1389 (Context, getMDOrNull(Record[1]), 1390 getMDString(Record[2]), getMDString(Record[3]), 1391 getMDOrNull(Record[4]), Record[5], 1392 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1393 getMDOrNull(Record[10]), Record[11])), 1394 NextMetadataNo); 1395 NextMetadataNo++; 1396 } else if (Version == 0) { 1397 // Upgrade old metadata, which stored a global variable reference or a 1398 // ConstantInt here. 1399 Metadata *Expr = getMDOrNull(Record[9]); 1400 uint32_t AlignInBits = 0; 1401 if (Record.size() > 11) { 1402 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1403 return error("Alignment value is too large"); 1404 AlignInBits = Record[11]; 1405 } 1406 GlobalVariable *Attach = nullptr; 1407 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) { 1408 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) { 1409 Attach = GV; 1410 Expr = nullptr; 1411 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) { 1412 Expr = DIExpression::get(Context, 1413 {dwarf::DW_OP_constu, CI->getZExtValue(), 1414 dwarf::DW_OP_stack_value}); 1415 } else { 1416 Expr = nullptr; 1417 } 1418 } 1419 DIGlobalVariable *DGV = GET_OR_DISTINCT( 1420 DIGlobalVariable, 1421 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 1422 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 1423 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1424 getMDOrNull(Record[10]), AlignInBits)); 1425 1426 auto *DGVE = DIGlobalVariableExpression::getDistinct(Context, DGV, Expr); 1427 MetadataList.assignValue(DGVE, NextMetadataNo); 1428 NextMetadataNo++; 1429 if (Attach) 1430 Attach->addDebugInfo(DGVE); 1431 } else 1432 return error("Invalid record"); 1433 1434 break; 1435 } 1436 case bitc::METADATA_LOCAL_VAR: { 1437 // 10th field is for the obseleted 'inlinedAt:' field. 1438 if (Record.size() < 8 || Record.size() > 10) 1439 return error("Invalid record"); 1440 1441 IsDistinct = Record[0] & 1; 1442 bool HasAlignment = Record[0] & 2; 1443 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 1444 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that 1445 // this is newer version of record which doesn't have artifical tag. 1446 bool HasTag = !HasAlignment && Record.size() > 8; 1447 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]); 1448 uint32_t AlignInBits = 0; 1449 if (HasAlignment) { 1450 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1451 return error("Alignment value is too large"); 1452 AlignInBits = Record[8 + HasTag]; 1453 } 1454 MetadataList.assignValue( 1455 GET_OR_DISTINCT(DILocalVariable, 1456 (Context, getMDOrNull(Record[1 + HasTag]), 1457 getMDString(Record[2 + HasTag]), 1458 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 1459 getDITypeRefOrNull(Record[5 + HasTag]), 1460 Record[6 + HasTag], Flags, AlignInBits)), 1461 NextMetadataNo); 1462 NextMetadataNo++; 1463 break; 1464 } 1465 case bitc::METADATA_EXPRESSION: { 1466 if (Record.size() < 1) 1467 return error("Invalid record"); 1468 1469 IsDistinct = Record[0] & 1; 1470 bool HasOpFragment = Record[0] & 2; 1471 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1); 1472 if (!HasOpFragment) 1473 if (unsigned N = Elts.size()) 1474 if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece) 1475 Elts[N - 3] = dwarf::DW_OP_LLVM_fragment; 1476 1477 MetadataList.assignValue( 1478 GET_OR_DISTINCT(DIExpression, (Context, makeArrayRef(Record).slice(1))), 1479 NextMetadataNo); 1480 NextMetadataNo++; 1481 break; 1482 } 1483 case bitc::METADATA_GLOBAL_VAR_EXPR: { 1484 if (Record.size() != 3) 1485 return error("Invalid record"); 1486 1487 IsDistinct = Record[0]; 1488 MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression, 1489 (Context, getMDOrNull(Record[1]), 1490 getMDOrNull(Record[2]))), 1491 NextMetadataNo); 1492 NextMetadataNo++; 1493 break; 1494 } 1495 case bitc::METADATA_OBJC_PROPERTY: { 1496 if (Record.size() != 8) 1497 return error("Invalid record"); 1498 1499 IsDistinct = Record[0]; 1500 MetadataList.assignValue( 1501 GET_OR_DISTINCT(DIObjCProperty, 1502 (Context, getMDString(Record[1]), 1503 getMDOrNull(Record[2]), Record[3], 1504 getMDString(Record[4]), getMDString(Record[5]), 1505 Record[6], getDITypeRefOrNull(Record[7]))), 1506 NextMetadataNo); 1507 NextMetadataNo++; 1508 break; 1509 } 1510 case bitc::METADATA_IMPORTED_ENTITY: { 1511 if (Record.size() != 6) 1512 return error("Invalid record"); 1513 1514 IsDistinct = Record[0]; 1515 MetadataList.assignValue( 1516 GET_OR_DISTINCT(DIImportedEntity, 1517 (Context, Record[1], getMDOrNull(Record[2]), 1518 getDITypeRefOrNull(Record[3]), Record[4], 1519 getMDString(Record[5]))), 1520 NextMetadataNo); 1521 NextMetadataNo++; 1522 break; 1523 } 1524 case bitc::METADATA_STRING_OLD: { 1525 std::string String(Record.begin(), Record.end()); 1526 1527 // Test for upgrading !llvm.loop. 1528 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String); 1529 ++NumMDStringLoaded; 1530 Metadata *MD = MDString::get(Context, String); 1531 MetadataList.assignValue(MD, NextMetadataNo); 1532 NextMetadataNo++; 1533 break; 1534 } 1535 case bitc::METADATA_STRINGS: { 1536 auto CreateNextMDString = [&](StringRef Str) { 1537 ++NumMDStringLoaded; 1538 MetadataList.assignValue(MDString::get(Context, Str), NextMetadataNo); 1539 NextMetadataNo++; 1540 }; 1541 if (Error Err = parseMetadataStrings(Record, Blob, CreateNextMDString)) 1542 return Err; 1543 break; 1544 } 1545 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 1546 if (Record.size() % 2 == 0) 1547 return error("Invalid record"); 1548 unsigned ValueID = Record[0]; 1549 if (ValueID >= ValueList.size()) 1550 return error("Invalid record"); 1551 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) 1552 if (Error Err = parseGlobalObjectAttachment( 1553 *GO, ArrayRef<uint64_t>(Record).slice(1))) 1554 return Err; 1555 break; 1556 } 1557 case bitc::METADATA_KIND: { 1558 // Support older bitcode files that had METADATA_KIND records in a 1559 // block with METADATA_BLOCK_ID. 1560 if (Error Err = parseMetadataKindRecord(Record)) 1561 return Err; 1562 break; 1563 } 1564 } 1565 return Error::success(); 1566 #undef GET_OR_DISTINCT 1567 } 1568 1569 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings( 1570 ArrayRef<uint64_t> Record, StringRef Blob, 1571 function_ref<void(StringRef)> CallBack) { 1572 // All the MDStrings in the block are emitted together in a single 1573 // record. The strings are concatenated and stored in a blob along with 1574 // their sizes. 1575 if (Record.size() != 2) 1576 return error("Invalid record: metadata strings layout"); 1577 1578 unsigned NumStrings = Record[0]; 1579 unsigned StringsOffset = Record[1]; 1580 if (!NumStrings) 1581 return error("Invalid record: metadata strings with no strings"); 1582 if (StringsOffset > Blob.size()) 1583 return error("Invalid record: metadata strings corrupt offset"); 1584 1585 StringRef Lengths = Blob.slice(0, StringsOffset); 1586 SimpleBitstreamCursor R(Lengths); 1587 1588 StringRef Strings = Blob.drop_front(StringsOffset); 1589 do { 1590 if (R.AtEndOfStream()) 1591 return error("Invalid record: metadata strings bad length"); 1592 1593 unsigned Size = R.ReadVBR(6); 1594 if (Strings.size() < Size) 1595 return error("Invalid record: metadata strings truncated chars"); 1596 1597 CallBack(Strings.slice(0, Size)); 1598 Strings = Strings.drop_front(Size); 1599 } while (--NumStrings); 1600 1601 return Error::success(); 1602 } 1603 1604 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment( 1605 GlobalObject &GO, ArrayRef<uint64_t> Record) { 1606 assert(Record.size() % 2 == 0); 1607 for (unsigned I = 0, E = Record.size(); I != E; I += 2) { 1608 auto K = MDKindMap.find(Record[I]); 1609 if (K == MDKindMap.end()) 1610 return error("Invalid ID"); 1611 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]); 1612 if (!MD) 1613 return error("Invalid metadata attachment"); 1614 GO.addMetadata(K->second, *MD); 1615 } 1616 return Error::success(); 1617 } 1618 1619 /// Parse metadata attachments. 1620 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment( 1621 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 1622 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 1623 return error("Invalid record"); 1624 1625 SmallVector<uint64_t, 64> Record; 1626 PlaceholderQueue Placeholders; 1627 1628 while (true) { 1629 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1630 1631 switch (Entry.Kind) { 1632 case BitstreamEntry::SubBlock: // Handled for us already. 1633 case BitstreamEntry::Error: 1634 return error("Malformed block"); 1635 case BitstreamEntry::EndBlock: 1636 resolveForwardRefsAndPlaceholders(Placeholders); 1637 return Error::success(); 1638 case BitstreamEntry::Record: 1639 // The interesting case. 1640 break; 1641 } 1642 1643 // Read a metadata attachment record. 1644 Record.clear(); 1645 ++NumMDRecordLoaded; 1646 switch (Stream.readRecord(Entry.ID, Record)) { 1647 default: // Default behavior: ignore. 1648 break; 1649 case bitc::METADATA_ATTACHMENT: { 1650 unsigned RecordLength = Record.size(); 1651 if (Record.empty()) 1652 return error("Invalid record"); 1653 if (RecordLength % 2 == 0) { 1654 // A function attachment. 1655 if (Error Err = parseGlobalObjectAttachment(F, Record)) 1656 return Err; 1657 continue; 1658 } 1659 1660 // An instruction attachment. 1661 Instruction *Inst = InstructionList[Record[0]]; 1662 for (unsigned i = 1; i != RecordLength; i = i + 2) { 1663 unsigned Kind = Record[i]; 1664 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind); 1665 if (I == MDKindMap.end()) 1666 return error("Invalid ID"); 1667 if (I->second == LLVMContext::MD_tbaa && StripTBAA) 1668 continue; 1669 1670 auto Idx = Record[i + 1]; 1671 if (Idx < (MDStringRef.size() + GlobalMetadataBitPosIndex.size()) && 1672 !MetadataList.lookup(Idx)) { 1673 // Load the attachment if it is in the lazy-loadable range and hasn't 1674 // been loaded yet. 1675 lazyLoadOneMetadata(Idx, Placeholders); 1676 resolveForwardRefsAndPlaceholders(Placeholders); 1677 } 1678 1679 Metadata *Node = MetadataList.getMetadataFwdRef(Idx); 1680 if (isa<LocalAsMetadata>(Node)) 1681 // Drop the attachment. This used to be legal, but there's no 1682 // upgrade path. 1683 break; 1684 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 1685 if (!MD) 1686 return error("Invalid metadata attachment"); 1687 1688 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 1689 MD = upgradeInstructionLoopAttachment(*MD); 1690 1691 if (I->second == LLVMContext::MD_tbaa) { 1692 assert(!MD->isTemporary() && "should load MDs before attachments"); 1693 MD = UpgradeTBAANode(*MD); 1694 } 1695 Inst->setMetadata(I->second, MD); 1696 } 1697 break; 1698 } 1699 } 1700 } 1701 } 1702 1703 /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 1704 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord( 1705 SmallVectorImpl<uint64_t> &Record) { 1706 if (Record.size() < 2) 1707 return error("Invalid record"); 1708 1709 unsigned Kind = Record[0]; 1710 SmallString<8> Name(Record.begin() + 1, Record.end()); 1711 1712 unsigned NewKind = TheModule.getMDKindID(Name.str()); 1713 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1714 return error("Conflicting METADATA_KIND records"); 1715 return Error::success(); 1716 } 1717 1718 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 1719 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() { 1720 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 1721 return error("Invalid record"); 1722 1723 SmallVector<uint64_t, 64> Record; 1724 1725 // Read all the records. 1726 while (true) { 1727 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1728 1729 switch (Entry.Kind) { 1730 case BitstreamEntry::SubBlock: // Handled for us already. 1731 case BitstreamEntry::Error: 1732 return error("Malformed block"); 1733 case BitstreamEntry::EndBlock: 1734 return Error::success(); 1735 case BitstreamEntry::Record: 1736 // The interesting case. 1737 break; 1738 } 1739 1740 // Read a record. 1741 Record.clear(); 1742 ++NumMDRecordLoaded; 1743 unsigned Code = Stream.readRecord(Entry.ID, Record); 1744 switch (Code) { 1745 default: // Default behavior: ignore. 1746 break; 1747 case bitc::METADATA_KIND: { 1748 if (Error Err = parseMetadataKindRecord(Record)) 1749 return Err; 1750 break; 1751 } 1752 } 1753 } 1754 } 1755 1756 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) { 1757 Pimpl = std::move(RHS.Pimpl); 1758 return *this; 1759 } 1760 MetadataLoader::MetadataLoader(MetadataLoader &&RHS) 1761 : Pimpl(std::move(RHS.Pimpl)) {} 1762 1763 MetadataLoader::~MetadataLoader() = default; 1764 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule, 1765 BitcodeReaderValueList &ValueList, 1766 bool IsImporting, 1767 std::function<Type *(unsigned)> getTypeByID) 1768 : Pimpl(llvm::make_unique<MetadataLoaderImpl>( 1769 Stream, TheModule, ValueList, std::move(getTypeByID), IsImporting)) {} 1770 1771 Error MetadataLoader::parseMetadata(bool ModuleLevel) { 1772 return Pimpl->parseMetadata(ModuleLevel); 1773 } 1774 1775 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); } 1776 1777 /// Return the given metadata, creating a replaceable forward reference if 1778 /// necessary. 1779 Metadata *MetadataLoader::getMetadataFwdRefOrLoad(unsigned Idx) { 1780 return Pimpl->getMetadataFwdRefOrLoad(Idx); 1781 } 1782 1783 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) { 1784 return Pimpl->getMDNodeFwdRefOrNull(Idx); 1785 } 1786 1787 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) { 1788 return Pimpl->lookupSubprogramForFunction(F); 1789 } 1790 1791 Error MetadataLoader::parseMetadataAttachment( 1792 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 1793 return Pimpl->parseMetadataAttachment(F, InstructionList); 1794 } 1795 1796 Error MetadataLoader::parseMetadataKinds() { 1797 return Pimpl->parseMetadataKinds(); 1798 } 1799 1800 void MetadataLoader::setStripTBAA(bool StripTBAA) { 1801 return Pimpl->setStripTBAA(StripTBAA); 1802 } 1803 1804 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); } 1805 1806 unsigned MetadataLoader::size() const { return Pimpl->size(); } 1807 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); } 1808