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