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