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