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/None.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/SmallString.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/Triple.h" 23 #include "llvm/ADT/Twine.h" 24 #include "llvm/Bitcode/BitcodeReader.h" 25 #include "llvm/Bitcode/BitstreamReader.h" 26 #include "llvm/Bitcode/LLVMBitCodes.h" 27 #include "llvm/IR/Argument.h" 28 #include "llvm/IR/Attributes.h" 29 #include "llvm/IR/AutoUpgrade.h" 30 #include "llvm/IR/BasicBlock.h" 31 #include "llvm/IR/CallSite.h" 32 #include "llvm/IR/CallingConv.h" 33 #include "llvm/IR/Comdat.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DebugInfo.h" 37 #include "llvm/IR/DebugInfoMetadata.h" 38 #include "llvm/IR/DebugLoc.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/DiagnosticInfo.h" 41 #include "llvm/IR/DiagnosticPrinter.h" 42 #include "llvm/IR/Function.h" 43 #include "llvm/IR/GVMaterializer.h" 44 #include "llvm/IR/GlobalAlias.h" 45 #include "llvm/IR/GlobalIFunc.h" 46 #include "llvm/IR/GlobalIndirectSymbol.h" 47 #include "llvm/IR/GlobalObject.h" 48 #include "llvm/IR/GlobalValue.h" 49 #include "llvm/IR/GlobalVariable.h" 50 #include "llvm/IR/InlineAsm.h" 51 #include "llvm/IR/InstrTypes.h" 52 #include "llvm/IR/Instruction.h" 53 #include "llvm/IR/Instructions.h" 54 #include "llvm/IR/Intrinsics.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/Module.h" 57 #include "llvm/IR/ModuleSummaryIndex.h" 58 #include "llvm/IR/OperandTraits.h" 59 #include "llvm/IR/Operator.h" 60 #include "llvm/IR/TrackingMDRef.h" 61 #include "llvm/IR/Type.h" 62 #include "llvm/IR/ValueHandle.h" 63 #include "llvm/Support/AtomicOrdering.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/CommandLine.h" 66 #include "llvm/Support/Compiler.h" 67 #include "llvm/Support/Debug.h" 68 #include "llvm/Support/Error.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/ManagedStatic.h" 71 #include "llvm/Support/MemoryBuffer.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include <algorithm> 74 #include <cassert> 75 #include <cstddef> 76 #include <cstdint> 77 #include <deque> 78 #include <limits> 79 #include <map> 80 #include <memory> 81 #include <string> 82 #include <system_error> 83 #include <tuple> 84 #include <utility> 85 #include <vector> 86 87 using namespace llvm; 88 89 /// Flag whether we need to import full type definitions for ThinLTO. 90 /// Currently needed for Darwin and LLDB. 91 static cl::opt<bool> ImportFullTypeDefinitions( 92 "import-full-type-definitions", cl::init(false), cl::Hidden, 93 cl::desc("Import full type definitions for ThinLTO.")); 94 95 namespace { 96 97 static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; } 98 99 class BitcodeReaderMetadataList { 100 /// Keep track of the current number of ForwardReference in the list. 101 unsigned NumFwdRefs = 0; 102 /// Maintain the range [min-max] that needs to be inspected to resolve cycles. 103 /// This is the range of Metadata that have involved forward reference during 104 /// loading and that needs to be inspected to resolve cycles. It is purely an 105 /// optimization to avoid spending time resolving cycles outside of this 106 /// range, i.e. where there hasn't been any forward reference. 107 unsigned MinFwdRef = 0; 108 unsigned MaxFwdRef = 0; 109 /// Set to true if there was any FwdRef encountered. This is used to track if 110 /// we need to resolve cycles after loading metadatas. 111 bool AnyFwdRefs = false; 112 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 /// Structures for resolving old type refs. 120 struct { 121 SmallDenseMap<MDString *, TempMDTuple, 1> Unknown; 122 SmallDenseMap<MDString *, DICompositeType *, 1> Final; 123 SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls; 124 SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays; 125 } OldTypeRefs; 126 127 LLVMContext &Context; 128 129 public: 130 BitcodeReaderMetadataList(LLVMContext &C) : Context(C) {} 131 132 // vector compatibility methods 133 unsigned size() const { return MetadataPtrs.size(); } 134 void resize(unsigned N) { MetadataPtrs.resize(N); } 135 void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); } 136 void clear() { MetadataPtrs.clear(); } 137 Metadata *back() const { return MetadataPtrs.back(); } 138 void pop_back() { MetadataPtrs.pop_back(); } 139 bool empty() const { return MetadataPtrs.empty(); } 140 141 Metadata *operator[](unsigned i) const { 142 assert(i < MetadataPtrs.size()); 143 return MetadataPtrs[i]; 144 } 145 146 Metadata *lookup(unsigned I) const { 147 if (I < MetadataPtrs.size()) 148 return MetadataPtrs[I]; 149 return nullptr; 150 } 151 152 void shrinkTo(unsigned N) { 153 assert(N <= size() && "Invalid shrinkTo request!"); 154 assert(!AnyFwdRefs && "Unexpected forward refs"); 155 MetadataPtrs.resize(N); 156 } 157 158 /// Return the given metadata, creating a replaceable forward reference if 159 /// necessary. 160 Metadata *getMetadataFwdRef(unsigned Idx); 161 162 /// Return the the given metadata only if it is fully resolved. 163 /// 164 /// Gives the same result as \a lookup(), unless \a MDNode::isResolved() 165 /// would give \c false. 166 Metadata *getMetadataIfResolved(unsigned Idx); 167 168 MDNode *getMDNodeFwdRefOrNull(unsigned Idx); 169 void assignValue(Metadata *MD, unsigned Idx); 170 void tryToResolveCycles(); 171 bool hasFwdRefs() const { return AnyFwdRefs; } 172 173 /// Upgrade a type that had an MDString reference. 174 void addTypeRef(MDString &UUID, DICompositeType &CT); 175 176 /// Upgrade a type that had an MDString reference. 177 Metadata *upgradeTypeRef(Metadata *MaybeUUID); 178 179 /// Upgrade a type ref array that may have MDString references. 180 Metadata *upgradeTypeRefArray(Metadata *MaybeTuple); 181 182 private: 183 Metadata *resolveTypeRefArray(Metadata *MaybeTuple); 184 }; 185 186 void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) { 187 if (Idx == size()) { 188 push_back(MD); 189 return; 190 } 191 192 if (Idx >= size()) 193 resize(Idx + 1); 194 195 TrackingMDRef &OldMD = MetadataPtrs[Idx]; 196 if (!OldMD) { 197 OldMD.reset(MD); 198 return; 199 } 200 201 // If there was a forward reference to this value, replace it. 202 TempMDTuple PrevMD(cast<MDTuple>(OldMD.get())); 203 PrevMD->replaceAllUsesWith(MD); 204 --NumFwdRefs; 205 } 206 207 Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) { 208 if (Idx >= size()) 209 resize(Idx + 1); 210 211 if (Metadata *MD = MetadataPtrs[Idx]) 212 return MD; 213 214 // Track forward refs to be resolved later. 215 if (AnyFwdRefs) { 216 MinFwdRef = std::min(MinFwdRef, Idx); 217 MaxFwdRef = std::max(MaxFwdRef, Idx); 218 } else { 219 AnyFwdRefs = true; 220 MinFwdRef = MaxFwdRef = Idx; 221 } 222 ++NumFwdRefs; 223 224 // Create and return a placeholder, which will later be RAUW'd. 225 Metadata *MD = MDNode::getTemporary(Context, None).release(); 226 MetadataPtrs[Idx].reset(MD); 227 return MD; 228 } 229 230 Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) { 231 Metadata *MD = lookup(Idx); 232 if (auto *N = dyn_cast_or_null<MDNode>(MD)) 233 if (!N->isResolved()) 234 return nullptr; 235 return MD; 236 } 237 238 MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) { 239 return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx)); 240 } 241 242 void BitcodeReaderMetadataList::tryToResolveCycles() { 243 if (NumFwdRefs) 244 // Still forward references... can't resolve cycles. 245 return; 246 247 bool DidReplaceTypeRefs = false; 248 249 // Give up on finding a full definition for any forward decls that remain. 250 for (const auto &Ref : OldTypeRefs.FwdDecls) 251 OldTypeRefs.Final.insert(Ref); 252 OldTypeRefs.FwdDecls.clear(); 253 254 // Upgrade from old type ref arrays. In strange cases, this could add to 255 // OldTypeRefs.Unknown. 256 for (const auto &Array : OldTypeRefs.Arrays) { 257 DidReplaceTypeRefs = true; 258 Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get())); 259 } 260 OldTypeRefs.Arrays.clear(); 261 262 // Replace old string-based type refs with the resolved node, if possible. 263 // If we haven't seen the node, leave it to the verifier to complain about 264 // the invalid string reference. 265 for (const auto &Ref : OldTypeRefs.Unknown) { 266 DidReplaceTypeRefs = true; 267 if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first)) 268 Ref.second->replaceAllUsesWith(CT); 269 else 270 Ref.second->replaceAllUsesWith(Ref.first); 271 } 272 OldTypeRefs.Unknown.clear(); 273 274 // Make sure all the upgraded types are resolved. 275 if (DidReplaceTypeRefs) { 276 AnyFwdRefs = true; 277 MinFwdRef = 0; 278 MaxFwdRef = MetadataPtrs.size() - 1; 279 } 280 281 if (!AnyFwdRefs) 282 // Nothing to do. 283 return; 284 285 // Resolve any cycles. 286 for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) { 287 auto &MD = MetadataPtrs[I]; 288 auto *N = dyn_cast_or_null<MDNode>(MD); 289 if (!N) 290 continue; 291 292 assert(!N->isTemporary() && "Unexpected forward reference"); 293 N->resolveCycles(); 294 } 295 296 // Make sure we return early again until there's another forward ref. 297 AnyFwdRefs = false; 298 } 299 300 void BitcodeReaderMetadataList::addTypeRef(MDString &UUID, 301 DICompositeType &CT) { 302 assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID"); 303 if (CT.isForwardDecl()) 304 OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT)); 305 else 306 OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT)); 307 } 308 309 Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) { 310 auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID); 311 if (LLVM_LIKELY(!UUID)) 312 return MaybeUUID; 313 314 if (auto *CT = OldTypeRefs.Final.lookup(UUID)) 315 return CT; 316 317 auto &Ref = OldTypeRefs.Unknown[UUID]; 318 if (!Ref) 319 Ref = MDNode::getTemporary(Context, None); 320 return Ref.get(); 321 } 322 323 Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) { 324 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple); 325 if (!Tuple || Tuple->isDistinct()) 326 return MaybeTuple; 327 328 // Look through the array immediately if possible. 329 if (!Tuple->isTemporary()) 330 return resolveTypeRefArray(Tuple); 331 332 // Create and return a placeholder to use for now. Eventually 333 // resolveTypeRefArrays() will be resolve this forward reference. 334 OldTypeRefs.Arrays.emplace_back( 335 std::piecewise_construct, std::forward_as_tuple(Tuple), 336 std::forward_as_tuple(MDTuple::getTemporary(Context, None))); 337 return OldTypeRefs.Arrays.back().second.get(); 338 } 339 340 Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) { 341 auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple); 342 if (!Tuple || Tuple->isDistinct()) 343 return MaybeTuple; 344 345 // Look through the DITypeRefArray, upgrading each DITypeRef. 346 SmallVector<Metadata *, 32> Ops; 347 Ops.reserve(Tuple->getNumOperands()); 348 for (Metadata *MD : Tuple->operands()) 349 Ops.push_back(upgradeTypeRef(MD)); 350 351 return MDTuple::get(Context, Ops); 352 } 353 354 namespace { 355 356 class PlaceholderQueue { 357 // Placeholders would thrash around when moved, so store in a std::deque 358 // instead of some sort of vector. 359 std::deque<DistinctMDOperandPlaceholder> PHs; 360 361 public: 362 DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID); 363 void flush(BitcodeReaderMetadataList &MetadataList); 364 }; 365 366 } // end anonymous namespace 367 368 DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) { 369 PHs.emplace_back(ID); 370 return PHs.back(); 371 } 372 373 void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) { 374 while (!PHs.empty()) { 375 PHs.front().replaceUseWith( 376 MetadataList.getMetadataFwdRef(PHs.front().getID())); 377 PHs.pop_front(); 378 } 379 } 380 381 } // anonynous namespace 382 383 class MetadataLoader::MetadataLoaderImpl { 384 BitcodeReaderMetadataList MetadataList; 385 BitcodeReaderValueList &ValueList; 386 BitstreamCursor &Stream; 387 LLVMContext &Context; 388 Module &TheModule; 389 std::function<Type *(unsigned)> getTypeByID; 390 391 /// Functions that need to be matched with subprograms when upgrading old 392 /// metadata. 393 SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs; 394 395 // Map the bitcode's custom MDKind ID to the Module's MDKind ID. 396 DenseMap<unsigned, unsigned> MDKindMap; 397 398 bool StripTBAA = false; 399 bool HasSeenOldLoopTags = false; 400 401 /// True if metadata is being parsed for a module being ThinLTO imported. 402 bool IsImporting = false; 403 404 Error parseMetadataStrings(ArrayRef<uint64_t> Record, StringRef Blob, 405 unsigned &NextMetadataNo); 406 Error parseGlobalObjectAttachment(GlobalObject &GO, 407 ArrayRef<uint64_t> Record); 408 Error parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record); 409 410 public: 411 MetadataLoaderImpl(BitstreamCursor &Stream, Module &TheModule, 412 BitcodeReaderValueList &ValueList, 413 std::function<Type *(unsigned)> getTypeByID, 414 bool IsImporting) 415 : MetadataList(TheModule.getContext()), ValueList(ValueList), 416 Stream(Stream), Context(TheModule.getContext()), TheModule(TheModule), 417 getTypeByID(getTypeByID), IsImporting(IsImporting) {} 418 419 Error parseMetadata(bool ModuleLevel); 420 421 bool hasFwdRefs() const { return MetadataList.hasFwdRefs(); } 422 Metadata *getMetadataFwdRef(unsigned Idx) { 423 return MetadataList.getMetadataFwdRef(Idx); 424 } 425 426 MDNode *getMDNodeFwdRefOrNull(unsigned Idx) { 427 return MetadataList.getMDNodeFwdRefOrNull(Idx); 428 } 429 430 DISubprogram *lookupSubprogramForFunction(Function *F) { 431 return FunctionsWithSPs.lookup(F); 432 } 433 434 bool hasSeenOldLoopTags() { return HasSeenOldLoopTags; } 435 436 Error parseMetadataAttachment( 437 Function &F, const SmallVectorImpl<Instruction *> &InstructionList); 438 439 Error parseMetadataKinds(); 440 441 void setStripTBAA(bool Value) { StripTBAA = Value; } 442 bool isStrippingTBAA() { return StripTBAA; } 443 444 unsigned size() const { return MetadataList.size(); } 445 void shrinkTo(unsigned N) { MetadataList.shrinkTo(N); } 446 }; 447 448 Error error(const Twine &Message) { 449 return make_error<StringError>( 450 Message, make_error_code(BitcodeError::CorruptedBitcode)); 451 } 452 453 /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing 454 /// module level metadata. 455 Error MetadataLoader::MetadataLoaderImpl::parseMetadata(bool ModuleLevel) { 456 if (!ModuleLevel && MetadataList.hasFwdRefs()) 457 return error("Invalid metadata: fwd refs into function blocks"); 458 459 if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID)) 460 return error("Invalid record"); 461 462 unsigned NextMetadataNo = MetadataList.size(); 463 std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms; 464 SmallVector<uint64_t, 64> Record; 465 466 PlaceholderQueue Placeholders; 467 bool IsDistinct; 468 auto getMD = [&](unsigned ID) -> Metadata * { 469 if (!IsDistinct) 470 return MetadataList.getMetadataFwdRef(ID); 471 if (auto *MD = MetadataList.getMetadataIfResolved(ID)) 472 return MD; 473 return &Placeholders.getPlaceholderOp(ID); 474 }; 475 auto getMDOrNull = [&](unsigned ID) -> Metadata * { 476 if (ID) 477 return getMD(ID - 1); 478 return nullptr; 479 }; 480 auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * { 481 if (ID) 482 return MetadataList.getMetadataFwdRef(ID - 1); 483 return nullptr; 484 }; 485 auto getMDString = [&](unsigned ID) -> MDString * { 486 // This requires that the ID is not really a forward reference. In 487 // particular, the MDString must already have been resolved. 488 return cast_or_null<MDString>(getMDOrNull(ID)); 489 }; 490 491 // Support for old type refs. 492 auto getDITypeRefOrNull = [&](unsigned ID) { 493 return MetadataList.upgradeTypeRef(getMDOrNull(ID)); 494 }; 495 496 #define GET_OR_DISTINCT(CLASS, ARGS) \ 497 (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS) 498 499 // Read all the records. 500 while (true) { 501 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 502 503 switch (Entry.Kind) { 504 case BitstreamEntry::SubBlock: // Handled for us already. 505 case BitstreamEntry::Error: 506 return error("Malformed block"); 507 case BitstreamEntry::EndBlock: 508 // Upgrade old-style CU <-> SP pointers to point from SP to CU. 509 for (auto CU_SP : CUSubprograms) 510 if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second)) 511 for (auto &Op : SPs->operands()) 512 if (auto *SP = dyn_cast_or_null<MDNode>(Op)) 513 SP->replaceOperandWith(7, CU_SP.first); 514 515 MetadataList.tryToResolveCycles(); 516 Placeholders.flush(MetadataList); 517 return Error::success(); 518 case BitstreamEntry::Record: 519 // The interesting case. 520 break; 521 } 522 523 // Read a record. 524 Record.clear(); 525 StringRef Blob; 526 unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob); 527 IsDistinct = false; 528 switch (Code) { 529 default: // Default behavior: ignore. 530 break; 531 case bitc::METADATA_NAME: { 532 // Read name of the named metadata. 533 SmallString<8> Name(Record.begin(), Record.end()); 534 Record.clear(); 535 Code = Stream.ReadCode(); 536 537 unsigned NextBitCode = Stream.readRecord(Code, Record); 538 if (NextBitCode != bitc::METADATA_NAMED_NODE) 539 return error("METADATA_NAME not followed by METADATA_NAMED_NODE"); 540 541 // Read named metadata elements. 542 unsigned Size = Record.size(); 543 NamedMDNode *NMD = TheModule.getOrInsertNamedMetadata(Name); 544 for (unsigned i = 0; i != Size; ++i) { 545 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]); 546 if (!MD) 547 return error("Invalid record"); 548 NMD->addOperand(MD); 549 } 550 break; 551 } 552 case bitc::METADATA_OLD_FN_NODE: { 553 // FIXME: Remove in 4.0. 554 // This is a LocalAsMetadata record, the only type of function-local 555 // metadata. 556 if (Record.size() % 2 == 1) 557 return error("Invalid record"); 558 559 // If this isn't a LocalAsMetadata record, we're dropping it. This used 560 // to be legal, but there's no upgrade path. 561 auto dropRecord = [&] { 562 MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++); 563 }; 564 if (Record.size() != 2) { 565 dropRecord(); 566 break; 567 } 568 569 Type *Ty = getTypeByID(Record[0]); 570 if (Ty->isMetadataTy() || Ty->isVoidTy()) { 571 dropRecord(); 572 break; 573 } 574 575 MetadataList.assignValue( 576 LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 577 NextMetadataNo++); 578 break; 579 } 580 case bitc::METADATA_OLD_NODE: { 581 // FIXME: Remove in 4.0. 582 if (Record.size() % 2 == 1) 583 return error("Invalid record"); 584 585 unsigned Size = Record.size(); 586 SmallVector<Metadata *, 8> Elts; 587 for (unsigned i = 0; i != Size; i += 2) { 588 Type *Ty = getTypeByID(Record[i]); 589 if (!Ty) 590 return error("Invalid record"); 591 if (Ty->isMetadataTy()) 592 Elts.push_back(getMD(Record[i + 1])); 593 else if (!Ty->isVoidTy()) { 594 auto *MD = 595 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty)); 596 assert(isa<ConstantAsMetadata>(MD) && 597 "Expected non-function-local metadata"); 598 Elts.push_back(MD); 599 } else 600 Elts.push_back(nullptr); 601 } 602 MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++); 603 break; 604 } 605 case bitc::METADATA_VALUE: { 606 if (Record.size() != 2) 607 return error("Invalid record"); 608 609 Type *Ty = getTypeByID(Record[0]); 610 if (Ty->isMetadataTy() || Ty->isVoidTy()) 611 return error("Invalid record"); 612 613 MetadataList.assignValue( 614 ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)), 615 NextMetadataNo++); 616 break; 617 } 618 case bitc::METADATA_DISTINCT_NODE: 619 IsDistinct = true; 620 LLVM_FALLTHROUGH; 621 case bitc::METADATA_NODE: { 622 SmallVector<Metadata *, 8> Elts; 623 Elts.reserve(Record.size()); 624 for (unsigned ID : Record) 625 Elts.push_back(getMDOrNull(ID)); 626 MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts) 627 : MDNode::get(Context, Elts), 628 NextMetadataNo++); 629 break; 630 } 631 case bitc::METADATA_LOCATION: { 632 if (Record.size() != 5) 633 return error("Invalid record"); 634 635 IsDistinct = Record[0]; 636 unsigned Line = Record[1]; 637 unsigned Column = Record[2]; 638 Metadata *Scope = getMD(Record[3]); 639 Metadata *InlinedAt = getMDOrNull(Record[4]); 640 MetadataList.assignValue( 641 GET_OR_DISTINCT(DILocation, 642 (Context, Line, Column, Scope, InlinedAt)), 643 NextMetadataNo++); 644 break; 645 } 646 case bitc::METADATA_GENERIC_DEBUG: { 647 if (Record.size() < 4) 648 return error("Invalid record"); 649 650 IsDistinct = Record[0]; 651 unsigned Tag = Record[1]; 652 unsigned Version = Record[2]; 653 654 if (Tag >= 1u << 16 || Version != 0) 655 return error("Invalid record"); 656 657 auto *Header = getMDString(Record[3]); 658 SmallVector<Metadata *, 8> DwarfOps; 659 for (unsigned I = 4, E = Record.size(); I != E; ++I) 660 DwarfOps.push_back(getMDOrNull(Record[I])); 661 MetadataList.assignValue( 662 GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)), 663 NextMetadataNo++); 664 break; 665 } 666 case bitc::METADATA_SUBRANGE: { 667 if (Record.size() != 3) 668 return error("Invalid record"); 669 670 IsDistinct = Record[0]; 671 MetadataList.assignValue( 672 GET_OR_DISTINCT(DISubrange, 673 (Context, Record[1], unrotateSign(Record[2]))), 674 NextMetadataNo++); 675 break; 676 } 677 case bitc::METADATA_ENUMERATOR: { 678 if (Record.size() != 3) 679 return error("Invalid record"); 680 681 IsDistinct = Record[0]; 682 MetadataList.assignValue( 683 GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]), 684 getMDString(Record[2]))), 685 NextMetadataNo++); 686 break; 687 } 688 case bitc::METADATA_BASIC_TYPE: { 689 if (Record.size() != 6) 690 return error("Invalid record"); 691 692 IsDistinct = Record[0]; 693 MetadataList.assignValue( 694 GET_OR_DISTINCT(DIBasicType, 695 (Context, Record[1], getMDString(Record[2]), 696 Record[3], Record[4], Record[5])), 697 NextMetadataNo++); 698 break; 699 } 700 case bitc::METADATA_DERIVED_TYPE: { 701 if (Record.size() != 12) 702 return error("Invalid record"); 703 704 IsDistinct = Record[0]; 705 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 706 MetadataList.assignValue( 707 GET_OR_DISTINCT(DIDerivedType, 708 (Context, Record[1], getMDString(Record[2]), 709 getMDOrNull(Record[3]), Record[4], 710 getDITypeRefOrNull(Record[5]), 711 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 712 Record[9], Flags, getDITypeRefOrNull(Record[11]))), 713 NextMetadataNo++); 714 break; 715 } 716 case bitc::METADATA_COMPOSITE_TYPE: { 717 if (Record.size() != 16) 718 return error("Invalid record"); 719 720 // If we have a UUID and this is not a forward declaration, lookup the 721 // mapping. 722 IsDistinct = Record[0] & 0x1; 723 bool IsNotUsedInTypeRef = Record[0] >= 2; 724 unsigned Tag = Record[1]; 725 MDString *Name = getMDString(Record[2]); 726 Metadata *File = getMDOrNull(Record[3]); 727 unsigned Line = Record[4]; 728 Metadata *Scope = getDITypeRefOrNull(Record[5]); 729 Metadata *BaseType = nullptr; 730 uint64_t SizeInBits = Record[7]; 731 if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max()) 732 return error("Alignment value is too large"); 733 uint32_t AlignInBits = Record[8]; 734 uint64_t OffsetInBits = 0; 735 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]); 736 Metadata *Elements = nullptr; 737 unsigned RuntimeLang = Record[12]; 738 Metadata *VTableHolder = nullptr; 739 Metadata *TemplateParams = nullptr; 740 auto *Identifier = getMDString(Record[15]); 741 // If this module is being parsed so that it can be ThinLTO imported 742 // into another module, composite types only need to be imported 743 // as type declarations (unless full type definitions requested). 744 // Create type declarations up front to save memory. Also, buildODRType 745 // handles the case where this is type ODRed with a definition needed 746 // by the importing module, in which case the existing definition is 747 // used. 748 if (IsImporting && !ImportFullTypeDefinitions && 749 (Tag == dwarf::DW_TAG_enumeration_type || 750 Tag == dwarf::DW_TAG_class_type || 751 Tag == dwarf::DW_TAG_structure_type || 752 Tag == dwarf::DW_TAG_union_type)) { 753 Flags = Flags | DINode::FlagFwdDecl; 754 } else { 755 BaseType = getDITypeRefOrNull(Record[6]); 756 OffsetInBits = Record[9]; 757 Elements = getMDOrNull(Record[11]); 758 VTableHolder = getDITypeRefOrNull(Record[13]); 759 TemplateParams = getMDOrNull(Record[14]); 760 } 761 DICompositeType *CT = nullptr; 762 if (Identifier) 763 CT = DICompositeType::buildODRType( 764 Context, *Identifier, Tag, Name, File, Line, Scope, BaseType, 765 SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang, 766 VTableHolder, TemplateParams); 767 768 // Create a node if we didn't get a lazy ODR type. 769 if (!CT) 770 CT = GET_OR_DISTINCT(DICompositeType, 771 (Context, Tag, Name, File, Line, Scope, BaseType, 772 SizeInBits, AlignInBits, OffsetInBits, Flags, 773 Elements, RuntimeLang, VTableHolder, 774 TemplateParams, Identifier)); 775 if (!IsNotUsedInTypeRef && Identifier) 776 MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT)); 777 778 MetadataList.assignValue(CT, NextMetadataNo++); 779 break; 780 } 781 case bitc::METADATA_SUBROUTINE_TYPE: { 782 if (Record.size() < 3 || Record.size() > 4) 783 return error("Invalid record"); 784 bool IsOldTypeRefArray = Record[0] < 2; 785 unsigned CC = (Record.size() > 3) ? Record[3] : 0; 786 787 IsDistinct = Record[0] & 0x1; 788 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]); 789 Metadata *Types = getMDOrNull(Record[2]); 790 if (LLVM_UNLIKELY(IsOldTypeRefArray)) 791 Types = MetadataList.upgradeTypeRefArray(Types); 792 793 MetadataList.assignValue( 794 GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)), 795 NextMetadataNo++); 796 break; 797 } 798 799 case bitc::METADATA_MODULE: { 800 if (Record.size() != 6) 801 return error("Invalid record"); 802 803 IsDistinct = Record[0]; 804 MetadataList.assignValue( 805 GET_OR_DISTINCT(DIModule, 806 (Context, getMDOrNull(Record[1]), 807 getMDString(Record[2]), getMDString(Record[3]), 808 getMDString(Record[4]), getMDString(Record[5]))), 809 NextMetadataNo++); 810 break; 811 } 812 813 case bitc::METADATA_FILE: { 814 if (Record.size() != 3) 815 return error("Invalid record"); 816 817 IsDistinct = Record[0]; 818 MetadataList.assignValue( 819 GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]), 820 getMDString(Record[2]))), 821 NextMetadataNo++); 822 break; 823 } 824 case bitc::METADATA_COMPILE_UNIT: { 825 if (Record.size() < 14 || Record.size() > 17) 826 return error("Invalid record"); 827 828 // Ignore Record[0], which indicates whether this compile unit is 829 // distinct. It's always distinct. 830 IsDistinct = true; 831 auto *CU = DICompileUnit::getDistinct( 832 Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]), 833 Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]), 834 Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]), 835 getMDOrNull(Record[12]), getMDOrNull(Record[13]), 836 Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]), 837 Record.size() <= 14 ? 0 : Record[14], 838 Record.size() <= 16 ? true : Record[16]); 839 840 MetadataList.assignValue(CU, NextMetadataNo++); 841 842 // Move the Upgrade the list of subprograms. 843 if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11])) 844 CUSubprograms.push_back({CU, SPs}); 845 break; 846 } 847 case bitc::METADATA_SUBPROGRAM: { 848 if (Record.size() < 18 || Record.size() > 20) 849 return error("Invalid record"); 850 851 IsDistinct = 852 (Record[0] & 1) || Record[8]; // All definitions should be distinct. 853 // Version 1 has a Function as Record[15]. 854 // Version 2 has removed Record[15]. 855 // Version 3 has the Unit as Record[15]. 856 // Version 4 added thisAdjustment. 857 bool HasUnit = Record[0] >= 2; 858 if (HasUnit && Record.size() < 19) 859 return error("Invalid record"); 860 Metadata *CUorFn = getMDOrNull(Record[15]); 861 unsigned Offset = Record.size() >= 19 ? 1 : 0; 862 bool HasFn = Offset && !HasUnit; 863 bool HasThisAdj = Record.size() >= 20; 864 DISubprogram *SP = GET_OR_DISTINCT( 865 DISubprogram, (Context, 866 getDITypeRefOrNull(Record[1]), // scope 867 getMDString(Record[2]), // name 868 getMDString(Record[3]), // linkageName 869 getMDOrNull(Record[4]), // file 870 Record[5], // line 871 getMDOrNull(Record[6]), // type 872 Record[7], // isLocal 873 Record[8], // isDefinition 874 Record[9], // scopeLine 875 getDITypeRefOrNull(Record[10]), // containingType 876 Record[11], // virtuality 877 Record[12], // virtualIndex 878 HasThisAdj ? Record[19] : 0, // thisAdjustment 879 static_cast<DINode::DIFlags>(Record[13] // flags 880 ), 881 Record[14], // isOptimized 882 HasUnit ? CUorFn : nullptr, // unit 883 getMDOrNull(Record[15 + Offset]), // templateParams 884 getMDOrNull(Record[16 + Offset]), // declaration 885 getMDOrNull(Record[17 + Offset]) // variables 886 )); 887 MetadataList.assignValue(SP, NextMetadataNo++); 888 889 // Upgrade sp->function mapping to function->sp mapping. 890 if (HasFn) { 891 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn)) 892 if (auto *F = dyn_cast<Function>(CMD->getValue())) { 893 if (F->isMaterializable()) 894 // Defer until materialized; unmaterialized functions may not have 895 // metadata. 896 FunctionsWithSPs[F] = SP; 897 else if (!F->empty()) 898 F->setSubprogram(SP); 899 } 900 } 901 break; 902 } 903 case bitc::METADATA_LEXICAL_BLOCK: { 904 if (Record.size() != 5) 905 return error("Invalid record"); 906 907 IsDistinct = Record[0]; 908 MetadataList.assignValue( 909 GET_OR_DISTINCT(DILexicalBlock, 910 (Context, getMDOrNull(Record[1]), 911 getMDOrNull(Record[2]), Record[3], Record[4])), 912 NextMetadataNo++); 913 break; 914 } 915 case bitc::METADATA_LEXICAL_BLOCK_FILE: { 916 if (Record.size() != 4) 917 return error("Invalid record"); 918 919 IsDistinct = Record[0]; 920 MetadataList.assignValue( 921 GET_OR_DISTINCT(DILexicalBlockFile, 922 (Context, getMDOrNull(Record[1]), 923 getMDOrNull(Record[2]), Record[3])), 924 NextMetadataNo++); 925 break; 926 } 927 case bitc::METADATA_NAMESPACE: { 928 if (Record.size() != 5) 929 return error("Invalid record"); 930 931 IsDistinct = Record[0] & 1; 932 bool ExportSymbols = Record[0] & 2; 933 MetadataList.assignValue( 934 GET_OR_DISTINCT(DINamespace, 935 (Context, getMDOrNull(Record[1]), 936 getMDOrNull(Record[2]), getMDString(Record[3]), 937 Record[4], ExportSymbols)), 938 NextMetadataNo++); 939 break; 940 } 941 case bitc::METADATA_MACRO: { 942 if (Record.size() != 5) 943 return error("Invalid record"); 944 945 IsDistinct = Record[0]; 946 MetadataList.assignValue( 947 GET_OR_DISTINCT(DIMacro, 948 (Context, Record[1], Record[2], 949 getMDString(Record[3]), getMDString(Record[4]))), 950 NextMetadataNo++); 951 break; 952 } 953 case bitc::METADATA_MACRO_FILE: { 954 if (Record.size() != 5) 955 return error("Invalid record"); 956 957 IsDistinct = Record[0]; 958 MetadataList.assignValue( 959 GET_OR_DISTINCT(DIMacroFile, 960 (Context, Record[1], Record[2], 961 getMDOrNull(Record[3]), getMDOrNull(Record[4]))), 962 NextMetadataNo++); 963 break; 964 } 965 case bitc::METADATA_TEMPLATE_TYPE: { 966 if (Record.size() != 3) 967 return error("Invalid record"); 968 969 IsDistinct = Record[0]; 970 MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter, 971 (Context, getMDString(Record[1]), 972 getDITypeRefOrNull(Record[2]))), 973 NextMetadataNo++); 974 break; 975 } 976 case bitc::METADATA_TEMPLATE_VALUE: { 977 if (Record.size() != 5) 978 return error("Invalid record"); 979 980 IsDistinct = Record[0]; 981 MetadataList.assignValue( 982 GET_OR_DISTINCT(DITemplateValueParameter, 983 (Context, Record[1], getMDString(Record[2]), 984 getDITypeRefOrNull(Record[3]), 985 getMDOrNull(Record[4]))), 986 NextMetadataNo++); 987 break; 988 } 989 case bitc::METADATA_GLOBAL_VAR: { 990 if (Record.size() < 11 || Record.size() > 12) 991 return error("Invalid record"); 992 993 IsDistinct = Record[0] & 1; 994 unsigned Version = Record[0] >> 1; 995 996 if (Version == 1) { 997 MetadataList.assignValue( 998 GET_OR_DISTINCT(DIGlobalVariable, 999 (Context, getMDOrNull(Record[1]), 1000 getMDString(Record[2]), getMDString(Record[3]), 1001 getMDOrNull(Record[4]), Record[5], 1002 getDITypeRefOrNull(Record[6]), Record[7], 1003 Record[8], getMDOrNull(Record[10]), Record[11])), 1004 NextMetadataNo++); 1005 } else if (Version == 0) { 1006 // Upgrade old metadata, which stored a global variable reference or a 1007 // ConstantInt here. 1008 Metadata *Expr = getMDOrNull(Record[9]); 1009 uint32_t AlignInBits = 0; 1010 if (Record.size() > 11) { 1011 if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1012 return error("Alignment value is too large"); 1013 AlignInBits = Record[11]; 1014 } 1015 GlobalVariable *Attach = nullptr; 1016 if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) { 1017 if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) { 1018 Attach = GV; 1019 Expr = nullptr; 1020 } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) { 1021 Expr = DIExpression::get(Context, 1022 {dwarf::DW_OP_constu, CI->getZExtValue(), 1023 dwarf::DW_OP_stack_value}); 1024 } else { 1025 Expr = nullptr; 1026 } 1027 } 1028 DIGlobalVariable *DGV = GET_OR_DISTINCT( 1029 DIGlobalVariable, 1030 (Context, getMDOrNull(Record[1]), getMDString(Record[2]), 1031 getMDString(Record[3]), getMDOrNull(Record[4]), Record[5], 1032 getDITypeRefOrNull(Record[6]), Record[7], Record[8], 1033 getMDOrNull(Record[10]), AlignInBits)); 1034 1035 auto *DGVE = 1036 DIGlobalVariableExpression::getDistinct(Context, DGV, Expr); 1037 MetadataList.assignValue(DGVE, NextMetadataNo++); 1038 if (Attach) 1039 Attach->addDebugInfo(DGVE); 1040 } else 1041 return error("Invalid record"); 1042 1043 break; 1044 } 1045 case bitc::METADATA_LOCAL_VAR: { 1046 // 10th field is for the obseleted 'inlinedAt:' field. 1047 if (Record.size() < 8 || Record.size() > 10) 1048 return error("Invalid record"); 1049 1050 IsDistinct = Record[0] & 1; 1051 bool HasAlignment = Record[0] & 2; 1052 // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or 1053 // DW_TAG_arg_variable, if we have alignment flag encoded it means, that 1054 // this is newer version of record which doesn't have artifical tag. 1055 bool HasTag = !HasAlignment && Record.size() > 8; 1056 DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]); 1057 uint32_t AlignInBits = 0; 1058 if (HasAlignment) { 1059 if (Record[8 + HasTag] > (uint64_t)std::numeric_limits<uint32_t>::max()) 1060 return error("Alignment value is too large"); 1061 AlignInBits = Record[8 + HasTag]; 1062 } 1063 MetadataList.assignValue( 1064 GET_OR_DISTINCT(DILocalVariable, 1065 (Context, getMDOrNull(Record[1 + HasTag]), 1066 getMDString(Record[2 + HasTag]), 1067 getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag], 1068 getDITypeRefOrNull(Record[5 + HasTag]), 1069 Record[6 + HasTag], Flags, AlignInBits)), 1070 NextMetadataNo++); 1071 break; 1072 } 1073 case bitc::METADATA_EXPRESSION: { 1074 if (Record.size() < 1) 1075 return error("Invalid record"); 1076 1077 IsDistinct = Record[0] & 1; 1078 bool HasOpFragment = Record[0] & 2; 1079 auto Elts = MutableArrayRef<uint64_t>(Record).slice(1); 1080 if (!HasOpFragment) 1081 if (unsigned N = Elts.size()) 1082 if (N >= 3 && Elts[N - 3] == dwarf::DW_OP_bit_piece) 1083 Elts[N - 3] = dwarf::DW_OP_LLVM_fragment; 1084 1085 MetadataList.assignValue( 1086 GET_OR_DISTINCT(DIExpression, 1087 (Context, makeArrayRef(Record).slice(1))), 1088 NextMetadataNo++); 1089 break; 1090 } 1091 case bitc::METADATA_GLOBAL_VAR_EXPR: { 1092 if (Record.size() != 3) 1093 return error("Invalid record"); 1094 1095 IsDistinct = Record[0]; 1096 MetadataList.assignValue(GET_OR_DISTINCT(DIGlobalVariableExpression, 1097 (Context, getMDOrNull(Record[1]), 1098 getMDOrNull(Record[2]))), 1099 NextMetadataNo++); 1100 break; 1101 } 1102 case bitc::METADATA_OBJC_PROPERTY: { 1103 if (Record.size() != 8) 1104 return error("Invalid record"); 1105 1106 IsDistinct = Record[0]; 1107 MetadataList.assignValue( 1108 GET_OR_DISTINCT(DIObjCProperty, 1109 (Context, getMDString(Record[1]), 1110 getMDOrNull(Record[2]), Record[3], 1111 getMDString(Record[4]), getMDString(Record[5]), 1112 Record[6], getDITypeRefOrNull(Record[7]))), 1113 NextMetadataNo++); 1114 break; 1115 } 1116 case bitc::METADATA_IMPORTED_ENTITY: { 1117 if (Record.size() != 6) 1118 return error("Invalid record"); 1119 1120 IsDistinct = Record[0]; 1121 MetadataList.assignValue( 1122 GET_OR_DISTINCT(DIImportedEntity, 1123 (Context, Record[1], getMDOrNull(Record[2]), 1124 getDITypeRefOrNull(Record[3]), Record[4], 1125 getMDString(Record[5]))), 1126 NextMetadataNo++); 1127 break; 1128 } 1129 case bitc::METADATA_STRING_OLD: { 1130 std::string String(Record.begin(), Record.end()); 1131 1132 // Test for upgrading !llvm.loop. 1133 HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String); 1134 1135 Metadata *MD = MDString::get(Context, String); 1136 MetadataList.assignValue(MD, NextMetadataNo++); 1137 break; 1138 } 1139 case bitc::METADATA_STRINGS: 1140 if (Error Err = parseMetadataStrings(Record, Blob, NextMetadataNo)) 1141 return Err; 1142 break; 1143 case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: { 1144 if (Record.size() % 2 == 0) 1145 return error("Invalid record"); 1146 unsigned ValueID = Record[0]; 1147 if (ValueID >= ValueList.size()) 1148 return error("Invalid record"); 1149 if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID])) 1150 if (Error Err = parseGlobalObjectAttachment( 1151 *GO, ArrayRef<uint64_t>(Record).slice(1))) 1152 return Err; 1153 break; 1154 } 1155 case bitc::METADATA_KIND: { 1156 // Support older bitcode files that had METADATA_KIND records in a 1157 // block with METADATA_BLOCK_ID. 1158 if (Error Err = parseMetadataKindRecord(Record)) 1159 return Err; 1160 break; 1161 } 1162 } 1163 } 1164 #undef GET_OR_DISTINCT 1165 } 1166 1167 Error MetadataLoader::MetadataLoaderImpl::parseMetadataStrings( 1168 ArrayRef<uint64_t> Record, StringRef Blob, unsigned &NextMetadataNo) { 1169 // All the MDStrings in the block are emitted together in a single 1170 // record. The strings are concatenated and stored in a blob along with 1171 // their sizes. 1172 if (Record.size() != 2) 1173 return error("Invalid record: metadata strings layout"); 1174 1175 unsigned NumStrings = Record[0]; 1176 unsigned StringsOffset = Record[1]; 1177 if (!NumStrings) 1178 return error("Invalid record: metadata strings with no strings"); 1179 if (StringsOffset > Blob.size()) 1180 return error("Invalid record: metadata strings corrupt offset"); 1181 1182 StringRef Lengths = Blob.slice(0, StringsOffset); 1183 SimpleBitstreamCursor R(Lengths); 1184 1185 StringRef Strings = Blob.drop_front(StringsOffset); 1186 do { 1187 if (R.AtEndOfStream()) 1188 return error("Invalid record: metadata strings bad length"); 1189 1190 unsigned Size = R.ReadVBR(6); 1191 if (Strings.size() < Size) 1192 return error("Invalid record: metadata strings truncated chars"); 1193 1194 MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)), 1195 NextMetadataNo++); 1196 Strings = Strings.drop_front(Size); 1197 } while (--NumStrings); 1198 1199 return Error::success(); 1200 } 1201 1202 Error MetadataLoader::MetadataLoaderImpl::parseGlobalObjectAttachment( 1203 GlobalObject &GO, ArrayRef<uint64_t> Record) { 1204 assert(Record.size() % 2 == 0); 1205 for (unsigned I = 0, E = Record.size(); I != E; I += 2) { 1206 auto K = MDKindMap.find(Record[I]); 1207 if (K == MDKindMap.end()) 1208 return error("Invalid ID"); 1209 MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]); 1210 if (!MD) 1211 return error("Invalid metadata attachment"); 1212 GO.addMetadata(K->second, *MD); 1213 } 1214 return Error::success(); 1215 } 1216 1217 /// Parse metadata attachments. 1218 Error MetadataLoader::MetadataLoaderImpl::parseMetadataAttachment( 1219 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 1220 if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID)) 1221 return error("Invalid record"); 1222 1223 SmallVector<uint64_t, 64> Record; 1224 1225 while (true) { 1226 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1227 1228 switch (Entry.Kind) { 1229 case BitstreamEntry::SubBlock: // Handled for us already. 1230 case BitstreamEntry::Error: 1231 return error("Malformed block"); 1232 case BitstreamEntry::EndBlock: 1233 return Error::success(); 1234 case BitstreamEntry::Record: 1235 // The interesting case. 1236 break; 1237 } 1238 1239 // Read a metadata attachment record. 1240 Record.clear(); 1241 switch (Stream.readRecord(Entry.ID, Record)) { 1242 default: // Default behavior: ignore. 1243 break; 1244 case bitc::METADATA_ATTACHMENT: { 1245 unsigned RecordLength = Record.size(); 1246 if (Record.empty()) 1247 return error("Invalid record"); 1248 if (RecordLength % 2 == 0) { 1249 // A function attachment. 1250 if (Error Err = parseGlobalObjectAttachment(F, Record)) 1251 return Err; 1252 continue; 1253 } 1254 1255 // An instruction attachment. 1256 Instruction *Inst = InstructionList[Record[0]]; 1257 for (unsigned i = 1; i != RecordLength; i = i + 2) { 1258 unsigned Kind = Record[i]; 1259 DenseMap<unsigned, unsigned>::iterator I = MDKindMap.find(Kind); 1260 if (I == MDKindMap.end()) 1261 return error("Invalid ID"); 1262 if (I->second == LLVMContext::MD_tbaa && StripTBAA) 1263 continue; 1264 1265 Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]); 1266 if (isa<LocalAsMetadata>(Node)) 1267 // Drop the attachment. This used to be legal, but there's no 1268 // upgrade path. 1269 break; 1270 MDNode *MD = dyn_cast_or_null<MDNode>(Node); 1271 if (!MD) 1272 return error("Invalid metadata attachment"); 1273 1274 if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop) 1275 MD = upgradeInstructionLoopAttachment(*MD); 1276 1277 if (I->second == LLVMContext::MD_tbaa) { 1278 assert(!MD->isTemporary() && "should load MDs before attachments"); 1279 MD = UpgradeTBAANode(*MD); 1280 } 1281 Inst->setMetadata(I->second, MD); 1282 } 1283 break; 1284 } 1285 } 1286 } 1287 } 1288 1289 /// Parse a single METADATA_KIND record, inserting result in MDKindMap. 1290 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKindRecord( 1291 SmallVectorImpl<uint64_t> &Record) { 1292 if (Record.size() < 2) 1293 return error("Invalid record"); 1294 1295 unsigned Kind = Record[0]; 1296 SmallString<8> Name(Record.begin() + 1, Record.end()); 1297 1298 unsigned NewKind = TheModule.getMDKindID(Name.str()); 1299 if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second) 1300 return error("Conflicting METADATA_KIND records"); 1301 return Error::success(); 1302 } 1303 1304 /// Parse the metadata kinds out of the METADATA_KIND_BLOCK. 1305 Error MetadataLoader::MetadataLoaderImpl::parseMetadataKinds() { 1306 if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID)) 1307 return error("Invalid record"); 1308 1309 SmallVector<uint64_t, 64> Record; 1310 1311 // Read all the records. 1312 while (true) { 1313 BitstreamEntry Entry = Stream.advanceSkippingSubblocks(); 1314 1315 switch (Entry.Kind) { 1316 case BitstreamEntry::SubBlock: // Handled for us already. 1317 case BitstreamEntry::Error: 1318 return error("Malformed block"); 1319 case BitstreamEntry::EndBlock: 1320 return Error::success(); 1321 case BitstreamEntry::Record: 1322 // The interesting case. 1323 break; 1324 } 1325 1326 // Read a record. 1327 Record.clear(); 1328 unsigned Code = Stream.readRecord(Entry.ID, Record); 1329 switch (Code) { 1330 default: // Default behavior: ignore. 1331 break; 1332 case bitc::METADATA_KIND: { 1333 if (Error Err = parseMetadataKindRecord(Record)) 1334 return Err; 1335 break; 1336 } 1337 } 1338 } 1339 } 1340 1341 MetadataLoader &MetadataLoader::operator=(MetadataLoader &&RHS) { 1342 Pimpl = std::move(RHS.Pimpl); 1343 return *this; 1344 } 1345 MetadataLoader::MetadataLoader(MetadataLoader &&RHS) 1346 : Pimpl(std::move(RHS.Pimpl)) {} 1347 1348 MetadataLoader::~MetadataLoader() = default; 1349 MetadataLoader::MetadataLoader(BitstreamCursor &Stream, Module &TheModule, 1350 BitcodeReaderValueList &ValueList, 1351 bool IsImporting, 1352 std::function<Type *(unsigned)> getTypeByID) 1353 : Pimpl(llvm::make_unique<MetadataLoaderImpl>(Stream, TheModule, ValueList, 1354 getTypeByID, IsImporting)) {} 1355 1356 Error MetadataLoader::parseMetadata(bool ModuleLevel) { 1357 return Pimpl->parseMetadata(ModuleLevel); 1358 } 1359 1360 bool MetadataLoader::hasFwdRefs() const { return Pimpl->hasFwdRefs(); } 1361 1362 /// Return the given metadata, creating a replaceable forward reference if 1363 /// necessary. 1364 Metadata *MetadataLoader::getMetadataFwdRef(unsigned Idx) { 1365 return Pimpl->getMetadataFwdRef(Idx); 1366 } 1367 1368 MDNode *MetadataLoader::getMDNodeFwdRefOrNull(unsigned Idx) { 1369 return Pimpl->getMDNodeFwdRefOrNull(Idx); 1370 } 1371 1372 DISubprogram *MetadataLoader::lookupSubprogramForFunction(Function *F) { 1373 return Pimpl->lookupSubprogramForFunction(F); 1374 } 1375 1376 Error MetadataLoader::parseMetadataAttachment( 1377 Function &F, const SmallVectorImpl<Instruction *> &InstructionList) { 1378 return Pimpl->parseMetadataAttachment(F, InstructionList); 1379 } 1380 1381 Error MetadataLoader::parseMetadataKinds() { 1382 return Pimpl->parseMetadataKinds(); 1383 } 1384 1385 void MetadataLoader::setStripTBAA(bool StripTBAA) { 1386 return Pimpl->setStripTBAA(StripTBAA); 1387 } 1388 1389 bool MetadataLoader::isStrippingTBAA() { return Pimpl->isStrippingTBAA(); } 1390 1391 unsigned MetadataLoader::size() const { return Pimpl->size(); } 1392 void MetadataLoader::shrinkTo(unsigned N) { return Pimpl->shrinkTo(N); } 1393