LLVM 23.0.0git
DWARFLinker.cpp
Go to the documentation of this file.
1//=== DWARFLinker.cpp -----------------------------------------------------===//
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
10#include "llvm/ADT/ArrayRef.h"
11#include "llvm/ADT/BitVector.h"
12#include "llvm/ADT/STLExtras.h"
30#include "llvm/MC/MCDwarf.h"
32#include "llvm/Support/Error.h"
36#include "llvm/Support/LEB128.h"
37#include "llvm/Support/Path.h"
39#include <vector>
40
41namespace llvm {
42
43using namespace dwarf_linker;
44using namespace dwarf_linker::classic;
45
46/// Hold the input and output of the debug info size in bytes.
51
52/// Compute the total size of the debug info.
54 uint64_t Size = 0;
55 for (auto &Unit : Dwarf.compile_units()) {
56 Size += Unit->getLength();
57 }
58 return Size;
59}
60
61/// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
62/// CompileUnit object instead.
64 auto CU = llvm::upper_bound(
65 Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
66 return LHS < RHS->getOrigUnit().getNextUnitOffset();
67 });
68 return CU != Units.end() ? CU->get() : nullptr;
69}
70
71/// Resolve the DIE attribute reference that has been extracted in \p RefValue.
72/// The resulting DIE might be in another CompileUnit which is stored into \p
73/// ReferencedCU. \returns null if resolving fails for any reason.
74DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
75 const UnitListTy &Units,
76 const DWARFFormValue &RefValue,
77 const DWARFDie &DIE,
78 CompileUnit *&RefCU) {
79 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
80 uint64_t RefOffset;
81 if (std::optional<uint64_t> Off = RefValue.getAsRelativeReference()) {
82 RefOffset = RefValue.getUnit()->getOffset() + *Off;
83 } else if (Off = RefValue.getAsDebugInfoReference(); Off) {
84 RefOffset = *Off;
85 } else {
86 reportWarning("Unsupported reference type", File, &DIE);
87 return DWARFDie();
88 }
89 if ((RefCU = getUnitForOffset(Units, RefOffset)))
90 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
91 // In a file with broken references, an attribute might point to a NULL
92 // DIE.
93 if (!RefDie.isNULL())
94 return RefDie;
95 }
96
97 reportWarning("could not find referenced DIE", File, &DIE);
98 return DWARFDie();
99}
100
101/// \returns whether the passed \a Attr type might contain a DIE reference
102/// suitable for ODR uniquing.
103static bool isODRAttribute(uint16_t Attr) {
104 switch (Attr) {
105 default:
106 return false;
107 case dwarf::DW_AT_type:
108 case dwarf::DW_AT_containing_type:
109 case dwarf::DW_AT_specification:
110 case dwarf::DW_AT_abstract_origin:
111 case dwarf::DW_AT_import:
112 case dwarf::DW_AT_LLVM_alloc_type:
113 return true;
114 }
115 llvm_unreachable("Improper attribute.");
116}
117
118static bool isTypeTag(uint16_t Tag) {
119 switch (Tag) {
120 case dwarf::DW_TAG_array_type:
121 case dwarf::DW_TAG_class_type:
122 case dwarf::DW_TAG_enumeration_type:
123 case dwarf::DW_TAG_pointer_type:
124 case dwarf::DW_TAG_reference_type:
125 case dwarf::DW_TAG_string_type:
126 case dwarf::DW_TAG_structure_type:
127 case dwarf::DW_TAG_subroutine_type:
128 case dwarf::DW_TAG_template_alias:
129 case dwarf::DW_TAG_typedef:
130 case dwarf::DW_TAG_union_type:
131 case dwarf::DW_TAG_ptr_to_member_type:
132 case dwarf::DW_TAG_set_type:
133 case dwarf::DW_TAG_subrange_type:
134 case dwarf::DW_TAG_base_type:
135 case dwarf::DW_TAG_const_type:
136 case dwarf::DW_TAG_constant:
137 case dwarf::DW_TAG_file_type:
138 case dwarf::DW_TAG_namelist:
139 case dwarf::DW_TAG_packed_type:
140 case dwarf::DW_TAG_volatile_type:
141 case dwarf::DW_TAG_restrict_type:
142 case dwarf::DW_TAG_atomic_type:
143 case dwarf::DW_TAG_interface_type:
144 case dwarf::DW_TAG_unspecified_type:
145 case dwarf::DW_TAG_shared_type:
146 case dwarf::DW_TAG_immutable_type:
147 return true;
148 default:
149 break;
150 }
151 return false;
152}
153
154/// Recurse through the input DIE's canonical references until we find a
155/// DW_AT_name.
157DWARFLinker::DIECloner::getCanonicalDIEName(DWARFDie Die, const DWARFFile &File,
158 CompileUnit *Unit) {
159 if (!Die)
160 return {};
161
162 std::optional<DWARFFormValue> Ref;
163
164 auto GetDieName = [](const DWARFDie &D) -> llvm::StringRef {
165 auto NameForm = D.find(llvm::dwarf::DW_AT_name);
166 if (!NameForm)
167 return {};
168
169 auto NameOrErr = NameForm->getAsCString();
170 if (!NameOrErr) {
171 llvm::consumeError(NameOrErr.takeError());
172 return {};
173 }
174
175 return *NameOrErr;
176 };
177
178 llvm::StringRef Name = GetDieName(Die);
179 if (!Name.empty())
180 return Name;
181
182 while (true) {
183 if (!(Ref = Die.find(llvm::dwarf::DW_AT_specification)) &&
184 !(Ref = Die.find(llvm::dwarf::DW_AT_abstract_origin)))
185 break;
186
187 Die = Linker.resolveDIEReference(File, CompileUnits, *Ref, Die, Unit);
188 if (!Die)
189 break;
190
191 assert(Unit);
192
193 unsigned SpecIdx = Unit->getOrigUnit().getDIEIndex(Die);
194 CompileUnit::DIEInfo &SpecInfo = Unit->getInfo(SpecIdx);
195 if (SpecInfo.Ctxt && SpecInfo.Ctxt->hasCanonicalDIE()) {
196 if (!SpecInfo.Ctxt->getCanonicalName().empty()) {
197 Name = SpecInfo.Ctxt->getCanonicalName();
198 break;
199 }
200 }
201
202 Name = GetDieName(Die);
203 if (!Name.empty())
204 break;
205 }
206
207 return Name;
208}
209
210bool DWARFLinker::DIECloner::getDIENames(
211 const DWARFDie &Die, AttributesInfo &Info, OffsetsStringPool &StringPool,
212 const DWARFFile &File, CompileUnit &Unit, bool StripTemplate) {
213 // This function will be called on DIEs having low_pcs and
214 // ranges. As getting the name might be more expansive, filter out
215 // blocks directly.
216 if (Die.getTag() == dwarf::DW_TAG_lexical_block)
217 return false;
218
219 // The mangled name of an specification DIE will by virtue of the
220 // uniquing algorithm be the same as the one it got uniqued into.
221 // So just use the input DIE's linkage name.
222 if (!Info.MangledName)
223 if (const char *MangledName = Die.getLinkageName())
224 Info.MangledName = StringPool.getEntry(MangledName);
225
226 // For subprograms with linkage names, we unique on the linkage name,
227 // so DW_AT_name's may differ between the input and canonical DIEs.
228 // Use the name of the canonical DIE.
229 if (!Info.Name)
230 if (llvm::StringRef Name = getCanonicalDIEName(Die, File, &Unit);
231 !Name.empty())
232 Info.Name = StringPool.getEntry(Name);
233
234 if (!Info.MangledName)
235 Info.MangledName = Info.Name;
236
237 if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
238 StringRef Name = Info.Name.getString();
239 if (std::optional<StringRef> StrippedName = StripTemplateParameters(Name))
240 Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
241 }
242
243 return Info.Name || Info.MangledName;
244}
245
246/// Resolve the relative path to a build artifact referenced by DWARF by
247/// applying DW_AT_comp_dir.
249 sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
250}
251
252/// Collect references to parseable Swift interfaces in imported
253/// DW_TAG_module blocks.
255 const DWARFDie &DIE, CompileUnit &CU,
256 DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces,
257 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
258 if (CU.getLanguage() != dwarf::DW_LANG_Swift)
259 return;
260
261 if (!ParseableSwiftInterfaces)
262 return;
263
264 StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
265 if (!Path.ends_with(".swiftinterface"))
266 return;
267 // Don't track interfaces that are part of the SDK.
268 StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
269 if (SysRoot.empty())
270 SysRoot = CU.getSysRoot();
271 if (!SysRoot.empty() && Path.starts_with(SysRoot))
272 return;
273 // Don't track interfaces that are part of the toolchain.
274 // For example: Swift, _Concurrency, ...
275 StringRef DeveloperDir = guessDeveloperDir(SysRoot);
276 if (!DeveloperDir.empty() && Path.starts_with(DeveloperDir))
277 return;
278 if (isInToolchainDir(Path))
279 return;
280 std::optional<const char *> Name =
281 dwarf::toString(DIE.find(dwarf::DW_AT_name));
282 if (!Name)
283 return;
284 auto &Entry = (*ParseableSwiftInterfaces)[*Name];
285 // The prepend path is applied later when copying.
286 DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
287 SmallString<128> ResolvedPath;
288 if (sys::path::is_relative(Path))
289 resolveRelativeObjectPath(ResolvedPath, CUDie);
290 sys::path::append(ResolvedPath, Path);
291 if (!Entry.empty() && Entry != ResolvedPath)
292 ReportWarning(Twine("Conflicting parseable interfaces for Swift Module ") +
293 *Name + ": " + Entry + " and " + Path,
294 DIE);
295 Entry = std::string(ResolvedPath);
296}
297
298/// The distinct types of work performed by the work loop in
299/// analyzeContextInfo.
305
306/// This class represents an item in the work list. The type defines what kind
307/// of work needs to be performed when processing the current item. Everything
308/// but the Type and Die fields are optional based on the type.
330
331static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
332 uint64_t ModulesEndOffset) {
333 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
334
335 // Prune this DIE if it is either a forward declaration inside a
336 // DW_TAG_module or a DW_TAG_module that contains nothing but
337 // forward declarations.
338 Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
339 (isTypeTag(Die.getTag()) &&
340 dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
341
342 // Only prune forward declarations inside a DW_TAG_module for which a
343 // definition exists elsewhere.
344 if (ModulesEndOffset == 0)
345 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
346 else
347 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
348 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
349
350 return Info.Prune;
351}
352
353static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
354 CompileUnit::DIEInfo &ChildInfo) {
355 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
356 Info.Prune &= ChildInfo.Prune;
357}
358
359/// Recursive helper to build the global DeclContext information and
360/// gather the child->parent relationships in the original compile unit.
361///
362/// This function uses the same work list approach as lookForDIEsToKeep.
363///
364/// \return true when this DIE and all of its children are only
365/// forward declarations to types defined in external clang modules
366/// (i.e., forward declarations that are children of a DW_TAG_module).
368 const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
369 DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
370 uint64_t ModulesEndOffset,
371 DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces,
372 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
373 // LIFO work list.
374 std::vector<ContextWorklistItem> Worklist;
375 Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, false);
376
377 while (!Worklist.empty()) {
378 ContextWorklistItem Current = Worklist.back();
379 Worklist.pop_back();
380
381 switch (Current.Type) {
383 updatePruning(Current.Die, CU, ModulesEndOffset);
384 continue;
386 updateChildPruning(Current.Die, CU, *Current.OtherInfo);
387 continue;
389 break;
390 }
391
392 unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
393 CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
394
395 // Clang imposes an ODR on modules(!) regardless of the language:
396 // "The module-id should consist of only a single identifier,
397 // which provides the name of the module being defined. Each
398 // module shall have a single definition."
399 //
400 // This does not extend to the types inside the modules:
401 // "[I]n C, this implies that if two structs are defined in
402 // different submodules with the same name, those two types are
403 // distinct types (but may be compatible types if their
404 // definitions match)."
405 //
406 // We treat non-C++ modules like namespaces for this reason.
407 if (Current.Die.getTag() == dwarf::DW_TAG_module &&
408 Current.ParentIdx == 0 &&
409 dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
410 CU.getClangModuleName()) {
411 Current.InImportedModule = true;
412 analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
413 ReportWarning);
414 }
415
416 Info.ParentIdx = Current.ParentIdx;
417 Info.InModuleScope = CU.isClangModule() || Current.InImportedModule;
418 if (CU.hasODR() || Info.InModuleScope) {
419 if (Current.Context) {
420 auto PtrInvalidPair = Contexts.getChildDeclContext(
421 *Current.Context, Current.Die, CU, Info.InModuleScope);
422 Current.Context = PtrInvalidPair.getPointer();
423 Info.Ctxt =
424 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
425 if (Info.Ctxt)
426 Info.Ctxt->setDefinedInClangModule(Info.InModuleScope);
427 } else
428 Info.Ctxt = Current.Context = nullptr;
429 }
430
431 Info.Prune = Current.InImportedModule;
432 // Add children in reverse order to the worklist to effectively process
433 // them in order.
434 Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
435 for (auto Child : reverse(Current.Die.children())) {
436 CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
437 Worklist.emplace_back(
439 Worklist.emplace_back(Child, Current.Context, Idx,
440 Current.InImportedModule);
441 }
442 }
443}
444
446 switch (Tag) {
447 default:
448 return false;
449 case dwarf::DW_TAG_class_type:
450 case dwarf::DW_TAG_common_block:
451 case dwarf::DW_TAG_lexical_block:
452 case dwarf::DW_TAG_structure_type:
453 case dwarf::DW_TAG_subprogram:
454 case dwarf::DW_TAG_subroutine_type:
455 case dwarf::DW_TAG_union_type:
456 return true;
457 }
458 llvm_unreachable("Invalid Tag");
459}
460
461void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
462 Context.clear();
463
464 for (DIEBlock *I : DIEBlocks)
465 I->~DIEBlock();
466 for (DIELoc *I : DIELocs)
467 I->~DIELoc();
468
469 DIEBlocks.clear();
470 DIELocs.clear();
471 DIEAlloc.Reset();
472}
473
475 CompileUnit &Unit, const DWARFDebugLine::LineTable &LT,
476 DenseMap<uint64_t, unsigned> &SeqOffToOrigRow) {
477
478 // Use std::map for ordered iteration.
479 std::map<uint64_t, unsigned> LineTableMapping;
480
481 // First, trust the sequences that the DWARF parser did identify.
482 for (const DWARFDebugLine::Sequence &Seq : LT.Sequences)
483 LineTableMapping[Seq.StmtSeqOffset] = Seq.FirstRowIndex;
484
485 // Second, manually find sequence boundaries and match them to the
486 // sorted attributes to handle sequences the parser might have missed.
487 auto StmtAttrs = Unit.getStmtSeqListAttributes();
488 llvm::sort(StmtAttrs, [](const PatchLocation &A, const PatchLocation &B) {
489 return A.get() < B.get();
490 });
491
492 std::vector<unsigned> SeqStartRows;
493 SeqStartRows.push_back(0);
494 for (auto [I, Row] : llvm::enumerate(ArrayRef(LT.Rows).drop_back()))
495 if (Row.EndSequence)
496 SeqStartRows.push_back(I + 1);
497
498 // While SeqOffToOrigRow parsed from CU could be the ground truth,
499 // e.g.
500 //
501 // SeqOff Row
502 // 0x08 9
503 // 0x14 15
504 //
505 // The StmtAttrs and SeqStartRows may not match perfectly, e.g.
506 //
507 // StmtAttrs SeqStartRows
508 // 0x04 3
509 // 0x08 5
510 // 0x10 9
511 // 0x12 11
512 // 0x14 15
513 //
514 // In this case, we don't want to assign 5 to 0x08, since we know 0x08
515 // maps to 9. If we do a dummy 1:1 mapping 0x10 will be mapped to 9
516 // which is incorrect. The expected behavior is ignore 5, realign the
517 // table based on the result from the line table:
518 //
519 // StmtAttrs SeqStartRows
520 // 0x04 3
521 // -- 5
522 // 0x08 9 <- LineTableMapping ground truth
523 // 0x10 11
524 // 0x12 --
525 // 0x14 15 <- LineTableMapping ground truth
526
527 ArrayRef StmtAttrsRef(StmtAttrs);
528 ArrayRef SeqStartRowsRef(SeqStartRows);
529
530 // Dummy last element to make sure StmtAttrsRef and SeqStartRowsRef always
531 // run out first.
532 constexpr uint64_t DummyKey = UINT64_MAX;
533 constexpr unsigned DummyVal = UINT32_MAX;
534 LineTableMapping[DummyKey] = DummyVal;
535
536 for (auto [NextSeqOff, NextRow] : LineTableMapping) {
537 // Explict capture to avoid capturing structured bindings and make C++17
538 // happy.
539 auto StmtAttrSmallerThanNext = [N = NextSeqOff](const PatchLocation &SA) {
540 return SA.get() < N;
541 };
542 auto SeqStartSmallerThanNext = [N = NextRow](const unsigned &Row) {
543 return Row < N;
544 };
545 // If both StmtAttrs and SeqStartRows points to value not in
546 // the LineTableMapping yet, we do a dummy one to one mapping and
547 // move the pointer.
548 while (!StmtAttrsRef.empty() && !SeqStartRowsRef.empty() &&
549 StmtAttrSmallerThanNext(StmtAttrsRef.front()) &&
550 SeqStartSmallerThanNext(SeqStartRowsRef.front())) {
551 SeqOffToOrigRow[StmtAttrsRef.consume_front().get()] =
552 SeqStartRowsRef.consume_front();
553 }
554 // One of the pointer points to the value at or past Next in the
555 // LineTableMapping, We move the pointer to re-align with the
556 // LineTableMapping
557 StmtAttrsRef = StmtAttrsRef.drop_while(StmtAttrSmallerThanNext);
558 SeqStartRowsRef = SeqStartRowsRef.drop_while(SeqStartSmallerThanNext);
559 // Use the LineTableMapping's result as the ground truth and move
560 // on.
561 if (NextSeqOff != DummyKey) {
562 SeqOffToOrigRow[NextSeqOff] = NextRow;
563 }
564 // Move the pointers if they are pointed at Next.
565 // It is possible that they point to later entries in LineTableMapping.
566 // Therefore we only increment the pointers after we validate they are
567 // pointing to the `Next` entry. e.g.
568 //
569 // LineTableMapping
570 // SeqOff Row
571 // 0x08 9 <- NextSeqOff/NextRow
572 // 0x14 15
573 //
574 // StmtAttrs SeqStartRows
575 // 0x14 13 <- StmtAttrsRef.front() / SeqStartRowsRef.front()
576 // 0x16 15
577 // -- 17
578 if (!StmtAttrsRef.empty() && StmtAttrsRef.front().get() == NextSeqOff)
579 StmtAttrsRef.consume_front();
580 if (!SeqStartRowsRef.empty() && SeqStartRowsRef.front() == NextRow)
581 SeqStartRowsRef.consume_front();
582 }
583}
584
585std::pair<bool, std::optional<int64_t>>
586DWARFLinker::getVariableRelocAdjustment(AddressesMap &RelocMgr,
587 const DWARFDie &DIE) {
588 assert((DIE.getTag() == dwarf::DW_TAG_variable ||
589 DIE.getTag() == dwarf::DW_TAG_constant) &&
590 "Wrong type of input die");
591
592 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
593
594 // Check if DIE has DW_AT_location attribute.
595 DWARFUnit *U = DIE.getDwarfUnit();
596 std::optional<uint32_t> LocationIdx =
597 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
598 if (!LocationIdx)
599 return std::make_pair(false, std::nullopt);
600
601 // Get offset to the DW_AT_location attribute.
602 uint64_t AttrOffset =
603 Abbrev->getAttributeOffsetFromIndex(*LocationIdx, DIE.getOffset(), *U);
604
605 // Get value of the DW_AT_location attribute.
606 std::optional<DWARFFormValue> LocationValue =
607 Abbrev->getAttributeValueFromOffset(*LocationIdx, AttrOffset, *U);
608 if (!LocationValue)
609 return std::make_pair(false, std::nullopt);
610
611 // Check that DW_AT_location attribute is of 'exprloc' class.
612 // Handling value of location expressions for attributes of 'loclist'
613 // class is not implemented yet.
614 std::optional<ArrayRef<uint8_t>> Expr = LocationValue->getAsBlock();
615 if (!Expr)
616 return std::make_pair(false, std::nullopt);
617
618 // Parse 'exprloc' expression.
619 DataExtractor Data(toStringRef(*Expr), U->getContext().isLittleEndian(),
620 U->getAddressByteSize());
621 DWARFExpression Expression(Data, U->getAddressByteSize(),
622 U->getFormParams().Format);
623
624 bool HasLocationAddress = false;
625 uint64_t CurExprOffset = 0;
626 for (DWARFExpression::iterator It = Expression.begin();
627 It != Expression.end(); ++It) {
628 DWARFExpression::iterator NextIt = It;
629 ++NextIt;
630
631 const DWARFExpression::Operation &Op = *It;
632 switch (Op.getCode()) {
633 case dwarf::DW_OP_const2u:
634 case dwarf::DW_OP_const4u:
635 case dwarf::DW_OP_const8u:
636 case dwarf::DW_OP_const2s:
637 case dwarf::DW_OP_const4s:
638 case dwarf::DW_OP_const8s:
639 if (NextIt == Expression.end() ||
640 !dwarf::isTlsAddressOp(NextIt->getCode()))
641 break;
642 [[fallthrough]];
643 case dwarf::DW_OP_addr: {
644 HasLocationAddress = true;
645 // Check relocation for the address.
646 if (std::optional<int64_t> RelocAdjustment =
647 RelocMgr.getExprOpAddressRelocAdjustment(
648 *U, Op, AttrOffset + CurExprOffset,
649 AttrOffset + Op.getEndOffset(), Options.Verbose))
650 return std::make_pair(HasLocationAddress, *RelocAdjustment);
651 } break;
652 case dwarf::DW_OP_constx:
653 case dwarf::DW_OP_addrx: {
654 HasLocationAddress = true;
655 if (std::optional<uint64_t> AddressOffset =
656 DIE.getDwarfUnit()->getIndexedAddressOffset(
657 Op.getRawOperand(0))) {
658 // Check relocation for the address.
659 if (std::optional<int64_t> RelocAdjustment =
660 RelocMgr.getExprOpAddressRelocAdjustment(
661 *U, Op, *AddressOffset,
662 *AddressOffset + DIE.getDwarfUnit()->getAddressByteSize(),
663 Options.Verbose))
664 return std::make_pair(HasLocationAddress, *RelocAdjustment);
665 }
666 } break;
667 default: {
668 // Nothing to do.
669 } break;
670 }
671 CurExprOffset = Op.getEndOffset();
672 }
673
674 return std::make_pair(HasLocationAddress, std::nullopt);
675}
676
677/// Check if a variable describing DIE should be kept.
678/// \returns updated TraversalFlags.
679unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
680 const DWARFDie &DIE,
681 CompileUnit::DIEInfo &MyInfo,
682 unsigned Flags) {
683 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
684
685 // Global variables with constant value can always be kept.
686 if (!(Flags & TF_InFunctionScope) &&
687 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
688 MyInfo.InDebugMap = true;
689 return Flags | TF_Keep;
690 }
691
692 // See if there is a relocation to a valid debug map entry inside this
693 // variable's location. The order is important here. We want to always check
694 // if the variable has a valid relocation, so that the DIEInfo is filled.
695 // However, we don't want a static variable in a function to force us to keep
696 // the enclosing function, unless requested explicitly.
697 std::pair<bool, std::optional<int64_t>> LocExprAddrAndRelocAdjustment =
698 getVariableRelocAdjustment(RelocMgr, DIE);
699
700 if (LocExprAddrAndRelocAdjustment.first)
701 MyInfo.HasLocationExpressionAddr = true;
702
703 if (!LocExprAddrAndRelocAdjustment.second)
704 return Flags;
705
706 MyInfo.AddrAdjust = *LocExprAddrAndRelocAdjustment.second;
707 MyInfo.InDebugMap = true;
708
709 if (((Flags & TF_InFunctionScope) &&
710 !LLVM_UNLIKELY(Options.KeepFunctionForStatic)))
711 return Flags;
712
713 if (Options.Verbose) {
714 outs() << "Keeping variable DIE:";
715 DIDumpOptions DumpOpts;
716 DumpOpts.ChildRecurseDepth = 0;
717 DumpOpts.Verbose = Options.Verbose;
718 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
719 }
720
721 return Flags | TF_Keep;
722}
723
724/// Check if a function describing DIE should be kept.
725/// \returns updated TraversalFlags.
726unsigned DWARFLinker::shouldKeepSubprogramDIE(
727 AddressesMap &RelocMgr, const DWARFDie &DIE, const DWARFFile &File,
728 CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
729 Flags |= TF_InFunctionScope;
730
731 auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
732 if (!LowPc)
733 return Flags;
734
735 assert(LowPc && "low_pc attribute is not an address.");
736 std::optional<int64_t> RelocAdjustment =
737 RelocMgr.getSubprogramRelocAdjustment(DIE, Options.Verbose);
738 if (!RelocAdjustment)
739 return Flags;
740
741 MyInfo.AddrAdjust = *RelocAdjustment;
742 MyInfo.InDebugMap = true;
743
744 if (Options.Verbose) {
745 outs() << "Keeping subprogram DIE:";
746 DIDumpOptions DumpOpts;
747 DumpOpts.ChildRecurseDepth = 0;
748 DumpOpts.Verbose = Options.Verbose;
749 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
750 }
751
752 if (DIE.getTag() == dwarf::DW_TAG_label) {
753 if (Unit.hasLabelAt(*LowPc))
754 return Flags;
755
756 DWARFUnit &OrigUnit = Unit.getOrigUnit();
757 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
758 // that don't fall into the CU's aranges. This is wrong IMO. Debug info
759 // generation bugs aside, this is really wrong in the case of labels, where
760 // a label marking the end of a function will have a PC == CU's high_pc.
761 if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
762 .value_or(UINT64_MAX) <= LowPc)
763 return Flags;
764 // For assembly language files, try to preserve DWARF info by using
765 // function ranges when available, falling back to labels otherwise.
766 if (Unit.getLanguage() == dwarf::DW_LANG_Mips_Assembler ||
767 Unit.getLanguage() == dwarf::DW_LANG_Assembly) {
768 if (auto Range = RelocMgr.getAssemblyRangeForAddress(*LowPc)) {
769 Unit.addFunctionRange(Range->LowPC, Range->HighPC, MyInfo.AddrAdjust);
770 } else {
771 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
772 }
773 } else {
774 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
775 }
776 return Flags | TF_Keep;
777 }
778
779 Flags |= TF_Keep;
780
781 std::optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
782 if (!HighPc) {
783 reportWarning("Function without high_pc. Range will be discarded.\n", File,
784 &DIE);
785 return Flags;
786 }
787 if (*LowPc > *HighPc) {
788 reportWarning("low_pc greater than high_pc. Range will be discarded.\n",
789 File, &DIE);
790 return Flags;
791 }
792
793 // Replace the debug map range with a more accurate one.
794 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
795 return Flags;
796}
797
798/// Check if a DIE should be kept.
799/// \returns updated TraversalFlags.
800unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, const DWARFDie &DIE,
801 const DWARFFile &File, CompileUnit &Unit,
802 CompileUnit::DIEInfo &MyInfo,
803 unsigned Flags) {
804 switch (DIE.getTag()) {
805 case dwarf::DW_TAG_constant:
806 case dwarf::DW_TAG_variable:
807 return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
808 case dwarf::DW_TAG_subprogram:
809 case dwarf::DW_TAG_label:
810 return shouldKeepSubprogramDIE(RelocMgr, DIE, File, Unit, MyInfo, Flags);
811 case dwarf::DW_TAG_base_type:
812 // DWARF Expressions may reference basic types, but scanning them
813 // is expensive. Basic types are tiny, so just keep all of them.
814 case dwarf::DW_TAG_imported_module:
815 case dwarf::DW_TAG_imported_declaration:
816 case dwarf::DW_TAG_imported_unit:
817 // We always want to keep these.
818 return Flags | TF_Keep;
819 default:
820 break;
821 }
822
823 return Flags;
824}
825
826/// Helper that updates the completeness of the current DIE based on the
827/// completeness of one of its children. It depends on the incompleteness of
828/// the children already being computed.
830 CompileUnit::DIEInfo &ChildInfo) {
831 switch (Die.getTag()) {
832 case dwarf::DW_TAG_structure_type:
833 case dwarf::DW_TAG_class_type:
834 case dwarf::DW_TAG_union_type:
835 break;
836 default:
837 return;
838 }
839
840 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
841
842 if (ChildInfo.Incomplete || ChildInfo.Prune)
843 MyInfo.Incomplete = true;
844}
845
846/// Helper that updates the completeness of the current DIE based on the
847/// completeness of the DIEs it references. It depends on the incompleteness of
848/// the referenced DIE already being computed.
850 CompileUnit::DIEInfo &RefInfo) {
851 switch (Die.getTag()) {
852 case dwarf::DW_TAG_typedef:
853 case dwarf::DW_TAG_member:
854 case dwarf::DW_TAG_reference_type:
855 case dwarf::DW_TAG_ptr_to_member_type:
856 case dwarf::DW_TAG_pointer_type:
857 break;
858 default:
859 return;
860 }
861
862 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
863
864 if (MyInfo.Incomplete)
865 return;
866
867 if (RefInfo.Incomplete)
868 MyInfo.Incomplete = true;
869}
870
871/// Look at the children of the given DIE and decide whether they should be
872/// kept.
873void DWARFLinker::lookForChildDIEsToKeep(
874 const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
875 SmallVectorImpl<WorklistItem> &Worklist) {
876 // The TF_ParentWalk flag tells us that we are currently walking up the
877 // parent chain of a required DIE, and we don't want to mark all the children
878 // of the parents as kept (consider for example a DW_TAG_namespace node in
879 // the parent chain). There are however a set of DIE types for which we want
880 // to ignore that directive and still walk their children.
881 if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
882 Flags &= ~DWARFLinker::TF_ParentWalk;
883
884 // We're finished if this DIE has no children or we're walking the parent
885 // chain.
886 if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
887 return;
888
889 // Add children in reverse order to the worklist to effectively process them
890 // in order.
891 for (auto Child : reverse(Die.children())) {
892 // Add a worklist item before every child to calculate incompleteness right
893 // after the current child is processed.
894 CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
895 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
896 &ChildInfo);
897 Worklist.emplace_back(Child, CU, Flags);
898 }
899}
900
902 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
903
904 if (!Info.Ctxt || (Die.getTag() == dwarf::DW_TAG_namespace))
905 return false;
906
907 if (!CU.hasODR() && !Info.InModuleScope)
908 return false;
909
910 return !Info.Incomplete && Info.Ctxt != CU.getInfo(Info.ParentIdx).Ctxt;
911}
912
913void DWARFLinker::markODRCanonicalDie(const DWARFDie &Die, CompileUnit &CU) {
914 CompileUnit::DIEInfo &Info = CU.getInfo(Die);
915
916 Info.ODRMarkingDone = true;
917 if (Info.Keep && isODRCanonicalCandidate(Die, CU) &&
918 !Info.Ctxt->hasCanonicalDIE())
919 Info.Ctxt->setHasCanonicalDIE();
920}
921
922/// Look at DIEs referenced by the given DIE and decide whether they should be
923/// kept. All DIEs referenced though attributes should be kept.
924void DWARFLinker::lookForRefDIEsToKeep(
925 const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
926 const UnitListTy &Units, const DWARFFile &File,
927 SmallVectorImpl<WorklistItem> &Worklist) {
928 bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
929 ? (Flags & DWARFLinker::TF_ODR)
930 : CU.hasODR();
931 DWARFUnit &Unit = CU.getOrigUnit();
932 DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
933 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
934 uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
935
937 for (const auto &AttrSpec : Abbrev->attributes()) {
938 DWARFFormValue Val(AttrSpec.Form);
939 if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
940 AttrSpec.Attr == dwarf::DW_AT_sibling) {
941 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
942 Unit.getFormParams());
943 continue;
944 }
945
946 Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
947 CompileUnit *ReferencedCU;
948 if (auto RefDie =
949 resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
950 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
951 // If the referenced DIE has a DeclContext that has already been
952 // emitted, then do not keep the one in this CU. We'll link to
953 // the canonical DIE in cloneDieReferenceAttribute.
954 //
955 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
956 // be necessary and could be advantageously replaced by
957 // ReferencedCU->hasODR() && CU.hasODR().
958 //
959 // FIXME: compatibility with dsymutil-classic. There is no
960 // reason not to unique ref_addr references.
961 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr &&
962 isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
963 Info.Ctxt->hasCanonicalDIE())
964 continue;
965
966 // Keep a module forward declaration if there is no definition.
967 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
968 Info.Ctxt->hasCanonicalDIE()))
969 Info.Prune = false;
970 ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
971 }
972 }
973
974 unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
975
976 // Add referenced DIEs in reverse order to the worklist to effectively
977 // process them in order.
978 for (auto &P : reverse(ReferencedDIEs)) {
979 // Add a worklist item before every child to calculate incompleteness right
980 // after the current child is processed.
981 CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
982 Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
983 &Info);
984 Worklist.emplace_back(P.first, P.second,
985 DWARFLinker::TF_Keep |
986 DWARFLinker::TF_DependencyWalk | ODRFlag);
987 }
988}
989
990/// Look at the parent of the given DIE and decide whether they should be kept.
991void DWARFLinker::lookForParentDIEsToKeep(
992 unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
993 SmallVectorImpl<WorklistItem> &Worklist) {
994 // Stop if we encounter an ancestor that's already marked as kept.
995 if (CU.getInfo(AncestorIdx).Keep)
996 return;
997
998 DWARFUnit &Unit = CU.getOrigUnit();
999 DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
1000 Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
1001 Worklist.emplace_back(ParentDIE, CU, Flags);
1002}
1003
1004/// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
1005/// information in \p CU's DIEInfo.
1006///
1007/// This function is the entry point of the DIE selection algorithm. It is
1008/// expected to walk the DIE tree in file order and (though the mediation of
1009/// its helper) call hasValidRelocation() on each DIE that might be a 'root
1010/// DIE' (See DwarfLinker class comment).
1011///
1012/// While walking the dependencies of root DIEs, this function is also called,
1013/// but during these dependency walks the file order is not respected. The
1014/// TF_DependencyWalk flag tells us which kind of traversal we are currently
1015/// doing.
1016///
1017/// The recursive algorithm is implemented iteratively as a work list because
1018/// very deep recursion could exhaust the stack for large projects. The work
1019/// list acts as a scheduler for different types of work that need to be
1020/// performed.
1021///
1022/// The recursive nature of the algorithm is simulated by running the "main"
1023/// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
1024/// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
1025/// fixing up a computed property (UpdateChildIncompleteness,
1026/// UpdateRefIncompleteness).
1027///
1028/// The return value indicates whether the DIE is incomplete.
1029void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
1030 const UnitListTy &Units,
1031 const DWARFDie &Die, const DWARFFile &File,
1032 CompileUnit &Cu, unsigned Flags) {
1033 // LIFO work list.
1035 Worklist.emplace_back(Die, Cu, Flags);
1036
1037 while (!Worklist.empty()) {
1038 WorklistItem Current = Worklist.pop_back_val();
1039
1040 // Look at the worklist type to decide what kind of work to perform.
1041 switch (Current.Type) {
1042 case WorklistItemType::UpdateChildIncompleteness:
1043 updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
1044 continue;
1045 case WorklistItemType::UpdateRefIncompleteness:
1046 updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
1047 continue;
1048 case WorklistItemType::LookForChildDIEsToKeep:
1049 lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
1050 continue;
1051 case WorklistItemType::LookForRefDIEsToKeep:
1052 lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
1053 Worklist);
1054 continue;
1055 case WorklistItemType::LookForParentDIEsToKeep:
1056 lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
1057 Worklist);
1058 continue;
1059 case WorklistItemType::MarkODRCanonicalDie:
1060 markODRCanonicalDie(Current.Die, Current.CU);
1061 continue;
1062 case WorklistItemType::LookForDIEsToKeep:
1063 break;
1064 }
1065
1066 unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
1067 CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
1068
1069 if (MyInfo.Prune) {
1070 // We're walking the dependencies of a module forward declaration that was
1071 // kept because there is no definition.
1072 if (Current.Flags & TF_DependencyWalk)
1073 MyInfo.Prune = false;
1074 else
1075 continue;
1076 }
1077
1078 // If the Keep flag is set, we are marking a required DIE's dependencies.
1079 // If our target is already marked as kept, we're all set.
1080 bool AlreadyKept = MyInfo.Keep;
1081 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
1082 continue;
1083
1084 if (!(Current.Flags & TF_DependencyWalk))
1085 Current.Flags = shouldKeepDIE(AddressesMap, Current.Die, File, Current.CU,
1086 MyInfo, Current.Flags);
1087
1088 // We need to mark context for the canonical die in the end of normal
1089 // traversing(not TF_DependencyWalk) or after normal traversing if die
1090 // was not marked as kept.
1091 if (!(Current.Flags & TF_DependencyWalk) ||
1092 (MyInfo.ODRMarkingDone && !MyInfo.Keep)) {
1093 if (Current.CU.hasODR() || MyInfo.InModuleScope)
1094 Worklist.emplace_back(Current.Die, Current.CU,
1095 WorklistItemType::MarkODRCanonicalDie);
1096 }
1097
1098 // Finish by looking for child DIEs. Because of the LIFO worklist we need
1099 // to schedule that work before any subsequent items are added to the
1100 // worklist.
1101 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1102 WorklistItemType::LookForChildDIEsToKeep);
1103
1104 if (AlreadyKept || !(Current.Flags & TF_Keep))
1105 continue;
1106
1107 // If it is a newly kept DIE mark it as well as all its dependencies as
1108 // kept.
1109 MyInfo.Keep = true;
1110
1111 // We're looking for incomplete types.
1112 MyInfo.Incomplete =
1113 Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
1114 Current.Die.getTag() != dwarf::DW_TAG_member &&
1115 dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
1116
1117 // After looking at the parent chain, look for referenced DIEs. Because of
1118 // the LIFO worklist we need to schedule that work before any subsequent
1119 // items are added to the worklist.
1120 Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
1121 WorklistItemType::LookForRefDIEsToKeep);
1122
1123 bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
1124 : Current.CU.hasODR();
1125 unsigned ODRFlag = UseOdr ? TF_ODR : 0;
1126 unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
1127
1128 // Now schedule the parent walk.
1129 Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
1130 }
1131}
1132
1133#ifndef NDEBUG
1134/// A broken link in the keep chain. By recording both the parent and the child
1135/// we can show only broken links for DIEs with multiple children.
1141
1142/// Verify the keep chain by looking for DIEs that are kept but who's parent
1143/// isn't.
1145 std::vector<DWARFDie> Worklist;
1146 Worklist.push_back(CU.getOrigUnit().getUnitDIE());
1147
1148 // List of broken links.
1149 std::vector<BrokenLink> BrokenLinks;
1150
1151 while (!Worklist.empty()) {
1152 const DWARFDie Current = Worklist.back();
1153 Worklist.pop_back();
1154
1155 const bool CurrentDieIsKept = CU.getInfo(Current).Keep;
1156
1157 for (DWARFDie Child : reverse(Current.children())) {
1158 Worklist.push_back(Child);
1159
1160 const bool ChildDieIsKept = CU.getInfo(Child).Keep;
1161 if (!CurrentDieIsKept && ChildDieIsKept)
1162 BrokenLinks.emplace_back(Current, Child);
1163 }
1164 }
1165
1166 if (!BrokenLinks.empty()) {
1167 for (BrokenLink Link : BrokenLinks) {
1169 "Found invalid link in keep chain between {0:x} and {1:x}\n",
1170 Link.Parent.getOffset(), Link.Child.getOffset());
1171
1172 errs() << "Parent:";
1173 Link.Parent.dump(errs(), 0, {});
1174 CU.getInfo(Link.Parent).dump();
1175
1176 errs() << "Child:";
1177 Link.Child.dump(errs(), 2, {});
1178 CU.getInfo(Link.Child).dump();
1179 }
1180 report_fatal_error("invalid keep chain");
1181 }
1182}
1183#endif
1184
1185/// Assign an abbreviation number to \p Abbrev.
1186///
1187/// Our DIEs get freed after every DebugMapObject has been processed,
1188/// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
1189/// the instances hold by the DIEs. When we encounter an abbreviation
1190/// that we don't know, we create a permanent copy of it.
1191void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
1192 // Check the set for priors.
1193 FoldingSetNodeID ID;
1194 Abbrev.Profile(ID);
1195 void *InsertToken;
1196 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
1197
1198 // If it's newly added.
1199 if (InSet) {
1200 // Assign existing abbreviation number.
1201 Abbrev.setNumber(InSet->getNumber());
1202 } else {
1203 // Add to abbreviation list.
1204 Abbreviations.push_back(
1205 std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
1206 for (const auto &Attr : Abbrev.getData())
1207 Abbreviations.back()->AddAttribute(Attr);
1208 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
1209 // Assign the unique abbreviation number.
1210 Abbrev.setNumber(Abbreviations.size());
1211 Abbreviations.back()->setNumber(Abbreviations.size());
1212 }
1213}
1214
1215unsigned DWARFLinker::DIECloner::cloneStringAttribute(DIE &Die,
1216 AttributeSpec AttrSpec,
1217 const DWARFFormValue &Val,
1218 const DWARFUnit &U,
1219 AttributesInfo &Info) {
1220 std::optional<const char *> String = dwarf::toString(Val);
1221 if (!String)
1222 return 0;
1223 DwarfStringPoolEntryRef StringEntry;
1224 if (AttrSpec.Form == dwarf::DW_FORM_line_strp) {
1225 StringEntry = DebugLineStrPool.getEntry(*String);
1226 } else {
1227 StringEntry = DebugStrPool.getEntry(*String);
1228
1229 if (AttrSpec.Attr == dwarf::DW_AT_APPLE_origin) {
1230 Info.HasAppleOrigin = true;
1231 if (std::optional<StringRef> FileName =
1232 ObjFile.Addresses->getLibraryInstallName()) {
1233 StringEntry = DebugStrPool.getEntry(*FileName);
1234 }
1235 }
1236
1237 // Update attributes info.
1238 if (AttrSpec.Attr == dwarf::DW_AT_name)
1239 Info.Name = StringEntry;
1240 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
1241 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
1242 Info.MangledName = StringEntry;
1243 if (U.getVersion() >= 5) {
1244 // Switch everything to DW_FORM_strx strings.
1245 auto StringOffsetIndex =
1246 StringOffsetPool.getValueIndex(StringEntry.getOffset());
1247 return Die
1248 .addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1249 dwarf::DW_FORM_strx, DIEInteger(StringOffsetIndex))
1250 ->sizeOf(U.getFormParams());
1251 }
1252 // Switch everything to out of line strings.
1253 AttrSpec.Form = dwarf::DW_FORM_strp;
1254 }
1255 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), AttrSpec.Form,
1256 DIEInteger(StringEntry.getOffset()));
1257 return 4;
1258}
1259
1260unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
1261 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1262 unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
1263 CompileUnit &Unit) {
1264 const DWARFUnit &U = Unit.getOrigUnit();
1265 uint64_t Ref;
1266 if (std::optional<uint64_t> Off = Val.getAsRelativeReference())
1267 Ref = Val.getUnit()->getOffset() + *Off;
1268 else if (Off = Val.getAsDebugInfoReference(); Off)
1269 Ref = *Off;
1270 else
1271 return 0;
1272
1273 DIE *NewRefDie = nullptr;
1274 CompileUnit *RefUnit = nullptr;
1275
1276 DWARFDie RefDie =
1277 Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
1278
1279 // If the referenced DIE is not found, drop the attribute.
1280 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
1281 return 0;
1282
1283 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
1284
1285 // If we already have emitted an equivalent DeclContext, just point
1286 // at it.
1287 if (isODRAttribute(AttrSpec.Attr) && RefInfo.Ctxt &&
1288 RefInfo.Ctxt->getCanonicalDIEOffset()) {
1289 assert(RefInfo.Ctxt->hasCanonicalDIE() &&
1290 "Offset to canonical die is set, but context is not marked");
1291 DIEInteger Attr(RefInfo.Ctxt->getCanonicalDIEOffset());
1292 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1293 dwarf::DW_FORM_ref_addr, Attr);
1294 return U.getRefAddrByteSize();
1295 }
1296
1297 if (!RefInfo.Clone) {
1298 // We haven't cloned this DIE yet. Just create an empty one and
1299 // store it. It'll get really cloned when we process it.
1300 RefInfo.UnclonedReference = true;
1301 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
1302 }
1303 NewRefDie = RefInfo.Clone;
1304
1305 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
1306 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
1307 if (Ref < InputDIE.getOffset() && !RefInfo.UnclonedReference) {
1308 // Backward reference: the target DIE is already cloned and
1309 // parented in a unit tree, so DIEEntry can resolve the
1310 // absolute offset at emission time.
1311 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1312 dwarf::DW_FORM_ref_addr, DIEEntry(*NewRefDie));
1313 } else {
1314 // Forward reference: the target DIE may be a placeholder that
1315 // never gets adopted into a unit tree (e.g. due to ODR
1316 // pruning), so DIEEntry cannot safely resolve it. Use a
1317 // placeholder integer and fix it up after all units are cloned.
1318 Unit.noteForwardReference(
1319 NewRefDie, RefUnit, RefInfo.Ctxt,
1320 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1321 dwarf::DW_FORM_ref_addr, DIEInteger(UINT64_MAX)));
1322 }
1323 return U.getRefAddrByteSize();
1324 }
1325
1326 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1327 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1328
1329 return AttrSize;
1330}
1331
1332void DWARFLinker::DIECloner::cloneExpression(
1333 DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
1334 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer,
1335 int64_t AddrRelocAdjustment, bool IsLittleEndian) {
1336 using Encoding = DWARFExpression::Operation::Encoding;
1337
1338 uint8_t OrigAddressByteSize = Unit.getOrigUnit().getAddressByteSize();
1339
1340 uint64_t OpOffset = 0;
1341 for (auto &Op : Expression) {
1342 auto Desc = Op.getDescription();
1343 // DW_OP_const_type is variable-length and has 3
1344 // operands. Thus far we only support 2.
1345 if ((Desc.Op.size() == 2 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1346 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1347 Desc.Op[0] != Encoding::Size1))
1348 Linker.reportWarning("Unsupported DW_OP encoding.", File);
1349
1350 if ((Desc.Op.size() == 1 && Desc.Op[0] == Encoding::BaseTypeRef) ||
1351 (Desc.Op.size() == 2 && Desc.Op[1] == Encoding::BaseTypeRef &&
1352 Desc.Op[0] == Encoding::Size1)) {
1353 // This code assumes that the other non-typeref operand fits into 1 byte.
1354 assert(OpOffset < Op.getEndOffset());
1355 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
1356 assert(ULEBsize <= 16);
1357
1358 // Copy over the operation.
1359 assert(!Op.getSubCode() && "SubOps not yet supported");
1360 OutputBuffer.push_back(Op.getCode());
1361 uint64_t RefOffset;
1362 if (Desc.Op.size() == 1) {
1363 RefOffset = Op.getRawOperand(0);
1364 } else {
1365 OutputBuffer.push_back(Op.getRawOperand(0));
1366 RefOffset = Op.getRawOperand(1);
1367 }
1368 uint32_t Offset = 0;
1369 // Look up the base type. For DW_OP_convert, the operand may be 0 to
1370 // instead indicate the generic type. The same holds for
1371 // DW_OP_reinterpret, which is currently not supported.
1372 if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
1373 RefOffset += Unit.getOrigUnit().getOffset();
1374 auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
1375 CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
1376 if (DIE *Clone = Info.Clone)
1377 Offset = Clone->getOffset();
1378 else
1379 Linker.reportWarning(
1380 "base type ref doesn't point to DW_TAG_base_type.", File);
1381 }
1382 uint8_t ULEB[16];
1383 unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
1384 if (RealSize > ULEBsize) {
1385 // Emit the generic type as a fallback.
1386 RealSize = encodeULEB128(0, ULEB, ULEBsize);
1387 Linker.reportWarning("base type ref doesn't fit.", File);
1388 }
1389 assert(RealSize == ULEBsize && "padding failed");
1390 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1391 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1392 } else if (!Linker.Options.Update && Op.getCode() == dwarf::DW_OP_addrx) {
1393 if (std::optional<object::SectionedAddress> SA =
1394 Unit.getOrigUnit().getAddrOffsetSectionItem(
1395 Op.getRawOperand(0))) {
1396 // DWARFLinker does not use addrx forms since it generates relocated
1397 // addresses. Replace DW_OP_addrx with DW_OP_addr here.
1398 // Argument of DW_OP_addrx should be relocated here as it is not
1399 // processed by applyValidRelocs.
1400 OutputBuffer.push_back(dwarf::DW_OP_addr);
1401 uint64_t LinkedAddress = SA->Address + AddrRelocAdjustment;
1402 if (IsLittleEndian != sys::IsLittleEndianHost)
1403 sys::swapByteOrder(LinkedAddress);
1404 ArrayRef<uint8_t> AddressBytes(
1405 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1406 OrigAddressByteSize);
1407 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1408 } else
1409 Linker.reportWarning("cannot read DW_OP_addrx operand.", File);
1410 } else if (!Linker.Options.Update && Op.getCode() == dwarf::DW_OP_constx) {
1411 if (std::optional<object::SectionedAddress> SA =
1412 Unit.getOrigUnit().getAddrOffsetSectionItem(
1413 Op.getRawOperand(0))) {
1414 // DWARFLinker does not use constx forms since it generates relocated
1415 // addresses. Replace DW_OP_constx with DW_OP_const[*]u here.
1416 // Argument of DW_OP_constx should be relocated here as it is not
1417 // processed by applyValidRelocs.
1418 std::optional<uint8_t> OutOperandKind;
1419 switch (OrigAddressByteSize) {
1420 case 4:
1421 OutOperandKind = dwarf::DW_OP_const4u;
1422 break;
1423 case 8:
1424 OutOperandKind = dwarf::DW_OP_const8u;
1425 break;
1426 default:
1427 Linker.reportWarning(
1428 formatv(("unsupported address size: {0}."), OrigAddressByteSize),
1429 File);
1430 break;
1431 }
1432
1433 if (OutOperandKind) {
1434 OutputBuffer.push_back(*OutOperandKind);
1435 uint64_t LinkedAddress = SA->Address + AddrRelocAdjustment;
1436 if (IsLittleEndian != sys::IsLittleEndianHost)
1437 sys::swapByteOrder(LinkedAddress);
1438 ArrayRef<uint8_t> AddressBytes(
1439 reinterpret_cast<const uint8_t *>(&LinkedAddress),
1440 OrigAddressByteSize);
1441 OutputBuffer.append(AddressBytes.begin(), AddressBytes.end());
1442 }
1443 } else
1444 Linker.reportWarning("cannot read DW_OP_constx operand.", File);
1445 } else {
1446 // Copy over everything else unmodified.
1447 StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
1448 OutputBuffer.append(Bytes.begin(), Bytes.end());
1449 }
1450 OpOffset = Op.getEndOffset();
1451 }
1452}
1453
1454unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1455 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1456 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1457 bool IsLittleEndian) {
1458 DIEValueList *Attr;
1459 DIEValue Value;
1460 DIELoc *Loc = nullptr;
1461 DIEBlock *Block = nullptr;
1462 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1463 Loc = new (DIEAlloc) DIELoc;
1464 Linker.DIELocs.push_back(Loc);
1465 } else {
1466 Block = new (DIEAlloc) DIEBlock;
1467 Linker.DIEBlocks.push_back(Block);
1468 }
1469 Attr = Loc ? static_cast<DIEValueList *>(Loc)
1470 : static_cast<DIEValueList *>(Block);
1471
1472 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1473 // If the block is a DWARF Expression, clone it into the temporary
1474 // buffer using cloneExpression(), otherwise copy the data directly.
1475 SmallVector<uint8_t, 32> Buffer;
1476 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1477 if (DWARFAttribute::mayHaveLocationExpr(AttrSpec.Attr) &&
1478 (Val.isFormClass(DWARFFormValue::FC_Block) ||
1479 Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1480 DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1481 IsLittleEndian, OrigUnit.getAddressByteSize());
1482 DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1483 OrigUnit.getFormParams().Format);
1484 cloneExpression(Data, Expr, File, Unit, Buffer,
1485 Unit.getInfo(InputDIE).AddrAdjust, IsLittleEndian);
1486 Bytes = Buffer;
1487 }
1488 for (auto Byte : Bytes)
1489 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1490 dwarf::DW_FORM_data1, DIEInteger(Byte));
1491
1492 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1493 // the DIE class, this "if" could be replaced by
1494 // Attr->setSize(Bytes.size()).
1495 if (Loc)
1496 Loc->setSize(Bytes.size());
1497 else
1498 Block->setSize(Bytes.size());
1499
1500 if (Loc)
1501 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1502 dwarf::Form(AttrSpec.Form), Loc);
1503 else {
1504 // The expression location data might be updated and exceed the original
1505 // size. Check whether the new data fits into the original form.
1506 if ((AttrSpec.Form == dwarf::DW_FORM_block1 &&
1507 (Bytes.size() > UINT8_MAX)) ||
1508 (AttrSpec.Form == dwarf::DW_FORM_block2 &&
1509 (Bytes.size() > UINT16_MAX)) ||
1510 (AttrSpec.Form == dwarf::DW_FORM_block4 && (Bytes.size() > UINT32_MAX)))
1511 AttrSpec.Form = dwarf::DW_FORM_block;
1512
1513 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1514 dwarf::Form(AttrSpec.Form), Block);
1515 }
1516
1517 return Die.addValue(DIEAlloc, Value)->sizeOf(OrigUnit.getFormParams());
1518}
1519
1520unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1521 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1522 unsigned AttrSize, const DWARFFormValue &Val, const CompileUnit &Unit,
1523 AttributesInfo &Info) {
1524 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1525 Info.HasLowPc = true;
1526
1527 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1528 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1529 dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1530 return AttrSize;
1531 }
1532
1533 // Cloned Die may have address attributes relocated to a
1534 // totally unrelated value. This can happen:
1535 // - If high_pc is an address (Dwarf version == 2), then it might have been
1536 // relocated to a totally unrelated value (because the end address in the
1537 // object file might be start address of another function which got moved
1538 // independently by the linker).
1539 // - If address relocated in an inline_subprogram that happens at the
1540 // beginning of its inlining function.
1541 // To avoid above cases and to not apply relocation twice (in
1542 // applyValidRelocs and here), read address attribute from InputDIE and apply
1543 // Info.PCOffset here.
1544
1545 std::optional<DWARFFormValue> AddrAttribute = InputDIE.find(AttrSpec.Attr);
1546 if (!AddrAttribute)
1547 llvm_unreachable("Cann't find attribute.");
1548
1549 std::optional<uint64_t> Addr = AddrAttribute->getAsAddress();
1550 if (!Addr) {
1551 Linker.reportWarning("Cann't read address attribute value.", ObjFile);
1552 return 0;
1553 }
1554
1555 if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1556 AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1557 if (std::optional<uint64_t> LowPC = Unit.getLowPc())
1558 Addr = *LowPC;
1559 else
1560 return 0;
1561 } else if (InputDIE.getTag() == dwarf::DW_TAG_compile_unit &&
1562 AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1563 if (uint64_t HighPc = Unit.getHighPc())
1564 Addr = HighPc;
1565 else
1566 return 0;
1567 } else {
1568 *Addr += Info.PCOffset;
1569 }
1570
1571 if (AttrSpec.Form == dwarf::DW_FORM_addr) {
1572 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1573 AttrSpec.Form, DIEInteger(*Addr));
1574 return Unit.getOrigUnit().getAddressByteSize();
1575 }
1576
1577 auto AddrIndex = AddrPool.getValueIndex(*Addr);
1578
1579 return Die
1580 .addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1581 dwarf::Form::DW_FORM_addrx, DIEInteger(AddrIndex))
1582 ->sizeOf(Unit.getOrigUnit().getFormParams());
1583}
1584
1585unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1586 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1587 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1588 unsigned AttrSize, AttributesInfo &Info) {
1589 uint64_t Value;
1590
1591 // We don't emit any skeleton CUs with dsymutil. So avoid emitting
1592 // a redundant DW_AT_GNU_dwo_id on the non-skeleton CU.
1593 if (AttrSpec.Attr == dwarf::DW_AT_GNU_dwo_id ||
1594 AttrSpec.Attr == dwarf::DW_AT_dwo_id)
1595 return 0;
1596
1597 // Check for the offset to the macro table. If offset is incorrect then we
1598 // need to remove the attribute.
1599 if (AttrSpec.Attr == dwarf::DW_AT_macro_info) {
1600 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
1601 const llvm::DWARFDebugMacro *Macro = File.Dwarf->getDebugMacinfo();
1602 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
1603 return 0;
1604 }
1605 }
1606
1607 if (AttrSpec.Attr == dwarf::DW_AT_macros) {
1608 if (std::optional<uint64_t> Offset = Val.getAsSectionOffset()) {
1609 const llvm::DWARFDebugMacro *Macro = File.Dwarf->getDebugMacro();
1610 if (Macro == nullptr || !Macro->hasEntryForOffset(*Offset))
1611 return 0;
1612 }
1613 }
1614
1615 if (AttrSpec.Attr == dwarf::DW_AT_str_offsets_base) {
1616 // DWARFLinker generates common .debug_str_offsets table used for all
1617 // compile units. The offset to the common .debug_str_offsets table is 8 on
1618 // DWARF32.
1619 Info.AttrStrOffsetBaseSeen = true;
1620 return Die
1621 .addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
1622 dwarf::DW_FORM_sec_offset, DIEInteger(8))
1623 ->sizeOf(Unit.getOrigUnit().getFormParams());
1624 }
1625
1626 if (AttrSpec.Attr == dwarf::DW_AT_LLVM_stmt_sequence) {
1627 // If needed, we'll patch this sec_offset later with the correct offset.
1628 auto Patch = Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1629 dwarf::DW_FORM_sec_offset,
1630 DIEInteger(*Val.getAsSectionOffset()));
1631
1632 // Record this patch location so that it can be fixed up later.
1633 Unit.noteStmtSeqListAttribute(Patch);
1634
1635 return Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1636 }
1637
1638 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1639 if (auto OptionalValue = Val.getAsUnsignedConstant())
1640 Value = *OptionalValue;
1641 else if (auto OptionalValue = Val.getAsSignedConstant())
1642 Value = *OptionalValue;
1643 else if (auto OptionalValue = Val.getAsSectionOffset())
1644 Value = *OptionalValue;
1645 else {
1646 Linker.reportWarning(
1647 "Unsupported scalar attribute form. Dropping attribute.", File,
1648 &InputDIE);
1649 return 0;
1650 }
1651 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1652 Info.IsDeclaration = true;
1653
1654 if (AttrSpec.Form == dwarf::DW_FORM_loclistx)
1655 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1656 dwarf::Form(AttrSpec.Form), DIELocList(Value));
1657 else
1658 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1659 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1660 return AttrSize;
1661 }
1662
1663 [[maybe_unused]] dwarf::Form OriginalForm = AttrSpec.Form;
1664 if (AttrSpec.Form == dwarf::DW_FORM_rnglistx) {
1665 // DWARFLinker does not generate .debug_addr table. Thus we need to change
1666 // all "addrx" related forms to "addr" version. Change DW_FORM_rnglistx
1667 // to DW_FORM_sec_offset here.
1668 std::optional<uint64_t> Index = Val.getAsSectionOffset();
1669 if (!Index) {
1670 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1671 &InputDIE);
1672 return 0;
1673 }
1674 std::optional<uint64_t> Offset =
1675 Unit.getOrigUnit().getRnglistOffset(*Index);
1676 if (!Offset) {
1677 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1678 &InputDIE);
1679 return 0;
1680 }
1681
1682 Value = *Offset;
1683 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1684 AttrSize = Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1685 } else if (AttrSpec.Form == dwarf::DW_FORM_loclistx) {
1686 // DWARFLinker does not generate .debug_addr table. Thus we need to change
1687 // all "addrx" related forms to "addr" version. Change DW_FORM_loclistx
1688 // to DW_FORM_sec_offset here.
1689 std::optional<uint64_t> Index = Val.getAsSectionOffset();
1690 if (!Index) {
1691 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1692 &InputDIE);
1693 return 0;
1694 }
1695 std::optional<uint64_t> Offset =
1696 Unit.getOrigUnit().getLoclistOffset(*Index);
1697 if (!Offset) {
1698 Linker.reportWarning("Cannot read the attribute. Dropping.", File,
1699 &InputDIE);
1700 return 0;
1701 }
1702
1703 Value = *Offset;
1704 AttrSpec.Form = dwarf::DW_FORM_sec_offset;
1705 AttrSize = Unit.getOrigUnit().getFormParams().getDwarfOffsetByteSize();
1706 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1707 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1708 std::optional<uint64_t> LowPC = Unit.getLowPc();
1709 if (!LowPC)
1710 return 0;
1711 // Dwarf >= 4 high_pc is an size, not an address.
1712 Value = Unit.getHighPc() - *LowPC;
1713 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1714 Value = *Val.getAsSectionOffset();
1715 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1716 Value = *Val.getAsSignedConstant();
1717 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1718 Value = *OptionalValue;
1719 else {
1720 Linker.reportWarning(
1721 "Unsupported scalar attribute form. Dropping attribute.", File,
1722 &InputDIE);
1723 return 0;
1724 }
1725
1726 DIE::value_iterator Patch =
1727 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1728 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1729 if (AttrSpec.Attr == dwarf::DW_AT_ranges ||
1730 AttrSpec.Attr == dwarf::DW_AT_start_scope) {
1731 Unit.noteRangeAttribute(Die, Patch);
1732 Info.HasRanges = true;
1733 } else if (DWARFAttribute::mayHaveLocationList(AttrSpec.Attr) &&
1734 dwarf::doesFormBelongToClass(AttrSpec.Form,
1736 Unit.getOrigUnit().getVersion())) {
1737
1738 CompileUnit::DIEInfo &LocationDieInfo = Unit.getInfo(InputDIE);
1739 Unit.noteLocationAttribute({Patch, LocationDieInfo.InDebugMap
1740 ? LocationDieInfo.AddrAdjust
1741 : Info.PCOffset});
1742 } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1743 Info.IsDeclaration = true;
1744
1745 // check that all dwarf::DW_FORM_rnglistx are handled previously.
1746 assert((Info.HasRanges || (OriginalForm != dwarf::DW_FORM_rnglistx)) &&
1747 "Unhandled DW_FORM_rnglistx attribute");
1748
1749 return AttrSize;
1750}
1751
1752/// Clone \p InputDIE's attribute described by \p AttrSpec with
1753/// value \p Val, and add it to \p Die.
1754/// \returns the size of the cloned attribute.
1755unsigned DWARFLinker::DIECloner::cloneAttribute(
1756 DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1757 CompileUnit &Unit, const DWARFFormValue &Val, const AttributeSpec AttrSpec,
1758 unsigned AttrSize, AttributesInfo &Info, bool IsLittleEndian) {
1759 const DWARFUnit &U = Unit.getOrigUnit();
1760
1761 switch (AttrSpec.Form) {
1762 case dwarf::DW_FORM_strp:
1763 case dwarf::DW_FORM_line_strp:
1764 case dwarf::DW_FORM_string:
1765 case dwarf::DW_FORM_strx:
1766 case dwarf::DW_FORM_strx1:
1767 case dwarf::DW_FORM_strx2:
1768 case dwarf::DW_FORM_strx3:
1769 case dwarf::DW_FORM_strx4:
1770 return cloneStringAttribute(Die, AttrSpec, Val, U, Info);
1771 case dwarf::DW_FORM_ref_addr:
1772 case dwarf::DW_FORM_ref1:
1773 case dwarf::DW_FORM_ref2:
1774 case dwarf::DW_FORM_ref4:
1775 case dwarf::DW_FORM_ref8:
1776 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1777 File, Unit);
1778 case dwarf::DW_FORM_block:
1779 case dwarf::DW_FORM_block1:
1780 case dwarf::DW_FORM_block2:
1781 case dwarf::DW_FORM_block4:
1782 case dwarf::DW_FORM_exprloc:
1783 return cloneBlockAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1784 IsLittleEndian);
1785 case dwarf::DW_FORM_addr:
1786 case dwarf::DW_FORM_addrx:
1787 case dwarf::DW_FORM_addrx1:
1788 case dwarf::DW_FORM_addrx2:
1789 case dwarf::DW_FORM_addrx3:
1790 case dwarf::DW_FORM_addrx4:
1791 return cloneAddressAttribute(Die, InputDIE, AttrSpec, AttrSize, Val, Unit,
1792 Info);
1793 case dwarf::DW_FORM_data1:
1794 case dwarf::DW_FORM_data2:
1795 case dwarf::DW_FORM_data4:
1796 case dwarf::DW_FORM_data8:
1797 case dwarf::DW_FORM_udata:
1798 case dwarf::DW_FORM_sdata:
1799 case dwarf::DW_FORM_sec_offset:
1800 case dwarf::DW_FORM_flag:
1801 case dwarf::DW_FORM_flag_present:
1802 case dwarf::DW_FORM_rnglistx:
1803 case dwarf::DW_FORM_loclistx:
1804 case dwarf::DW_FORM_implicit_const:
1805 return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1806 AttrSize, Info);
1807 default:
1808 Linker.reportWarning("Unsupported attribute form " +
1809 dwarf::FormEncodingString(AttrSpec.Form) +
1810 " in cloneAttribute. Dropping.",
1811 File, &InputDIE);
1812 }
1813
1814 return 0;
1815}
1816
1817void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1818 const DIE *Die,
1819 DwarfStringPoolEntryRef Name,
1820 OffsetsStringPool &StringPool,
1821 bool SkipPubSection) {
1822 std::optional<ObjCSelectorNames> Names =
1823 getObjCNamesIfSelector(Name.getString());
1824 if (!Names)
1825 return;
1826 Unit.addNameAccelerator(Die, StringPool.getEntry(Names->Selector),
1827 SkipPubSection);
1828 Unit.addObjCAccelerator(Die, StringPool.getEntry(Names->ClassName),
1829 SkipPubSection);
1830 if (Names->ClassNameNoCategory)
1831 Unit.addObjCAccelerator(
1832 Die, StringPool.getEntry(*Names->ClassNameNoCategory), SkipPubSection);
1833 if (Names->MethodNameNoCategory)
1834 Unit.addNameAccelerator(
1835 Die, StringPool.getEntry(*Names->MethodNameNoCategory), SkipPubSection);
1836}
1837
1838static bool
1841 bool SkipPC) {
1842 switch (AttrSpec.Attr) {
1843 default:
1844 return false;
1845 case dwarf::DW_AT_low_pc:
1846 case dwarf::DW_AT_high_pc:
1847 case dwarf::DW_AT_ranges:
1848 return !Update && SkipPC;
1849 case dwarf::DW_AT_rnglists_base:
1850 // In case !Update the .debug_addr table is not generated/preserved.
1851 // Thus instead of DW_FORM_rnglistx the DW_FORM_sec_offset is used.
1852 // Since DW_AT_rnglists_base is used for only DW_FORM_rnglistx the
1853 // DW_AT_rnglists_base is removed.
1854 return !Update;
1855 case dwarf::DW_AT_loclists_base:
1856 // In case !Update the .debug_addr table is not generated/preserved.
1857 // Thus instead of DW_FORM_loclistx the DW_FORM_sec_offset is used.
1858 // Since DW_AT_loclists_base is used for only DW_FORM_loclistx the
1859 // DW_AT_loclists_base is removed.
1860 return !Update;
1861 case dwarf::DW_AT_location:
1862 case dwarf::DW_AT_frame_base:
1863 return !Update && SkipPC;
1864 }
1865}
1866
1872
1873DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
1874 const DWARFFile &File, CompileUnit &Unit,
1875 int64_t PCOffset, uint32_t OutOffset,
1876 unsigned Flags, bool IsLittleEndian,
1877 DIE *Die) {
1878 DWARFUnit &U = Unit.getOrigUnit();
1879 unsigned Idx = U.getDIEIndex(InputDIE);
1880 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1881
1882 // Should the DIE appear in the output?
1883 if (!Unit.getInfo(Idx).Keep)
1884 return nullptr;
1885
1886 uint64_t Offset = InputDIE.getOffset();
1887 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1888 if (!Die) {
1889 // The DIE might have been already created by a forward reference
1890 // (see cloneDieReferenceAttribute()).
1891 if (!Info.Clone)
1892 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1893 Die = Info.Clone;
1894 }
1895
1896 assert(Die->getTag() == InputDIE.getTag());
1897 Die->setOffset(OutOffset);
1898 if (isODRCanonicalCandidate(InputDIE, Unit) && Info.Ctxt &&
1899 (Info.Ctxt->getCanonicalDIEOffset() == 0)) {
1900 if (!Info.Ctxt->hasCanonicalDIE())
1901 Info.Ctxt->setHasCanonicalDIE();
1902 // We are about to emit a DIE that is the root of its own valid
1903 // DeclContext tree. Make the current offset the canonical offset
1904 // for this context.
1905 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1906 }
1907
1908 // Extract and clone every attribute.
1909 DWARFDataExtractor Data = U.getDebugInfoExtractor();
1910 // Point to the next DIE (generally there is always at least a NULL
1911 // entry after the current one). If this is a lone
1912 // DW_TAG_compile_unit without any children, point to the next unit.
1913 uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1914 ? U.getDIEAtIndex(Idx + 1).getOffset()
1915 : U.getNextUnitOffset();
1916 AttributesInfo AttrInfo;
1917
1918 // We could copy the data only if we need to apply a relocation to it. After
1919 // testing, it seems there is no performance downside to doing the copy
1920 // unconditionally, and it makes the code simpler.
1921 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1922 Data =
1923 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1924
1925 // Modify the copy with relocated addresses.
1926 ObjFile.Addresses->applyValidRelocs(DIECopy, Offset, Data.isLittleEndian());
1927
1928 // Reset the Offset to 0 as we will be working on the local copy of
1929 // the data.
1930 Offset = 0;
1931
1932 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1933 Offset += getULEB128Size(Abbrev->getCode());
1934
1935 // We are entering a subprogram. Get and propagate the PCOffset.
1936 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1937 PCOffset = Info.AddrAdjust;
1938 AttrInfo.PCOffset = PCOffset;
1939
1940 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1941 Flags |= TF_InFunctionScope;
1942 if (!Info.InDebugMap && LLVM_LIKELY(!Update))
1943 Flags |= TF_SkipPC;
1944 } else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
1945 // Function-local globals could be in the debug map even when the function
1946 // is not, e.g., inlined functions.
1947 if ((Flags & TF_InFunctionScope) && Info.InDebugMap)
1948 Flags &= ~TF_SkipPC;
1949 // Location expressions referencing an address which is not in debug map
1950 // should be deleted.
1951 else if (!Info.InDebugMap && Info.HasLocationExpressionAddr &&
1952 LLVM_LIKELY(!Update))
1953 Flags |= TF_SkipPC;
1954 }
1955
1956 std::optional<StringRef> LibraryInstallName =
1957 ObjFile.Addresses->getLibraryInstallName();
1959 for (const auto &AttrSpec : Abbrev->attributes()) {
1960 if (shouldSkipAttribute(Update, AttrSpec, Flags & TF_SkipPC)) {
1961 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1962 U.getFormParams());
1963 continue;
1964 }
1965
1966 AttributeLinkedOffsetFixup CurAttrFixup;
1967 CurAttrFixup.InputAttrStartOffset = InputDIE.getOffset() + Offset;
1968 CurAttrFixup.LinkedOffsetFixupVal =
1969 Unit.getStartOffset() + OutOffset - CurAttrFixup.InputAttrStartOffset;
1970
1971 DWARFFormValue Val = AttrSpec.getFormValue();
1972 uint64_t AttrSize = Offset;
1973 Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1974 CurAttrFixup.InputAttrEndOffset = InputDIE.getOffset() + Offset;
1975 AttrSize = Offset - AttrSize;
1976
1977 uint64_t FinalAttrSize =
1978 cloneAttribute(*Die, InputDIE, File, Unit, Val, AttrSpec, AttrSize,
1979 AttrInfo, IsLittleEndian);
1980 if (FinalAttrSize != 0 && ObjFile.Addresses->needToSaveValidRelocs())
1981 AttributesFixups.push_back(CurAttrFixup);
1982
1983 OutOffset += FinalAttrSize;
1984 }
1985
1986 uint16_t Tag = InputDIE.getTag();
1987 // Add the DW_AT_APPLE_origin attribute to Compile Unit die if we have
1988 // an install name and the DWARF doesn't have the attribute yet.
1989 const bool NeedsAppleOrigin = (Tag == dwarf::DW_TAG_compile_unit) &&
1990 LibraryInstallName.has_value() &&
1991 !AttrInfo.HasAppleOrigin;
1992 if (NeedsAppleOrigin) {
1993 auto StringEntry = DebugStrPool.getEntry(LibraryInstallName.value());
1994 Die->addValue(DIEAlloc, dwarf::Attribute(dwarf::DW_AT_APPLE_origin),
1995 dwarf::DW_FORM_strp, DIEInteger(StringEntry.getOffset()));
1996 AttrInfo.Name = StringEntry;
1997 OutOffset += 4;
1998 }
1999
2000 // Look for accelerator entries.
2001 // FIXME: This is slightly wrong. An inline_subroutine without a
2002 // low_pc, but with AT_ranges might be interesting to get into the
2003 // accelerator tables too. For now stick with dsymutil's behavior.
2004 if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
2005 Tag != dwarf::DW_TAG_compile_unit &&
2006 getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit,
2007 Tag != dwarf::DW_TAG_inlined_subroutine)) {
2008 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2009 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2010 Tag == dwarf::DW_TAG_inlined_subroutine);
2011 if (AttrInfo.Name) {
2012 if (AttrInfo.NameWithoutTemplate)
2013 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
2014 /* SkipPubSection */ true);
2015 Unit.addNameAccelerator(Die, AttrInfo.Name,
2016 Tag == dwarf::DW_TAG_inlined_subroutine);
2017 }
2018 if (AttrInfo.Name)
2019 addObjCAccelerator(Unit, Die, AttrInfo.Name, DebugStrPool,
2020 /* SkipPubSection =*/true);
2021
2022 } else if (Tag == dwarf::DW_TAG_namespace) {
2023 if (!AttrInfo.Name)
2024 AttrInfo.Name = DebugStrPool.getEntry("(anonymous namespace)");
2025 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
2026 } else if (Tag == dwarf::DW_TAG_imported_declaration && AttrInfo.Name) {
2027 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
2028 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration) {
2029 bool Success = getDIENames(InputDIE, AttrInfo, DebugStrPool, File, Unit);
2030 uint64_t RuntimeLang =
2031 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
2032 .value_or(0);
2033 bool ObjCClassIsImplementation =
2034 (RuntimeLang == dwarf::DW_LANG_ObjC ||
2035 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
2036 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
2037 .value_or(0);
2038 if (Success && AttrInfo.Name && !AttrInfo.Name.getString().empty()) {
2039 uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
2040 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
2041 Hash);
2042 }
2043
2044 // For Swift, mangled names are put into DW_AT_linkage_name.
2045 if (Success && AttrInfo.MangledName &&
2046 RuntimeLang == dwarf::DW_LANG_Swift &&
2047 !AttrInfo.MangledName.getString().empty() &&
2048 AttrInfo.MangledName != AttrInfo.Name) {
2049 auto Hash = djbHash(AttrInfo.MangledName.getString().data());
2050 Unit.addTypeAccelerator(Die, AttrInfo.MangledName,
2051 ObjCClassIsImplementation, Hash);
2052 }
2053 }
2054
2055 // Determine whether there are any children that we want to keep.
2056 bool HasChildren = false;
2057 for (auto Child : InputDIE.children()) {
2058 unsigned Idx = U.getDIEIndex(Child);
2059 if (Unit.getInfo(Idx).Keep) {
2060 HasChildren = true;
2061 break;
2062 }
2063 }
2064
2065 if (Unit.getOrigUnit().getVersion() >= 5 && !AttrInfo.AttrStrOffsetBaseSeen &&
2066 Die->getTag() == dwarf::DW_TAG_compile_unit) {
2067 // No DW_AT_str_offsets_base seen, add it to the DIE.
2068 Die->addValue(DIEAlloc, dwarf::DW_AT_str_offsets_base,
2069 dwarf::DW_FORM_sec_offset, DIEInteger(8));
2070 OutOffset += 4;
2071 }
2072
2073 DIEAbbrev NewAbbrev = Die->generateAbbrev();
2074 if (HasChildren)
2076 // Assign a permanent abbrev number
2077 Linker.assignAbbrev(NewAbbrev);
2078 Die->setAbbrevNumber(NewAbbrev.getNumber());
2079
2080 uint64_t AbbrevNumberSize = getULEB128Size(Die->getAbbrevNumber());
2081
2082 // Add the size of the abbreviation number to the output offset.
2083 OutOffset += AbbrevNumberSize;
2084
2085 // Update fixups with the size of the abbreviation number
2086 for (AttributeLinkedOffsetFixup &F : AttributesFixups)
2087 F.LinkedOffsetFixupVal += AbbrevNumberSize;
2088
2089 for (AttributeLinkedOffsetFixup &F : AttributesFixups)
2090 ObjFile.Addresses->updateAndSaveValidRelocs(
2091 Unit.getOrigUnit().getVersion() >= 5, Unit.getOrigUnit().getOffset(),
2092 F.LinkedOffsetFixupVal, F.InputAttrStartOffset, F.InputAttrEndOffset);
2093
2094 if (!HasChildren) {
2095 // Update our size.
2096 Die->setSize(OutOffset - Die->getOffset());
2097 return Die;
2098 }
2099
2100 // Recursively clone children.
2101 for (auto Child : InputDIE.children()) {
2102 if (DIE *Clone = cloneDIE(Child, File, Unit, PCOffset, OutOffset, Flags,
2103 IsLittleEndian)) {
2104 Die->addChild(Clone);
2105 OutOffset = Clone->getOffset() + Clone->getSize();
2106 }
2107 }
2108
2109 // Account for the end of children marker.
2110 OutOffset += sizeof(int8_t);
2111 // Update our size.
2112 Die->setSize(OutOffset - Die->getOffset());
2113 return Die;
2114}
2115
2116/// Patch the input object file relevant debug_ranges or debug_rnglists
2117/// entries and emit them in the output file. Update the relevant attributes
2118/// to point at the new entries.
2119Error DWARFLinker::generateUnitRanges(CompileUnit &Unit, const DWARFFile &File,
2120 DebugDieValuePool &AddrPool) const {
2121 if (LLVM_UNLIKELY(Options.Update))
2122 return Error::success();
2123
2124 const auto &FunctionRanges = Unit.getFunctionRanges();
2125
2126 // Build set of linked address ranges for unit function ranges.
2127 AddressRanges LinkedFunctionRanges;
2128 for (const AddressRangeValuePair &Range : FunctionRanges)
2129 LinkedFunctionRanges.insert(
2130 {Range.Range.start() + Range.Value, Range.Range.end() + Range.Value});
2131
2132 // Emit LinkedFunctionRanges into .debug_aranges
2133 if (!LinkedFunctionRanges.empty())
2134 TheDwarfEmitter->emitDwarfDebugArangesTable(Unit, LinkedFunctionRanges);
2135
2136 RngListAttributesTy AllRngListAttributes = Unit.getRangesAttributes();
2137 std::optional<PatchLocation> UnitRngListAttribute =
2138 Unit.getUnitRangesAttribute();
2139
2140 if (!AllRngListAttributes.empty() || UnitRngListAttribute) {
2141 std::optional<AddressRangeValuePair> CachedRange;
2142 MCSymbol *EndLabel = TheDwarfEmitter->emitDwarfDebugRangeListHeader(Unit);
2143
2144 // Read original address ranges, apply relocation value, emit linked address
2145 // ranges.
2146 for (PatchLocation &AttributePatch : AllRngListAttributes) {
2147 // Get ranges from the source DWARF corresponding to the current
2148 // attribute.
2149 AddressRanges LinkedRanges;
2150 if (Expected<DWARFAddressRangesVector> OriginalRanges =
2151 Unit.getOrigUnit().findRnglistFromOffset(AttributePatch.get())) {
2152 // Apply relocation adjustment.
2153 for (const auto &Range : *OriginalRanges) {
2154 if (!CachedRange || !CachedRange->Range.contains(Range.LowPC))
2155 CachedRange = FunctionRanges.getRangeThatContains(Range.LowPC);
2156
2157 // All range entries should lie in the function range.
2158 if (!CachedRange) {
2159 reportWarning("inconsistent range data.", File);
2160 continue;
2161 }
2162
2163 // Store range for emiting.
2164 LinkedRanges.insert({Range.LowPC + CachedRange->Value,
2165 Range.HighPC + CachedRange->Value});
2166 }
2167 } else {
2168 llvm::consumeError(OriginalRanges.takeError());
2169 reportWarning("invalid range list ignored.", File);
2170 }
2171
2172 // Emit linked ranges.
2173 if (Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2174 Unit, LinkedRanges, AttributePatch, AddrPool))
2175 return E;
2176 }
2177
2178 // Emit ranges for Unit AT_ranges attribute.
2179 if (UnitRngListAttribute.has_value())
2180 if (Error E = TheDwarfEmitter->emitDwarfDebugRangeListFragment(
2181 Unit, LinkedFunctionRanges, *UnitRngListAttribute, AddrPool))
2182 return E;
2183
2184 // Emit ranges footer.
2185 TheDwarfEmitter->emitDwarfDebugRangeListFooter(Unit, EndLabel);
2186 }
2187
2188 return Error::success();
2189}
2190
2191Error DWARFLinker::DIECloner::generateUnitLocations(
2192 CompileUnit &Unit, const DWARFFile &File,
2193 ExpressionHandlerRef ExprHandler) {
2194 if (LLVM_UNLIKELY(Linker.Options.Update))
2195 return Error::success();
2196
2197 const LocListAttributesTy &AllLocListAttributes =
2198 Unit.getLocationAttributes();
2199
2200 if (AllLocListAttributes.empty())
2201 return Error::success();
2202
2203 // Emit locations list table header.
2204 MCSymbol *EndLabel = Emitter->emitDwarfDebugLocListHeader(Unit);
2205
2206 for (auto &CurLocAttr : AllLocListAttributes) {
2207 // Get location expressions vector corresponding to the current attribute
2208 // from the source DWARF.
2209 Expected<DWARFLocationExpressionsVector> OriginalLocations =
2210 Unit.getOrigUnit().findLoclistFromOffset(CurLocAttr.get());
2211
2212 if (!OriginalLocations) {
2213 llvm::consumeError(OriginalLocations.takeError());
2214 Linker.reportWarning("Invalid location attribute ignored.", File);
2215 continue;
2216 }
2217
2218 DWARFLocationExpressionsVector LinkedLocationExpressions;
2219 for (DWARFLocationExpression &CurExpression : *OriginalLocations) {
2220 DWARFLocationExpression LinkedExpression;
2221
2222 if (CurExpression.Range) {
2223 // Relocate address range.
2224 LinkedExpression.Range = {
2225 CurExpression.Range->LowPC + CurLocAttr.RelocAdjustment,
2226 CurExpression.Range->HighPC + CurLocAttr.RelocAdjustment};
2227 }
2228
2229 // Clone expression.
2230 LinkedExpression.Expr.reserve(CurExpression.Expr.size());
2231 ExprHandler(CurExpression.Expr, LinkedExpression.Expr,
2232 CurLocAttr.RelocAdjustment);
2233
2234 LinkedLocationExpressions.push_back(LinkedExpression);
2235 }
2236
2237 // Emit locations list table fragment corresponding to the CurLocAttr.
2238 if (Error E = Emitter->emitDwarfDebugLocListFragment(
2239 Unit, LinkedLocationExpressions, CurLocAttr, AddrPool))
2240 return E;
2241 }
2242
2243 // Emit locations list table footer.
2244 Emitter->emitDwarfDebugLocListFooter(Unit, EndLabel);
2245
2246 return Error::success();
2247}
2248
2250 for (auto &V : Die.values())
2251 if (V.getAttribute() == dwarf::DW_AT_addr_base) {
2252 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2253 return;
2254 }
2255
2256 llvm_unreachable("Didn't find a DW_AT_addr_base in cloned DIE!");
2257}
2258
2259Error DWARFLinker::DIECloner::emitDebugAddrSection(
2260 CompileUnit &Unit, const uint16_t DwarfVersion) const {
2261
2262 if (LLVM_UNLIKELY(Linker.Options.Update))
2263 return Error::success();
2264
2265 if (DwarfVersion < 5)
2266 return Error::success();
2267
2268 if (AddrPool.getValues().empty())
2269 return Error::success();
2270
2271 MCSymbol *EndLabel = Emitter->emitDwarfDebugAddrsHeader(Unit);
2272 uint64_t AddrOffset = Emitter->getDebugAddrSectionSize();
2273 dwarf::FormParams FP = Unit.getOrigUnit().getFormParams();
2274 if (AddrOffset > FP.getDwarfMaxOffset())
2275 return createStringError(".debug_addr section offset 0x" +
2276 Twine::utohexstr(AddrOffset) + " exceeds the " +
2277 dwarf::FormatString(FP.Format) + " limit");
2278 patchAddrBase(*Unit.getOutputUnitDIE(), DIEInteger(AddrOffset));
2279 Emitter->emitDwarfDebugAddrs(AddrPool.getValues(),
2280 Unit.getOrigUnit().getAddressByteSize());
2281 Emitter->emitDwarfDebugAddrsFooter(Unit, EndLabel);
2282
2283 return Error::success();
2284}
2285
2286/// A helper struct to help keep track of the association between the input and
2287/// output rows during line table rewriting. This is used to patch
2288/// DW_AT_LLVM_stmt_sequence attributes, which reference a particular line table
2289/// row.
2295
2296/// Insert the new line info sequence \p Seq into the current
2297/// set of already linked line info \p Rows.
2298static void insertLineSequence(std::vector<TrackedRow> &Seq,
2299 std::vector<TrackedRow> &Rows) {
2300 if (Seq.empty())
2301 return;
2302
2303 // Mark the first row in Seq to indicate it is the start of a sequence
2304 // in the output line table.
2305 Seq.front().isStartSeqInOutput = true;
2306
2307 if (!Rows.empty() && Rows.back().Row.Address < Seq.front().Row.Address) {
2308 llvm::append_range(Rows, Seq);
2309 Seq.clear();
2310 return;
2311 }
2312
2313 object::SectionedAddress Front = Seq.front().Row.Address;
2315 Rows, [=](const TrackedRow &O) { return O.Row.Address < Front; });
2316
2317 // FIXME: this only removes the unneeded end_sequence if the
2318 // sequences have been inserted in order. Using a global sort like
2319 // described in generateLineTableForUnit() and delaying the end_sequence
2320 // elimination to emitLineTableForUnit() we can get rid of all of them.
2321 if (InsertPoint != Rows.end() && InsertPoint->Row.Address == Front &&
2322 InsertPoint->Row.EndSequence) {
2323 *InsertPoint = Seq.front();
2324 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2325 } else {
2326 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2327 }
2328
2329 Seq.clear();
2330}
2331
2333 for (auto &V : Die.values())
2334 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2335 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2336 return;
2337 }
2338
2339 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2340}
2341
2342void DWARFLinker::DIECloner::rememberUnitForMacroOffset(CompileUnit &Unit) {
2343 DWARFUnit &OrigUnit = Unit.getOrigUnit();
2344 DWARFDie OrigUnitDie = OrigUnit.getUnitDIE();
2345
2346 if (std::optional<uint64_t> MacroAttr =
2347 dwarf::toSectionOffset(OrigUnitDie.find(dwarf::DW_AT_macros))) {
2348 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2349 return;
2350 }
2351
2352 if (std::optional<uint64_t> MacroAttr =
2353 dwarf::toSectionOffset(OrigUnitDie.find(dwarf::DW_AT_macro_info))) {
2354 UnitMacroMap.insert(std::make_pair(*MacroAttr, &Unit));
2355 return;
2356 }
2357}
2358
2359Error DWARFLinker::DIECloner::generateLineTableForUnit(CompileUnit &Unit) {
2360 if (LLVM_UNLIKELY(Emitter == nullptr))
2361 return Error::success();
2362
2363 // Check whether DW_AT_stmt_list attribute is presented.
2364 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
2365 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
2366 if (!StmtList)
2367 return Error::success();
2368
2369 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2370 if (auto *OutputDIE = Unit.getOutputUnitDIE()) {
2371 uint64_t StmtOffset = Emitter->getLineSectionSize();
2372 dwarf::FormParams FP = Unit.getOrigUnit().getFormParams();
2373 if (StmtOffset > FP.getDwarfMaxOffset())
2374 return createStringError(".debug_line section offset 0x" +
2375 Twine::utohexstr(StmtOffset) + " exceeds the " +
2376 dwarf::FormatString(FP.Format) + " limit");
2377 patchStmtList(*OutputDIE, DIEInteger(StmtOffset));
2378 }
2379
2380 if (const DWARFDebugLine::LineTable *LT =
2381 ObjFile.Dwarf->getLineTableForUnit(&Unit.getOrigUnit())) {
2382
2383 DWARFDebugLine::LineTable LineTable;
2384
2385 // Set Line Table header.
2386 LineTable.Prologue = LT->Prologue;
2387
2388 // Set Line Table Rows.
2389 if (Linker.Options.Update) {
2390 LineTable.Rows = LT->Rows;
2391 // If all the line table contains is a DW_LNE_end_sequence, clear the line
2392 // table rows, it will be inserted again in the DWARFStreamer.
2393 if (LineTable.Rows.size() == 1 && LineTable.Rows[0].EndSequence)
2394 LineTable.Rows.clear();
2395
2396 LineTable.Sequences = LT->Sequences;
2397
2398 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2399 DebugLineStrPool);
2400 } else {
2401 // Create TrackedRow objects for all input rows.
2402 std::vector<TrackedRow> InputRows;
2403 InputRows.reserve(LT->Rows.size());
2404 for (size_t i = 0; i < LT->Rows.size(); i++)
2405 InputRows.emplace_back(TrackedRow{LT->Rows[i], i, false});
2406
2407 // This vector is the output line table (still in TrackedRow form).
2408 std::vector<TrackedRow> OutputRows;
2409 OutputRows.reserve(InputRows.size());
2410
2411 // Current sequence of rows being extracted, before being inserted
2412 // in OutputRows.
2413 std::vector<TrackedRow> Seq;
2414 Seq.reserve(InputRows.size());
2415
2416 const auto &FunctionRanges = Unit.getFunctionRanges();
2417 std::optional<AddressRangeValuePair> CurrRange;
2418
2419 // FIXME: This logic is meant to generate exactly the same output as
2420 // Darwin's classic dsymutil. There is a nicer way to implement this
2421 // by simply putting all the relocated line info in OutputRows and simply
2422 // sorting OutputRows before passing it to emitLineTableForUnit. This
2423 // should be correct as sequences for a function should stay
2424 // together in the sorted output. There are a few corner cases that
2425 // look suspicious though, and that required to implement the logic
2426 // this way. Revisit that once initial validation is finished.
2427
2428 // Iterate over the object file line info and extract the sequences
2429 // that correspond to linked functions.
2430 for (size_t i = 0; i < InputRows.size(); i++) {
2431 TrackedRow TR = InputRows[i];
2432
2433 // Check whether we stepped out of the range. The range is
2434 // half-open, but consider accepting the end address of the range if
2435 // it is marked as end_sequence in the input (because in that
2436 // case, the relocation offset is accurate and that entry won't
2437 // serve as the start of another function).
2438 if (!CurrRange || !CurrRange->Range.contains(TR.Row.Address.Address)) {
2439 // We just stepped out of a known range. Insert an end_sequence
2440 // corresponding to the end of the range.
2441 uint64_t StopAddress =
2442 CurrRange ? CurrRange->Range.end() + CurrRange->Value : -1ULL;
2443 CurrRange =
2444 FunctionRanges.getRangeThatContains(TR.Row.Address.Address);
2445 if (StopAddress != -1ULL && !Seq.empty()) {
2446 // Insert end sequence row with the computed end address, but
2447 // the same line as the previous one.
2448 auto NextLine = Seq.back();
2449 NextLine.Row.Address.Address = StopAddress;
2450 NextLine.Row.EndSequence = 1;
2451 NextLine.Row.PrologueEnd = 0;
2452 NextLine.Row.BasicBlock = 0;
2453 NextLine.Row.EpilogueBegin = 0;
2454 Seq.push_back(NextLine);
2455 insertLineSequence(Seq, OutputRows);
2456 }
2457
2458 if (!CurrRange)
2459 continue;
2460 }
2461
2462 // Ignore empty sequences.
2463 if (TR.Row.EndSequence && Seq.empty())
2464 continue;
2465
2466 // Relocate row address and add it to the current sequence.
2467 TR.Row.Address.Address += CurrRange->Value;
2468 Seq.push_back(TR);
2469
2470 if (TR.Row.EndSequence)
2471 insertLineSequence(Seq, OutputRows);
2472 }
2473
2474 // Recompute isStartSeqInOutput based on the final row ordering.
2475 // A row is a sequence start (will have DW_LNE_set_address emitted) iff:
2476 // 1. It's the first row, OR
2477 // 2. The previous row has EndSequence = 1
2478 // This is necessary because insertLineSequence may merge sequences when
2479 // an EndSequence row is replaced by the start of a new sequence, which
2480 // removes the EndSequence marker and invalidates the original flag.
2481 if (!OutputRows.empty()) {
2482 OutputRows[0].isStartSeqInOutput = true;
2483 for (size_t i = 1; i < OutputRows.size(); ++i)
2484 OutputRows[i].isStartSeqInOutput = OutputRows[i - 1].Row.EndSequence;
2485 }
2486
2487 // Materialize the tracked rows into final DWARFDebugLine::Row objects.
2488 LineTable.Rows.clear();
2489 LineTable.Rows.reserve(OutputRows.size());
2490 for (auto &TR : OutputRows)
2491 LineTable.Rows.push_back(TR.Row);
2492
2493 // Use OutputRowOffsets to store the offsets of each line table row in the
2494 // output .debug_line section.
2495 std::vector<uint64_t> OutputRowOffsets;
2496
2497 // The unit might not have any DW_AT_LLVM_stmt_sequence attributes, so use
2498 // hasStmtSeq to skip the patching logic.
2499 bool hasStmtSeq = Unit.getStmtSeqListAttributes().size() > 0;
2500 Emitter->emitLineTableForUnit(LineTable, Unit, DebugStrPool,
2501 DebugLineStrPool,
2502 hasStmtSeq ? &OutputRowOffsets : nullptr);
2503
2504 if (hasStmtSeq) {
2505 assert(OutputRowOffsets.size() == OutputRows.size() &&
2506 "must have an offset for each row");
2507
2508 // Create a map of stmt sequence offsets to original row indices.
2509 DenseMap<uint64_t, unsigned> SeqOffToOrigRow;
2510 // The DWARF parser's discovery of sequences can be incomplete. To
2511 // ensure all DW_AT_LLVM_stmt_sequence attributes can be patched, we
2512 // build a map from both the parser's results and a manual
2513 // reconstruction.
2514 if (!LT->Rows.empty())
2515 constructSeqOffsettoOrigRowMapping(Unit, *LT, SeqOffToOrigRow);
2516
2517 // Build two maps to handle stmt_sequence patching:
2518 // 1. OrigRowToOutputRow: maps original row indices to output row
2519 // indices (for all rows, not just sequence starts).
2520 // 2. OutputRowToSeqStart: maps each output row index to its sequence
2521 // start's output row index
2522 DenseMap<size_t, size_t> OrigRowToOutputRow;
2523 std::vector<size_t> OutputRowToSeqStart(OutputRows.size());
2524
2525 size_t CurrentSeqStart = 0;
2526 for (size_t i = 0; i < OutputRows.size(); ++i) {
2527 // Track the current sequence start.
2528 if (OutputRows[i].isStartSeqInOutput)
2529 CurrentSeqStart = i;
2530 OutputRowToSeqStart[i] = CurrentSeqStart;
2531
2532 // Map original row index to output row index.
2533 OrigRowToOutputRow[OutputRows[i].OriginalRowIndex] = i;
2534 }
2535
2536 // Patch DW_AT_LLVM_stmt_sequence attributes in the compile unit DIE
2537 // with the correct offset into the .debug_line section.
2538 for (const auto &StmtSeq : Unit.getStmtSeqListAttributes()) {
2539 uint64_t OrigStmtSeq = StmtSeq.get();
2540 // 1. Get the original row index from the stmt list offset.
2541 auto OrigRowIter = SeqOffToOrigRow.find(OrigStmtSeq);
2542 const uint64_t InvalidOffset =
2543 Unit.getOrigUnit().getFormParams().getDwarfMaxOffset();
2544 // Check whether we have an output sequence for the StmtSeq offset.
2545 // Some sequences are discarded by the DWARFLinker if they are invalid
2546 // (empty).
2547 if (OrigRowIter == SeqOffToOrigRow.end()) {
2548 StmtSeq.set(InvalidOffset);
2549 continue;
2550 }
2551 size_t OrigRowIndex = OrigRowIter->second;
2552
2553 // 2. Find the output row for this original row.
2554 auto OutputRowIter = OrigRowToOutputRow.find(OrigRowIndex);
2555 if (OutputRowIter == OrigRowToOutputRow.end()) {
2556 // Row was dropped during linking.
2557 StmtSeq.set(InvalidOffset);
2558 continue;
2559 }
2560 size_t OutputRowIdx = OutputRowIter->second;
2561
2562 // 3. Find the sequence start for this output row.
2563 // If the original row was a sequence start but got merged into
2564 // another sequence, this finds the correct sequence start.
2565 size_t SeqStartIdx = OutputRowToSeqStart[OutputRowIdx];
2566
2567 // 4. Get the offset of the sequence start in the output .debug_line
2568 // section. This offset points to the DW_LNE_set_address opcode.
2569 assert(SeqStartIdx < OutputRowOffsets.size() &&
2570 "Sequence start index out of bounds");
2571 uint64_t NewStmtSeqOffset = OutputRowOffsets[SeqStartIdx];
2572
2573 // 5. Patch the stmt_sequence attribute with the new offset.
2574 StmtSeq.set(NewStmtSeqOffset);
2575 }
2576 }
2577 }
2578
2579 } else
2580 Linker.reportWarning("Cann't load line table.", ObjFile);
2581
2582 return Error::success();
2583}
2584
2585void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2586 for (AccelTableKind AccelTableKind : Options.AccelTables) {
2587 switch (AccelTableKind) {
2588 case AccelTableKind::Apple: {
2589 // Add namespaces.
2590 for (const auto &Namespace : Unit.getNamespaces())
2591 AppleNamespaces.addName(Namespace.Name, Namespace.Die->getOffset() +
2592 Unit.getStartOffset());
2593 // Add names.
2594 for (const auto &Pubname : Unit.getPubnames())
2595 AppleNames.addName(Pubname.Name,
2596 Pubname.Die->getOffset() + Unit.getStartOffset());
2597 // Add types.
2598 for (const auto &Pubtype : Unit.getPubtypes())
2599 AppleTypes.addName(
2600 Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
2601 Pubtype.Die->getTag(),
2602 Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
2603 : 0,
2604 Pubtype.QualifiedNameHash);
2605 // Add ObjC names.
2606 for (const auto &ObjC : Unit.getObjC())
2607 AppleObjc.addName(ObjC.Name,
2608 ObjC.Die->getOffset() + Unit.getStartOffset());
2609 } break;
2610 case AccelTableKind::Pub: {
2611 TheDwarfEmitter->emitPubNamesForUnit(Unit);
2612 TheDwarfEmitter->emitPubTypesForUnit(Unit);
2613 } break;
2615 for (const auto &Namespace : Unit.getNamespaces())
2616 DebugNames.addName(
2617 Namespace.Name, Namespace.Die->getOffset(),
2619 Namespace.Die->getTag(), Unit.getUniqueID(),
2620 Unit.getTag() == dwarf::DW_TAG_type_unit);
2621 for (const auto &Pubname : Unit.getPubnames())
2622 DebugNames.addName(
2623 Pubname.Name, Pubname.Die->getOffset(),
2625 Pubname.Die->getTag(), Unit.getUniqueID(),
2626 Unit.getTag() == dwarf::DW_TAG_type_unit);
2627 for (const auto &Pubtype : Unit.getPubtypes())
2628 DebugNames.addName(
2629 Pubtype.Name, Pubtype.Die->getOffset(),
2631 Pubtype.Die->getTag(), Unit.getUniqueID(),
2632 Unit.getTag() == dwarf::DW_TAG_type_unit);
2633 } break;
2634 }
2635 }
2636}
2637
2638/// Read the frame info stored in the object, and emit the
2639/// patched frame descriptions for the resulting file.
2640///
2641/// This is actually pretty easy as the data of the CIEs and FDEs can
2642/// be considered as black boxes and moved as is. The only thing to do
2643/// is to patch the addresses in the headers.
2644void DWARFLinker::patchFrameInfoForObject(LinkContext &Context) {
2645 DWARFContext &OrigDwarf = *Context.File.Dwarf;
2646 unsigned SrcAddrSize = OrigDwarf.getDWARFObj().getAddressSize();
2647
2648 StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
2649 if (FrameData.empty())
2650 return;
2651
2652 RangesTy AllUnitsRanges;
2653 for (std::unique_ptr<CompileUnit> &Unit : Context.CompileUnits) {
2654 for (auto CurRange : Unit->getFunctionRanges())
2655 AllUnitsRanges.insert(CurRange.Range, CurRange.Value);
2656 }
2657
2658 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2659 uint64_t InputOffset = 0;
2660
2661 // Store the data of the CIEs defined in this object, keyed by their
2662 // offsets.
2663 DenseMap<uint64_t, StringRef> LocalCIES;
2664
2665 while (Data.isValidOffset(InputOffset)) {
2666 uint64_t EntryOffset = InputOffset;
2667 uint32_t InitialLength = Data.getU32(&InputOffset);
2668 if (InitialLength == 0xFFFFFFFF)
2669 return reportWarning("Dwarf64 bits no supported", Context.File);
2670
2671 uint32_t CIEId = Data.getU32(&InputOffset);
2672 if (CIEId == 0xFFFFFFFF) {
2673 // This is a CIE, store it.
2674 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2675 LocalCIES[EntryOffset] = CIEData;
2676 // The -4 is to account for the CIEId we just read.
2677 InputOffset += InitialLength - 4;
2678 continue;
2679 }
2680
2681 uint64_t Loc = Data.getUnsigned(&InputOffset, SrcAddrSize);
2682
2683 // Some compilers seem to emit frame info that doesn't start at
2684 // the function entry point, thus we can't just lookup the address
2685 // in the debug map. Use the AddressInfo's range map to see if the FDE
2686 // describes something that we can relocate.
2687 std::optional<AddressRangeValuePair> Range =
2688 AllUnitsRanges.getRangeThatContains(Loc);
2689 if (!Range) {
2690 // The +4 is to account for the size of the InitialLength field itself.
2691 InputOffset = EntryOffset + InitialLength + 4;
2692 continue;
2693 }
2694
2695 // This is an FDE, and we have a mapping.
2696 // Have we already emitted a corresponding CIE?
2697 StringRef CIEData = LocalCIES[CIEId];
2698 if (CIEData.empty())
2699 return reportWarning("Inconsistent debug_frame content. Dropping.",
2700 Context.File);
2701
2702 // Look if we already emitted a CIE that corresponds to the
2703 // referenced one (the CIE data is the key of that lookup).
2704 auto IteratorInserted = EmittedCIEs.insert(
2705 std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
2706 // If there is no CIE yet for this ID, emit it.
2707 if (IteratorInserted.second) {
2708 LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
2709 IteratorInserted.first->getValue() = LastCIEOffset;
2710 TheDwarfEmitter->emitCIE(CIEData);
2711 }
2712
2713 // Emit the FDE with updated address and CIE pointer.
2714 // (4 + AddrSize) is the size of the CIEId + initial_location
2715 // fields that will get reconstructed by emitFDE().
2716 unsigned FDERemainingBytes = InitialLength - (4 + SrcAddrSize);
2717 TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), SrcAddrSize,
2718 Loc + Range->Value,
2719 FrameData.substr(InputOffset, FDERemainingBytes));
2720 InputOffset += FDERemainingBytes;
2721 }
2722}
2723
2724uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
2725 CompileUnit &U,
2726 const DWARFFile &File,
2727 int ChildRecurseDepth) {
2728 const char *Name = nullptr;
2729 DWARFUnit *OrigUnit = &U.getOrigUnit();
2730 CompileUnit *CU = &U;
2731 std::optional<DWARFFormValue> Ref;
2732
2733 while (true) {
2734 if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
2735 Name = CurrentName;
2736
2737 if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
2738 !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
2739 break;
2740
2741 if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
2742 break;
2743
2744 CompileUnit *RefCU;
2745 if (auto RefDIE =
2746 Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
2747 CU = RefCU;
2748 OrigUnit = &RefCU->getOrigUnit();
2749 DIE = RefDIE;
2750 }
2751 }
2752
2753 unsigned Idx = OrigUnit->getDIEIndex(DIE);
2754 if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
2755 Name = "(anonymous namespace)";
2756
2757 if (CU->getInfo(Idx).ParentIdx == 0 ||
2758 // FIXME: dsymutil-classic compatibility. Ignore modules.
2759 CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
2760 dwarf::DW_TAG_module)
2761 return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
2762
2763 DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
2764 return djbHash(
2765 (Name ? Name : ""),
2766 djbHash((Name ? "::" : ""),
2767 hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
2768}
2769
2770static uint64_t getDwoId(const DWARFDie &CUDie) {
2771 auto DwoId = dwarf::toUnsigned(
2772 CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2773 if (DwoId)
2774 return *DwoId;
2775 return 0;
2776}
2777
2778static std::string
2780 const DWARFLinkerBase::ObjectPrefixMapTy &ObjectPrefixMap) {
2781 if (ObjectPrefixMap.empty())
2782 return Path.str();
2783
2784 SmallString<256> p = Path;
2785 for (const auto &Entry : ObjectPrefixMap)
2786 if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
2787 break;
2788 return p.str().str();
2789}
2790
2791static std::string
2793 const DWARFLinkerBase::ObjectPrefixMapTy *ObjectPrefixMap) {
2794 std::string PCMFile = dwarf::toString(
2795 CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2796
2797 if (PCMFile.empty())
2798 return PCMFile;
2799
2800 if (ObjectPrefixMap)
2801 PCMFile = remapPath(PCMFile, *ObjectPrefixMap);
2802
2803 return PCMFile;
2804}
2805
2806std::pair<bool, bool> DWARFLinker::isClangModuleRef(const DWARFDie &CUDie,
2807 std::string &PCMFile,
2808 LinkContext &Context,
2809 unsigned Indent,
2810 bool Quiet) {
2811 if (PCMFile.empty())
2812 return std::make_pair(false, false);
2813
2814 // Clang module DWARF skeleton CUs abuse this for the path to the module.
2815 uint64_t DwoId = getDwoId(CUDie);
2816
2817 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2818 if (Name.empty()) {
2819 if (!Quiet)
2820 reportWarning("Anonymous module skeleton CU for " + PCMFile,
2821 Context.File);
2822 return std::make_pair(true, true);
2823 }
2824
2825 if (!Quiet && Options.Verbose) {
2826 outs().indent(Indent);
2827 outs() << "Found clang module reference " << PCMFile;
2828 }
2829
2830 auto Cached = ClangModules.find(PCMFile);
2831 if (Cached != ClangModules.end()) {
2832 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2833 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2834 // ASTFileSignatures will change randomly when a module is rebuilt.
2835 if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2836 reportWarning(Twine("hash mismatch: this object file was built against a "
2837 "different version of the module ") +
2838 PCMFile,
2839 Context.File);
2840 if (!Quiet && Options.Verbose)
2841 outs() << " [cached].\n";
2842 return std::make_pair(true, true);
2843 }
2844
2845 return std::make_pair(true, false);
2846}
2847
2848bool DWARFLinker::registerModuleReference(const DWARFDie &CUDie,
2849 LinkContext &Context,
2850 ObjFileLoaderTy Loader,
2851 CompileUnitHandlerTy OnCUDieLoaded,
2852 unsigned Indent) {
2853 std::string PCMFile = getPCMFile(CUDie, Options.ObjectPrefixMap);
2854 std::pair<bool, bool> IsClangModuleRef =
2855 isClangModuleRef(CUDie, PCMFile, Context, Indent, false);
2856
2857 if (!IsClangModuleRef.first)
2858 return false;
2859
2860 if (IsClangModuleRef.second)
2861 return true;
2862
2863 if (Options.Verbose)
2864 outs() << " ...\n";
2865
2866 // Cyclic dependencies are disallowed by Clang, but we still
2867 // shouldn't run into an infinite loop, so mark it as processed now.
2868 ClangModules.insert({PCMFile, getDwoId(CUDie)});
2869
2870 if (Error E = loadClangModule(Loader, CUDie, PCMFile, Context, OnCUDieLoaded,
2871 Indent + 2)) {
2872 consumeError(std::move(E));
2873 return false;
2874 }
2875 return true;
2876}
2877
2878Error DWARFLinker::loadClangModule(
2879 ObjFileLoaderTy Loader, const DWARFDie &CUDie, const std::string &PCMFile,
2880 LinkContext &Context, CompileUnitHandlerTy OnCUDieLoaded, unsigned Indent) {
2881
2882 uint64_t DwoId = getDwoId(CUDie);
2883 std::string ModuleName = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2884
2885 /// Using a SmallString<0> because loadClangModule() is recursive.
2886 SmallString<0> Path(Options.PrependPath);
2887 if (sys::path::is_relative(PCMFile))
2888 resolveRelativeObjectPath(Path, CUDie);
2889 sys::path::append(Path, PCMFile);
2890 // Don't use the cached binary holder because we have no thread-safety
2891 // guarantee and the lifetime is limited.
2892
2893 if (Loader == nullptr) {
2894 reportError("Could not load clang module: loader is not specified.\n",
2895 Context.File);
2896 return Error::success();
2897 }
2898
2899 auto ErrOrObj = Loader(Context.File.FileName, Path);
2900 if (!ErrOrObj)
2901 return Error::success();
2902
2903 std::unique_ptr<CompileUnit> Unit;
2904 for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
2905 OnCUDieLoaded(*CU);
2906 // Recursively get all modules imported by this one.
2907 auto ChildCUDie = CU->getUnitDIE();
2908 if (!ChildCUDie)
2909 continue;
2910 if (!registerModuleReference(ChildCUDie, Context, Loader, OnCUDieLoaded,
2911 Indent)) {
2912 if (Unit) {
2913 std::string Err =
2914 (PCMFile +
2915 ": Clang modules are expected to have exactly 1 compile unit.\n");
2916 reportError(Err, Context.File);
2918 }
2919 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2920 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2921 // ASTFileSignatures will change randomly when a module is rebuilt.
2922 uint64_t PCMDwoId = getDwoId(ChildCUDie);
2923 if (PCMDwoId != DwoId) {
2924 if (Options.Verbose)
2925 reportWarning(
2926 Twine("hash mismatch: this object file was built against a "
2927 "different version of the module ") +
2928 PCMFile,
2929 Context.File);
2930 // Update the cache entry with the DwoId of the module loaded from disk.
2931 ClangModules[PCMFile] = PCMDwoId;
2932 }
2933
2934 // Add this module.
2935 Unit = std::make_unique<CompileUnit>(*CU, UniqueUnitID++, !Options.NoODR,
2936 ModuleName);
2937 }
2938 }
2939
2940 if (Unit)
2941 Context.ModuleUnits.emplace_back(RefModuleUnit{*ErrOrObj, std::move(Unit)});
2942
2943 return Error::success();
2944}
2945
2946Expected<uint64_t> DWARFLinker::DIECloner::cloneAllCompileUnits(
2947 DWARFContext &DwarfContext, const DWARFFile &File, bool IsLittleEndian) {
2948 uint64_t OutputDebugInfoSize =
2949 (Emitter == nullptr) ? 0 : Emitter->getDebugInfoSectionSize();
2950 const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
2951
2952 for (auto &CurrentUnit : CompileUnits) {
2953 const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2954 const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
2955 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2956 CurrentUnit->setStartOffset(OutputDebugInfoSize);
2957 if (!InputDIE) {
2958 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2959 continue;
2960 }
2961 if (CurrentUnit->getInfo(0).Keep) {
2962 // Clone the InputDIE into your Unit DIE in our compile unit since it
2963 // already has a DIE inside of it.
2964 CurrentUnit->createOutputDIE();
2965 rememberUnitForMacroOffset(*CurrentUnit);
2966 cloneDIE(InputDIE, File, *CurrentUnit, 0 /* PC offset */, UnitHeaderSize,
2967 0, IsLittleEndian, CurrentUnit->getOutputUnitDIE());
2968 }
2969
2970 OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2971
2972 if (Emitter != nullptr) {
2973
2974 if (Error E = generateLineTableForUnit(*CurrentUnit))
2975 return E;
2976
2977 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2978
2979 if (LLVM_UNLIKELY(Linker.Options.Update))
2980 continue;
2981
2982 if (Error E = Linker.generateUnitRanges(*CurrentUnit, File, AddrPool))
2983 return E;
2984
2985 auto ProcessExpr = [&](SmallVectorImpl<uint8_t> &SrcBytes,
2986 SmallVectorImpl<uint8_t> &OutBytes,
2987 int64_t RelocAdjustment) {
2988 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2989 DataExtractor Data(SrcBytes, IsLittleEndian,
2990 OrigUnit.getAddressByteSize());
2991 cloneExpression(Data,
2992 DWARFExpression(Data, OrigUnit.getAddressByteSize(),
2993 OrigUnit.getFormParams().Format),
2994 File, *CurrentUnit, OutBytes, RelocAdjustment,
2995 IsLittleEndian);
2996 };
2997 if (Error E = generateUnitLocations(*CurrentUnit, File, ProcessExpr))
2998 return E;
2999 if (Error E = emitDebugAddrSection(*CurrentUnit, DwarfVersion))
3000 return E;
3001 }
3002 AddrPool.clear();
3003 }
3004
3005 if (Emitter != nullptr) {
3006 assert(Emitter);
3007 // Emit macro tables.
3008 Emitter->emitMacroTables(File.Dwarf.get(), UnitMacroMap, DebugStrPool);
3009
3010 // Emit all the compile unit's debug information.
3011 for (auto &CurrentUnit : CompileUnits) {
3012 CurrentUnit->fixupForwardReferences();
3013
3014 if (!CurrentUnit->getOutputUnitDIE())
3015 continue;
3016
3017 unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
3018
3019 assert(Emitter->getDebugInfoSectionSize() ==
3020 CurrentUnit->getStartOffset());
3021 Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
3022 Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
3023 assert(Emitter->getDebugInfoSectionSize() ==
3024 CurrentUnit->computeNextUnitOffset(DwarfVersion));
3025 }
3026 }
3027
3028 return OutputDebugInfoSize - StartOutputDebugInfoSize;
3029}
3030
3031void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
3032 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
3034 TheDwarfEmitter->emitSectionContents(
3035 Dwarf.getDWARFObj().getRangesSection().Data,
3037 TheDwarfEmitter->emitSectionContents(
3038 Dwarf.getDWARFObj().getFrameSection().Data, DebugSectionKind::DebugFrame);
3039 TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
3041 TheDwarfEmitter->emitSectionContents(
3042 Dwarf.getDWARFObj().getAddrSection().Data, DebugSectionKind::DebugAddr);
3043 TheDwarfEmitter->emitSectionContents(
3044 Dwarf.getDWARFObj().getRnglistsSection().Data,
3046 TheDwarfEmitter->emitSectionContents(
3047 Dwarf.getDWARFObj().getLoclistsSection().Data,
3049}
3050
3052 CompileUnitHandlerTy OnCUDieLoaded) {
3053 ObjectContexts.emplace_back(LinkContext(File));
3054
3055 if (ObjectContexts.back().File.Dwarf) {
3056 for (const std::unique_ptr<DWARFUnit> &CU :
3057 ObjectContexts.back().File.Dwarf->compile_units()) {
3058 DWARFDie CUDie = CU->getUnitDIE();
3059
3060 if (!CUDie)
3061 continue;
3062
3063 OnCUDieLoaded(*CU);
3064
3065 if (!LLVM_UNLIKELY(Options.Update))
3066 registerModuleReference(CUDie, ObjectContexts.back(), Loader,
3067 OnCUDieLoaded);
3068 }
3069 }
3070}
3071
3073 assert((Options.TargetDWARFVersion != 0) &&
3074 "TargetDWARFVersion should be set");
3075
3076 // First populate the data structure we need for each iteration of the
3077 // parallel loop.
3078 unsigned NumObjects = ObjectContexts.size();
3079
3080 // This Dwarf string pool which is used for emission. It must be used
3081 // serially as the order of calling getStringOffset matters for
3082 // reproducibility.
3083 OffsetsStringPool DebugStrPool(true);
3084 OffsetsStringPool DebugLineStrPool(false);
3085 DebugDieValuePool StringOffsetPool;
3086
3087 // ODR Contexts for the optimize.
3088 DeclContextTree ODRContexts;
3089
3090 for (LinkContext &OptContext : ObjectContexts) {
3091 if (Options.Verbose)
3092 outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
3093
3094 if (!OptContext.File.Dwarf)
3095 continue;
3096
3097 if (Options.VerifyInputDWARF)
3098 verifyInput(OptContext.File);
3099
3100 // Look for relocations that correspond to address map entries.
3101
3102 // there was findvalidrelocations previously ... probably we need to gather
3103 // info here
3104 if (LLVM_LIKELY(!Options.Update) &&
3105 !OptContext.File.Addresses->hasValidRelocs()) {
3106 if (Options.Verbose)
3107 outs() << "No valid relocations found. Skipping.\n";
3108
3109 // Set "Skip" flag as a signal to other loops that we should not
3110 // process this iteration.
3111 OptContext.Skip = true;
3112 continue;
3113 }
3114
3115 // Setup access to the debug info.
3116 if (!OptContext.File.Dwarf)
3117 continue;
3118
3119 // Check whether type units are presented.
3120 if (!OptContext.File.Dwarf->types_section_units().empty()) {
3121 reportWarning("type units are not currently supported: file will "
3122 "be skipped",
3123 OptContext.File);
3124 OptContext.Skip = true;
3125 continue;
3126 }
3127
3128 // Clone all the clang modules with requires extracting the DIE units. We
3129 // don't need the full debug info until the Analyze phase.
3130 OptContext.CompileUnits.reserve(
3131 OptContext.File.Dwarf->getNumCompileUnits());
3132 for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
3133 auto CUDie = CU->getUnitDIE(/*ExtractUnitDIEOnly=*/true);
3134 if (Options.Verbose) {
3135 outs() << "Input compilation unit:";
3136 DIDumpOptions DumpOpts;
3137 DumpOpts.ChildRecurseDepth = 0;
3138 DumpOpts.Verbose = Options.Verbose;
3139 CUDie.dump(outs(), 0, DumpOpts);
3140 }
3141 }
3142
3143 for (auto &CU : OptContext.ModuleUnits) {
3144 if (Error Err = cloneModuleUnit(OptContext, CU, ODRContexts, DebugStrPool,
3145 DebugLineStrPool, StringOffsetPool))
3146 reportWarning(toString(std::move(Err)), CU.File);
3147 }
3148 }
3149
3150 // At this point we know how much data we have emitted. We use this value to
3151 // compare canonical DIE offsets in analyzeContextInfo to see if a definition
3152 // is already emitted, without being affected by canonical die offsets set
3153 // later. This prevents undeterminism when analyze and clone execute
3154 // concurrently, as clone set the canonical DIE offset and analyze reads it.
3155 const uint64_t ModulesEndOffset =
3156 (TheDwarfEmitter == nullptr) ? 0
3157 : TheDwarfEmitter->getDebugInfoSectionSize();
3158
3159 // These variables manage the list of processed object files.
3160 // The mutex and condition variable are to ensure that this is thread safe.
3161 std::mutex ProcessedFilesMutex;
3162 std::condition_variable ProcessedFilesConditionVariable;
3163 BitVector ProcessedFiles(NumObjects, false);
3164
3165 // Analyzing the context info is particularly expensive so it is executed in
3166 // parallel with emitting the previous compile unit.
3167 auto AnalyzeLambda = [&](size_t I) {
3168 auto &Context = ObjectContexts[I];
3169
3170 if (Context.Skip || !Context.File.Dwarf)
3171 return;
3172
3173 for (const auto &CU : Context.File.Dwarf->compile_units()) {
3174 // Previously we only extracted the unit DIEs. We need the full debug info
3175 // now.
3176 auto CUDie = CU->getUnitDIE(/*ExtractUnitDIEOnly=*/false);
3177 std::string PCMFile = getPCMFile(CUDie, Options.ObjectPrefixMap);
3178
3179 if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
3180 !isClangModuleRef(CUDie, PCMFile, Context, 0, true).first) {
3181 Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
3182 *CU, UniqueUnitID++, !Options.NoODR && !Options.Update, ""));
3183 }
3184 }
3185
3186 // Now build the DIE parent links that we will use during the next phase.
3187 for (auto &CurrentUnit : Context.CompileUnits) {
3188 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
3189 if (!CUDie)
3190 continue;
3191 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
3192 *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
3193 ModulesEndOffset, Options.ParseableSwiftInterfaces,
3194 [&](const Twine &Warning, const DWARFDie &DIE) {
3195 reportWarning(Warning, Context.File, &DIE);
3196 });
3197 }
3198 };
3199
3200 // For each object file map how many bytes were emitted.
3201 StringMap<DebugInfoSize> SizeByObject;
3202
3203 // And then the remaining work in serial again.
3204 // Note, although this loop runs in serial, it can run in parallel with
3205 // the analyzeContextInfo loop so long as we process files with indices >=
3206 // than those processed by analyzeContextInfo.
3207 auto CloneLambda = [&](size_t I, llvm::Error &CE) {
3208 auto &OptContext = ObjectContexts[I];
3209 if (OptContext.Skip || !OptContext.File.Dwarf)
3210 return;
3211
3212 // Then mark all the DIEs that need to be present in the generated output
3213 // and collect some information about them.
3214 // Note that this loop can not be merged with the previous one because
3215 // cross-cu references require the ParentIdx to be setup for every CU in
3216 // the object file before calling this.
3217 if (LLVM_UNLIKELY(Options.Update)) {
3218 for (auto &CurrentUnit : OptContext.CompileUnits)
3219 CurrentUnit->markEverythingAsKept();
3220 copyInvariantDebugSection(*OptContext.File.Dwarf);
3221 } else {
3222 for (auto &CurrentUnit : OptContext.CompileUnits) {
3223 lookForDIEsToKeep(*OptContext.File.Addresses, OptContext.CompileUnits,
3224 CurrentUnit->getOrigUnit().getUnitDIE(),
3225 OptContext.File, *CurrentUnit, 0);
3226#ifndef NDEBUG
3227 verifyKeepChain(*CurrentUnit);
3228#endif
3229 }
3230 }
3231
3232 // The calls to applyValidRelocs inside cloneDIE will walk the reloc
3233 // array again (in the same way findValidRelocsInDebugInfo() did). We
3234 // need to reset the NextValidReloc index to the beginning.
3235 if (OptContext.File.Addresses->hasValidRelocs() ||
3236 LLVM_UNLIKELY(Options.Update)) {
3237 SizeByObject[OptContext.File.FileName].Input =
3238 getDebugInfoSize(*OptContext.File.Dwarf);
3239 Expected<uint64_t> SizeOrErr =
3240 DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
3241 OptContext.CompileUnits, Options.Update, DebugStrPool,
3242 DebugLineStrPool, StringOffsetPool)
3243 .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
3244 OptContext.File.Dwarf->isLittleEndian());
3245 if (!SizeOrErr) {
3246 CE = SizeOrErr.takeError();
3247 return;
3248 }
3249 SizeByObject[OptContext.File.FileName].Output = *SizeOrErr;
3250 }
3251 if ((TheDwarfEmitter != nullptr) && !OptContext.CompileUnits.empty() &&
3252 LLVM_LIKELY(!Options.Update))
3253 patchFrameInfoForObject(OptContext);
3254
3255 // Clean-up before starting working on the next object.
3256 cleanupAuxiliarryData(OptContext);
3257 };
3258
3259 auto EmitLambda = [&]() {
3260 // Emit everything that's global.
3261 if (TheDwarfEmitter != nullptr) {
3262 TheDwarfEmitter->emitAbbrevs(Abbreviations, Options.TargetDWARFVersion);
3263 TheDwarfEmitter->emitStrings(DebugStrPool);
3264 TheDwarfEmitter->emitStringOffsets(StringOffsetPool.getValues(),
3265 Options.TargetDWARFVersion);
3266 TheDwarfEmitter->emitLineStrings(DebugLineStrPool);
3267 for (AccelTableKind TableKind : Options.AccelTables) {
3268 switch (TableKind) {
3270 TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
3271 TheDwarfEmitter->emitAppleNames(AppleNames);
3272 TheDwarfEmitter->emitAppleTypes(AppleTypes);
3273 TheDwarfEmitter->emitAppleObjc(AppleObjc);
3274 break;
3276 // Already emitted by emitAcceleratorEntriesForUnit.
3277 // Already emitted by emitAcceleratorEntriesForUnit.
3278 break;
3280 TheDwarfEmitter->emitDebugNames(DebugNames);
3281 break;
3282 }
3283 }
3284 }
3285 };
3286
3287 auto AnalyzeAll = [&]() {
3288 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
3289 AnalyzeLambda(I);
3290
3291 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3292 ProcessedFiles.set(I);
3293 ProcessedFilesConditionVariable.notify_one();
3294 }
3295 };
3296
3297 auto CloneAll = [&](llvm::Error &CE) {
3298 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
3299 {
3300 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
3301 if (!ProcessedFiles[I]) {
3302 ProcessedFilesConditionVariable.wait(
3303 LockGuard, [&]() { return ProcessedFiles[I]; });
3304 }
3305 }
3306
3307 CloneLambda(I, CE);
3308 if (CE)
3309 return;
3310 }
3311 EmitLambda();
3312 };
3313
3314 Error CE = Error::success();
3315
3316 // To limit memory usage in the single threaded case, analyze and clone are
3317 // run sequentially so the OptContext is freed after processing each object
3318 // in endDebugObject.
3319 if (Options.Threads == 1) {
3320 for (unsigned I = 0, E = NumObjects; I != E; ++I) {
3321 AnalyzeLambda(I);
3322 CloneLambda(I, CE);
3323 if (CE)
3324 break;
3325 }
3326 if (!CE)
3327 EmitLambda();
3328 } else {
3330 Pool.async(AnalyzeAll);
3331 Pool.async(CloneAll, std::reference_wrapper<Error>(CE));
3332 Pool.wait();
3333 }
3334
3335 if (CE)
3336 return CE;
3337
3338 if (Options.Statistics) {
3339 // Create a vector sorted in descending order by output size.
3340 std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
3341 for (auto &E : SizeByObject)
3342 Sorted.emplace_back(E.first(), E.second);
3343 llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
3344 return LHS.second.Output > RHS.second.Output;
3345 });
3346
3347 auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
3348 const float Difference = Output - Input;
3349 const float Sum = Input + Output;
3350 if (Sum == 0)
3351 return 0;
3352 return (Difference / (Sum / 2));
3353 };
3354
3355 int64_t InputTotal = 0;
3356 int64_t OutputTotal = 0;
3357 const char *FormatStr = "{0,-45} {1,10}b {2,10}b {3,8:P}\n";
3358
3359 // Print header.
3360 outs() << ".debug_info section size (in bytes)\n";
3361 outs() << "----------------------------------------------------------------"
3362 "---------------\n";
3363 outs() << "Filename Object "
3364 " dSYM Change\n";
3365 outs() << "----------------------------------------------------------------"
3366 "---------------\n";
3367
3368 // Print body.
3369 for (auto &E : Sorted) {
3370 InputTotal += E.second.Input;
3371 OutputTotal += E.second.Output;
3372 llvm::outs() << formatv(
3373 FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
3374 E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
3375 }
3376 // Print total and footer.
3377 outs() << "----------------------------------------------------------------"
3378 "---------------\n";
3379 llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
3380 ComputePercentange(InputTotal, OutputTotal));
3381 outs() << "----------------------------------------------------------------"
3382 "---------------\n\n";
3383 }
3384
3385 return Error::success();
3386}
3387
3388Error DWARFLinker::cloneModuleUnit(LinkContext &Context, RefModuleUnit &Unit,
3389 DeclContextTree &ODRContexts,
3390 OffsetsStringPool &DebugStrPool,
3391 OffsetsStringPool &DebugLineStrPool,
3392 DebugDieValuePool &StringOffsetPool,
3393 unsigned Indent) {
3394 assert(Unit.Unit.get() != nullptr);
3395
3396 if (!Unit.Unit->getOrigUnit().getUnitDIE().hasChildren())
3397 return Error::success();
3398
3399 if (Options.Verbose) {
3400 outs().indent(Indent);
3401 outs() << "cloning .debug_info from " << Unit.File.FileName << "\n";
3402 }
3403
3404 // Analyze context for the module.
3405 analyzeContextInfo(Unit.Unit->getOrigUnit().getUnitDIE(), 0, *(Unit.Unit),
3406 &ODRContexts.getRoot(), ODRContexts, 0,
3407 Options.ParseableSwiftInterfaces,
3408 [&](const Twine &Warning, const DWARFDie &DIE) {
3409 reportWarning(Warning, Context.File, &DIE);
3410 });
3411 // Keep everything.
3412 Unit.Unit->markEverythingAsKept();
3413
3414 // Clone unit.
3415 UnitListTy CompileUnits;
3416 CompileUnits.emplace_back(std::move(Unit.Unit));
3417 assert(TheDwarfEmitter);
3418 Expected<uint64_t> SizeOrErr =
3419 DIECloner(*this, TheDwarfEmitter, Unit.File, DIEAlloc, CompileUnits,
3420 Options.Update, DebugStrPool, DebugLineStrPool,
3421 StringOffsetPool)
3422 .cloneAllCompileUnits(*Unit.File.Dwarf, Unit.File,
3423 Unit.File.Dwarf->isLittleEndian());
3424 if (!SizeOrErr)
3425 return SizeOrErr.takeError();
3426 return Error::success();
3427}
3428
3429void DWARFLinker::verifyInput(const DWARFFile &File) {
3430 assert(File.Dwarf);
3431
3432 std::string Buffer;
3433 raw_string_ostream OS(Buffer);
3434 DIDumpOptions DumpOpts;
3435 if (!File.Dwarf->verify(OS, DumpOpts.noImplicitRecursion())) {
3436 if (Options.InputVerificationHandler)
3437 Options.InputVerificationHandler(File, OS.str());
3438 }
3439}
3440
3441} // namespace llvm
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static uint32_t hashFullyQualifiedName(CompileUnit &InputCU, DWARFDie &InputDIE, int ChildRecurseDepth=0)
This file implements the BitVector class.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_UNLIKELY(EXPR)
Definition Compiler.h:336
#define LLVM_LIKELY(EXPR)
Definition Compiler.h:335
dxil DXContainer Global Emitter
Provides ErrorOr<T> smart pointer.
static LVOptions Options
Definition LVOptions.cpp:25
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
if(PassOpts->AAPipeline)
This file contains some templates that are useful if you are working with the STL at all.
This file contains some functions that are useful when dealing with strings.
Value * RHS
Value * LHS
The Input class is used to parse a yaml document into in-memory structs and vectors.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > drop_while(PredicateT Pred) const
Return a copy of *this with the first N elements satisfying the given predicate removed.
Definition ArrayRef.h:208
const T & front() const
front - Get the first element.
Definition ArrayRef.h:145
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
Definition ArrayRef.h:157
BitVector & set()
Definition BitVector.h:370
void setChildrenFlag(bool hasChild)
Definition DIE.h:105
An integer value DIE.
Definition DIE.h:169
value_range values()
Definition DIE.h:816
value_iterator addValue(BumpPtrAllocator &Alloc, const DIEValue &V)
Definition DIE.h:749
A structured debug information entry.
Definition DIE.h:828
unsigned getAbbrevNumber() const
Definition DIE.h:863
DIE & addChild(DIE *Child)
Add a child to the DIE.
Definition DIE.h:944
LLVM_ABI DIEAbbrev generateAbbrev() const
Generate the abbreviation for this DIE.
Definition DIE.cpp:174
void setSize(unsigned S)
Definition DIE.h:941
static DIE * get(BumpPtrAllocator &Alloc, dwarf::Tag Tag)
Definition DIE.h:858
void setAbbrevNumber(unsigned I)
Set the abbreviation number for this DIE.
Definition DIE.h:900
unsigned getOffset() const
Get the compile/type unit relative offset of this DIE.
Definition DIE.h:866
void setOffset(unsigned O)
Definition DIE.h:940
dwarf::Tag getTag() const
Definition DIE.h:864
static LLVM_ABI std::optional< uint64_t > getDefiningParentDieOffset(const DIE &Die)
If Die has a non-null parent and the parent is not a declaration, return its offset.
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Utility class that carries the DWARF compile/type unit and the debug info entry in an object.
Definition DWARFDie.h:43
uint64_t getOffset() const
Get the absolute offset into the debug info or types section.
Definition DWARFDie.h:68
iterator_range< iterator > children() const
Definition DWARFDie.h:406
LLVM_ABI std::optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition DWARFDie.cpp:317
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
Get the abbreviation declaration for this DIE.
Definition DWARFDie.h:60
dwarf::Tag getTag() const
Definition DWARFDie.h:73
LLVM_ABI std::optional< unsigned > getSubCode() const
Encoding
Size and signedness of expression operations' operands.
const Description & getDescription() const
uint64_t getRawOperand(unsigned Idx) const
bool skipValue(DataExtractor DebugInfoData, uint64_t *OffsetPtr, const dwarf::FormParams Params) const
Skip a form's value in DebugInfoData at the offset specified by OffsetPtr.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
void wait() override
Blocking wait for all the tasks to execute first.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:133
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:140
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition ThreadPool.h:80
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static Twine utohexstr(uint64_t Val)
Definition Twine.h:385
static LLVM_ABI raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition WithColor.cpp:83
This class represents DWARF information for source file and it's address map.
Definition DWARFFile.h:25
std::map< std::string, std::string > ObjectPrefixMapTy
function_ref< void(const DWARFUnit &Unit)> CompileUnitHandlerTy
AccelTableKind
The kind of accelerator tables to be emitted.
@ Apple
.apple_names, .apple_namespaces, .apple_types, .apple_objc.
std::map< std::string, std::string > SwiftInterfacesMapTy
std::function< ErrorOr< DWARFFile & >( StringRef ContainerName, StringRef Path)> ObjFileLoaderTy
const SmallVector< T > & getValues() const
Stores all information relating to a compile unit, be it in its original instance in the object file ...
void addObjectFile(DWARFFile &File, ObjFileLoaderTy Loader=nullptr, CompileUnitHandlerTy OnCUDieLoaded=[](const DWARFUnit &) {}) override
Add object file to be linked.
Error link() override
Link debug info for added objFiles. Object files are linked all together.
This class gives a tree-like API to the DenseMap that stores the DeclContext objects.
PointerIntPair< DeclContext *, 1 > getChildDeclContext(DeclContext &Context, const DWARFDie &DIE, CompileUnit &Unit, bool InClangModule)
Get the child of Context described by DIE in Unit.
A DeclContext is a named program scope that is used for ODR uniquing of types.
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
LLVM_ABI StringRef FormEncodingString(unsigned Encoding)
Definition Dwarf.cpp:105
LLVM_ABI StringRef FormatString(DwarfFormat Format)
Definition Dwarf.cpp:1023
#define UINT64_MAX
Definition DataTypes.h:77
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
SmallVector< PatchLocation > RngListAttributesTy
std::vector< std::unique_ptr< CompileUnit > > UnitListTy
IndexedValuesMap< uint64_t > DebugDieValuePool
Definition DWARFLinker.h:38
AddressRangesMap RangesTy
Mapped value in the address map is the offset to apply to the linked address.
SmallVector< PatchLocation > LocListAttributesTy
StringRef guessDeveloperDir(StringRef SysRoot)
Make a best effort to guess the Xcode.app/Contents/Developer path from an SDK path.
Definition Utils.h:41
StringMapEntry< EmptyStringSetTag > StringEntry
StringEntry keeps data of the string: the length, external offset and a string body which is placed r...
Definition StringPool.h:23
bool isInToolchainDir(StringRef Path)
Make a best effort to determine whether Path is inside a toolchain.
Definition Utils.h:77
bool isTlsAddressOp(uint8_t O)
Definition Dwarf.h:1094
std::optional< uint64_t > toAddress(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an address.
Attribute
Attributes.
Definition Dwarf.h:125
std::optional< const char * > toString(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
LLVM_ABI bool doesFormBelongToClass(dwarf::Form Form, DWARFFormValue::FormClass FC, uint16_t DwarfVersion)
Check whether specified Form belongs to the FC class.
std::optional< uint64_t > toSectionOffset(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
StringRef toStringRef(const std::optional< DWARFFormValue > &V, StringRef Default={})
Take an optional DWARFFormValue and try to extract a string value from it.
@ DW_CHILDREN_yes
Definition Dwarf.h:866
@ DW_FLAG_type_implementation
Definition Dwarf.h:953
std::optional< uint64_t > toUnsigned(const std::optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
LLVM_ABI bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition Path.cpp:706
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:584
LLVM_ABI bool replace_path_prefix(SmallVectorImpl< char > &Path, StringRef OldPrefix, StringRef NewPrefix, Style style=Style::native)
Replace matching path prefix with another path.
Definition Path.cpp:519
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:457
constexpr bool IsLittleEndianHost
void swapByteOrder(T &Value)
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy hardware_concurrency(unsigned ThreadCount=0)
Returns a default thread strategy where all available hardware resources are to be used,...
Definition Threading.h:190
static void verifyKeepChain(CompileUnit &CU)
Verify the keep chain by looking for DIEs that are kept but who's parent isn't.
@ Offset
Definition DWP.cpp:532
FunctionAddr VTableAddr Value
Definition InstrProf.h:137
static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &RefInfo)
Helper that updates the completeness of the current DIE based on the completeness of the DIEs it refe...
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
auto partition_point(R &&Range, Predicate P)
Binary search for the first iterator in a range where a predicate is false.
Definition STLExtras.h:2129
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2208
static void patchAddrBase(DIE &Die, DIEInteger Offset)
static std::string remapPath(StringRef Path, const DWARFLinkerBase::ObjectPrefixMapTy &ObjectPrefixMap)
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2065
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
Op::Description Desc
static CompileUnit * getUnitForOffset(const UnitListTy &Units, uint64_t Offset)
Similar to DWARFUnitSection::getUnitForOffset(), but returning our CompileUnit object instead.
static void insertLineSequence(std::vector< TrackedRow > &Seq, std::vector< TrackedRow > &Rows)
Insert the new line info sequence Seq into the current set of already linked line info Rows.
static void resolveRelativeObjectPath(SmallVectorImpl< char > &Buf, DWARFDie CU)
Resolve the relative path to a build artifact referenced by DWARF by applying DW_AT_comp_dir.
static std::string getPCMFile(const DWARFDie &CUDie, const DWARFLinkerBase::ObjectPrefixMapTy *ObjectPrefixMap)
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
static bool shouldSkipAttribute(bool Update, DWARFAbbreviationDeclaration::AttributeSpec AttrSpec, bool SkipPC)
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1636
static uint64_t getDebugInfoSize(DWARFContext &Dwarf)
Compute the total size of the debug info.
static bool isTypeTag(uint16_t Tag)
@ Dwarf
DWARF v5 .debug_names.
Definition DwarfDebug.h:348
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI std::optional< StringRef > StripTemplateParameters(StringRef Name)
If Name is the name of a templated function that includes template parameters, returns a substring of...
static uint64_t getDwoId(const DWARFDie &CUDie)
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
static bool updatePruning(const DWARFDie &Die, CompileUnit &CU, uint64_t ModulesEndOffset)
@ Success
The lock was released successfully.
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Ref
The access may reference the value stored in memory.
Definition ModRef.h:32
LLVM_ABI unsigned getULEB128Size(uint64_t Value)
Utility function to get the size of the ULEB128-encoded value.
Definition LEB128.cpp:19
FunctionAddr VTableAddr uintptr_t uintptr_t Data
Definition InstrProf.h:221
static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &ChildInfo)
Helper that updates the completeness of the current DIE based on the completeness of one of its child...
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:262
DWARFExpression::Operation Op
static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU, CompileUnit::DIEInfo &ChildInfo)
ArrayRef(const T &OneElt) -> ArrayRef< T >
uint32_t djbHash(StringRef Buffer, uint32_t H=5381)
The Bernstein hash function used by the DWARF accelerator tables.
Definition DJB.h:22
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
LLVM_ABI std::optional< ObjCSelectorNames > getObjCNamesIfSelector(StringRef Name)
If Name is the AT_name of a DIE which refers to an Objective-C selector, returns an instance of ObjCS...
static void analyzeContextInfo(const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU, DeclContext *CurrentDeclContext, DeclContextTree &Contexts, uint64_t ModulesEndOffset, DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces, std::function< void(const Twine &, const DWARFDie &)> ReportWarning)
Recursive helper to build the global DeclContext information and gather the child->parent relationshi...
static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag)
StrongType< NonRelocatableStringpool, OffsetsTag > OffsetsStringPool
static bool isODRCanonicalCandidate(const DWARFDie &Die, CompileUnit &CU)
unsigned encodeULEB128(uint64_t Value, raw_ostream &OS, unsigned PadTo=0)
Utility function to encode a ULEB128 value to an output stream.
Definition LEB128.h:79
static void analyzeImportedModule(const DWARFDie &DIE, CompileUnit &CU, DWARFLinkerBase::SwiftInterfacesMapTy *ParseableSwiftInterfaces, std::function< void(const Twine &, const DWARFDie &)> ReportWarning)
Collect references to parseable Swift interfaces in imported DW_TAG_module blocks.
ContextWorklistItemType
The distinct types of work performed by the work loop in analyzeContextInfo.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1106
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
static bool isODRAttribute(uint16_t Attr)
static void constructSeqOffsettoOrigRowMapping(CompileUnit &Unit, const DWARFDebugLine::LineTable &LT, DenseMap< uint64_t, unsigned > &SeqOffToOrigRow)
static void patchStmtList(DIE &Die, DIEInteger Offset)
std::vector< DWARFLocationExpression > DWARFLocationExpressionsVector
Represents a set of absolute location expressions.
#define N
This class represents an item in the work list.
CompileUnit::DIEInfo * OtherInfo
ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx, bool InImportedModule)
ContextWorklistItemType Type
ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T, CompileUnit::DIEInfo *OtherInfo=nullptr)
Container for dump options that control which debug information will be dumped.
Definition DIContext.h:196
DIDumpOptions noImplicitRecursion() const
Return the options with RecurseDepth set to 0 unless explicitly required.
Definition DIContext.h:228
unsigned ChildRecurseDepth
Definition DIContext.h:198
static LLVM_ABI bool mayHaveLocationList(dwarf::Attribute Attr)
Identify DWARF attributes that may contain a pointer to a location list.
Definition DWARFDie.cpp:806
static LLVM_ABI bool mayHaveLocationExpr(dwarf::Attribute Attr)
Identifies DWARF attributes that may contain a reference to a DWARF expression.
Definition DWARFDie.cpp:823
Standard .debug_line state machine structure.
Represents a series of contiguous machine instructions.
uint64_t StmtSeqOffset
The offset into the line table where this sequence begins.
SmallVector< Encoding > Op
Encoding for Op operands.
Hold the input and output of the debug info size in bytes.
A helper struct to help keep track of the association between the input and output rows during line t...
DWARFDebugLine::Row Row
Information gathered about a DIE in the object file.
bool Prune
Is this a pure forward declaration we can strip?
bool Incomplete
Does DIE transitively refer an incomplete decl?