[MIParser] Set RegClassOrRegBank during instruction parsing
[llvm-complete.git] / tools / dsymutil / DwarfLinker.cpp
blob3313f6a1539e81905292800b3f8c5922922c9b64
1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
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 //===----------------------------------------------------------------------===//
9 #include "DwarfLinker.h"
10 #include "BinaryHolder.h"
11 #include "DebugMap.h"
12 #include "DeclContext.h"
13 #include "DwarfStreamer.h"
14 #include "MachOUtils.h"
15 #include "NonRelocatableStringpool.h"
16 #include "dsymutil.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/BitVector.h"
19 #include "llvm/ADT/DenseMap.h"
20 #include "llvm/ADT/DenseMapInfo.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/Hashing.h"
24 #include "llvm/ADT/IntervalMap.h"
25 #include "llvm/ADT/None.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/PointerIntPair.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/ADT/Twine.h"
34 #include "llvm/BinaryFormat/Dwarf.h"
35 #include "llvm/BinaryFormat/MachO.h"
36 #include "llvm/CodeGen/AccelTable.h"
37 #include "llvm/CodeGen/AsmPrinter.h"
38 #include "llvm/CodeGen/DIE.h"
39 #include "llvm/Config/config.h"
40 #include "llvm/DebugInfo/DIContext.h"
41 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
42 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
43 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
44 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
45 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
46 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
47 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
48 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
49 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
50 #include "llvm/MC/MCAsmBackend.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCCodeEmitter.h"
53 #include "llvm/MC/MCContext.h"
54 #include "llvm/MC/MCDwarf.h"
55 #include "llvm/MC/MCInstrInfo.h"
56 #include "llvm/MC/MCObjectFileInfo.h"
57 #include "llvm/MC/MCObjectWriter.h"
58 #include "llvm/MC/MCRegisterInfo.h"
59 #include "llvm/MC/MCSection.h"
60 #include "llvm/MC/MCStreamer.h"
61 #include "llvm/MC/MCSubtargetInfo.h"
62 #include "llvm/MC/MCTargetOptions.h"
63 #include "llvm/Object/MachO.h"
64 #include "llvm/Object/ObjectFile.h"
65 #include "llvm/Object/SymbolicFile.h"
66 #include "llvm/Support/Allocator.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/DJB.h"
70 #include "llvm/Support/DataExtractor.h"
71 #include "llvm/Support/Error.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/ErrorOr.h"
74 #include "llvm/Support/FileSystem.h"
75 #include "llvm/Support/Format.h"
76 #include "llvm/Support/LEB128.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Support/MemoryBuffer.h"
79 #include "llvm/Support/Path.h"
80 #include "llvm/Support/TargetRegistry.h"
81 #include "llvm/Support/ThreadPool.h"
82 #include "llvm/Support/ToolOutputFile.h"
83 #include "llvm/Support/WithColor.h"
84 #include "llvm/Support/raw_ostream.h"
85 #include "llvm/Target/TargetMachine.h"
86 #include "llvm/Target/TargetOptions.h"
87 #include <algorithm>
88 #include <cassert>
89 #include <cinttypes>
90 #include <climits>
91 #include <cstdint>
92 #include <cstdlib>
93 #include <cstring>
94 #include <limits>
95 #include <map>
96 #include <memory>
97 #include <string>
98 #include <system_error>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
103 namespace llvm {
104 namespace dsymutil {
106 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
107 /// CompileUnit object instead.
108 static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
109 auto CU = std::upper_bound(
110 Units.begin(), Units.end(), Offset,
111 [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
112 return LHS < RHS->getOrigUnit().getNextUnitOffset();
114 return CU != Units.end() ? CU->get() : nullptr;
117 /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
118 /// The resulting DIE might be in another CompileUnit which is stored into \p
119 /// ReferencedCU. \returns null if resolving fails for any reason.
120 static DWARFDie resolveDIEReference(const DwarfLinker &Linker,
121 const DebugMapObject &DMO,
122 const UnitListTy &Units,
123 const DWARFFormValue &RefValue,
124 const DWARFDie &DIE, CompileUnit *&RefCU) {
125 assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
126 uint64_t RefOffset = *RefValue.getAsReference();
127 if ((RefCU = getUnitForOffset(Units, RefOffset)))
128 if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
129 // In a file with broken references, an attribute might point to a NULL
130 // DIE.
131 if (!RefDie.isNULL())
132 return RefDie;
135 Linker.reportWarning("could not find referenced DIE", DMO, &DIE);
136 return DWARFDie();
139 /// \returns whether the passed \a Attr type might contain a DIE reference
140 /// suitable for ODR uniquing.
141 static bool isODRAttribute(uint16_t Attr) {
142 switch (Attr) {
143 default:
144 return false;
145 case dwarf::DW_AT_type:
146 case dwarf::DW_AT_containing_type:
147 case dwarf::DW_AT_specification:
148 case dwarf::DW_AT_abstract_origin:
149 case dwarf::DW_AT_import:
150 return true;
152 llvm_unreachable("Improper attribute.");
155 static bool isTypeTag(uint16_t Tag) {
156 switch (Tag) {
157 case dwarf::DW_TAG_array_type:
158 case dwarf::DW_TAG_class_type:
159 case dwarf::DW_TAG_enumeration_type:
160 case dwarf::DW_TAG_pointer_type:
161 case dwarf::DW_TAG_reference_type:
162 case dwarf::DW_TAG_string_type:
163 case dwarf::DW_TAG_structure_type:
164 case dwarf::DW_TAG_subroutine_type:
165 case dwarf::DW_TAG_typedef:
166 case dwarf::DW_TAG_union_type:
167 case dwarf::DW_TAG_ptr_to_member_type:
168 case dwarf::DW_TAG_set_type:
169 case dwarf::DW_TAG_subrange_type:
170 case dwarf::DW_TAG_base_type:
171 case dwarf::DW_TAG_const_type:
172 case dwarf::DW_TAG_constant:
173 case dwarf::DW_TAG_file_type:
174 case dwarf::DW_TAG_namelist:
175 case dwarf::DW_TAG_packed_type:
176 case dwarf::DW_TAG_volatile_type:
177 case dwarf::DW_TAG_restrict_type:
178 case dwarf::DW_TAG_atomic_type:
179 case dwarf::DW_TAG_interface_type:
180 case dwarf::DW_TAG_unspecified_type:
181 case dwarf::DW_TAG_shared_type:
182 return true;
183 default:
184 break;
186 return false;
189 bool DwarfLinker::DIECloner::getDIENames(const DWARFDie &Die,
190 AttributesInfo &Info,
191 OffsetsStringPool &StringPool,
192 bool StripTemplate) {
193 // This function will be called on DIEs having low_pcs and
194 // ranges. As getting the name might be more expansive, filter out
195 // blocks directly.
196 if (Die.getTag() == dwarf::DW_TAG_lexical_block)
197 return false;
199 // FIXME: a bit wasteful as the first getName might return the
200 // short name.
201 if (!Info.MangledName)
202 if (const char *MangledName = Die.getName(DINameKind::LinkageName))
203 Info.MangledName = StringPool.getEntry(MangledName);
205 if (!Info.Name)
206 if (const char *Name = Die.getName(DINameKind::ShortName))
207 Info.Name = StringPool.getEntry(Name);
209 if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
210 // FIXME: dsymutil compatibility. This is wrong for operator<
211 auto Split = Info.Name.getString().split('<');
212 if (!Split.second.empty())
213 Info.NameWithoutTemplate = StringPool.getEntry(Split.first);
216 return Info.Name || Info.MangledName;
219 /// Report a warning to the user, optionally including information about a
220 /// specific \p DIE related to the warning.
221 void DwarfLinker::reportWarning(const Twine &Warning, const DebugMapObject &DMO,
222 const DWARFDie *DIE) const {
223 StringRef Context = DMO.getObjectFilename();
224 warn(Warning, Context);
226 if (!Options.Verbose || !DIE)
227 return;
229 DIDumpOptions DumpOpts;
230 DumpOpts.ChildRecurseDepth = 0;
231 DumpOpts.Verbose = Options.Verbose;
233 WithColor::note() << " in DIE:\n";
234 DIE->dump(errs(), 6 /* Indent */, DumpOpts);
237 bool DwarfLinker::createStreamer(const Triple &TheTriple,
238 raw_fd_ostream &OutFile) {
239 if (Options.NoOutput)
240 return true;
242 Streamer = std::make_unique<DwarfStreamer>(OutFile, Options);
243 return Streamer->init(TheTriple);
246 /// Resolve the relative path to a build artifact referenced by DWARF by
247 /// applying DW_AT_comp_dir.
248 static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
249 sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
252 /// Collect references to parseable Swift interfaces in imported
253 /// DW_TAG_module blocks.
254 static void analyzeImportedModule(
255 const DWARFDie &DIE, CompileUnit &CU,
256 std::map<std::string, std::string> &ParseableSwiftInterfaces,
257 std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
258 if (CU.getLanguage() != dwarf::DW_LANG_Swift)
259 return;
261 StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
262 if (!Path.endswith(".swiftinterface"))
263 return;
264 if (Optional<DWARFFormValue> Val = DIE.find(dwarf::DW_AT_name))
265 if (Optional<const char *> Name = Val->getAsCString()) {
266 auto &Entry = ParseableSwiftInterfaces[*Name];
267 // The prepend path is applied later when copying.
268 DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
269 SmallString<128> ResolvedPath;
270 if (sys::path::is_relative(Path))
271 resolveRelativeObjectPath(ResolvedPath, CUDie);
272 sys::path::append(ResolvedPath, Path);
273 if (!Entry.empty() && Entry != ResolvedPath)
274 ReportWarning(
275 Twine("Conflicting parseable interfaces for Swift Module ") +
276 *Name + ": " + Entry + " and " + Path,
277 DIE);
278 Entry = ResolvedPath.str();
282 /// Recursive helper to build the global DeclContext information and
283 /// gather the child->parent relationships in the original compile unit.
285 /// \return true when this DIE and all of its children are only
286 /// forward declarations to types defined in external clang modules
287 /// (i.e., forward declarations that are children of a DW_TAG_module).
288 static bool analyzeContextInfo(
289 const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
290 DeclContext *CurrentDeclContext, UniquingStringPool &StringPool,
291 DeclContextTree &Contexts, uint64_t ModulesEndOffset,
292 std::map<std::string, std::string> &ParseableSwiftInterfaces,
293 std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
294 bool InImportedModule = false) {
295 unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
296 CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
298 // Clang imposes an ODR on modules(!) regardless of the language:
299 // "The module-id should consist of only a single identifier,
300 // which provides the name of the module being defined. Each
301 // module shall have a single definition."
303 // This does not extend to the types inside the modules:
304 // "[I]n C, this implies that if two structs are defined in
305 // different submodules with the same name, those two types are
306 // distinct types (but may be compatible types if their
307 // definitions match)."
309 // We treat non-C++ modules like namespaces for this reason.
310 if (DIE.getTag() == dwarf::DW_TAG_module && ParentIdx == 0 &&
311 dwarf::toString(DIE.find(dwarf::DW_AT_name), "") !=
312 CU.getClangModuleName()) {
313 InImportedModule = true;
314 analyzeImportedModule(DIE, CU, ParseableSwiftInterfaces, ReportWarning);
317 Info.ParentIdx = ParentIdx;
318 bool InClangModule = CU.isClangModule() || InImportedModule;
319 if (CU.hasODR() || InClangModule) {
320 if (CurrentDeclContext) {
321 auto PtrInvalidPair = Contexts.getChildDeclContext(
322 *CurrentDeclContext, DIE, CU, StringPool, InClangModule);
323 CurrentDeclContext = PtrInvalidPair.getPointer();
324 Info.Ctxt =
325 PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
326 if (Info.Ctxt)
327 Info.Ctxt->setDefinedInClangModule(InClangModule);
328 } else
329 Info.Ctxt = CurrentDeclContext = nullptr;
332 Info.Prune = InImportedModule;
333 if (DIE.hasChildren())
334 for (auto Child : DIE.children())
335 Info.Prune &= analyzeContextInfo(Child, MyIdx, CU, CurrentDeclContext,
336 StringPool, Contexts, ModulesEndOffset,
337 ParseableSwiftInterfaces, ReportWarning,
338 InImportedModule);
340 // Prune this DIE if it is either a forward declaration inside a
341 // DW_TAG_module or a DW_TAG_module that contains nothing but
342 // forward declarations.
343 Info.Prune &= (DIE.getTag() == dwarf::DW_TAG_module) ||
344 (isTypeTag(DIE.getTag()) &&
345 dwarf::toUnsigned(DIE.find(dwarf::DW_AT_declaration), 0));
347 // Only prune forward declarations inside a DW_TAG_module for which a
348 // definition exists elsewhere.
349 if (ModulesEndOffset == 0)
350 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
351 else
352 Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
353 Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
355 return Info.Prune;
356 } // namespace dsymutil
358 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
359 switch (Tag) {
360 default:
361 return false;
362 case dwarf::DW_TAG_subprogram:
363 case dwarf::DW_TAG_lexical_block:
364 case dwarf::DW_TAG_subroutine_type:
365 case dwarf::DW_TAG_structure_type:
366 case dwarf::DW_TAG_class_type:
367 case dwarf::DW_TAG_union_type:
368 return true;
370 llvm_unreachable("Invalid Tag");
373 void DwarfLinker::startDebugObject(LinkContext &Context) {
374 // Iterate over the debug map entries and put all the ones that are
375 // functions (because they have a size) into the Ranges map. This map is
376 // very similar to the FunctionRanges that are stored in each unit, with 2
377 // notable differences:
379 // 1. Obviously this one is global, while the other ones are per-unit.
381 // 2. This one contains not only the functions described in the DIE
382 // tree, but also the ones that are only in the debug map.
384 // The latter information is required to reproduce dsymutil's logic while
385 // linking line tables. The cases where this information matters look like
386 // bugs that need to be investigated, but for now we need to reproduce
387 // dsymutil's behavior.
388 // FIXME: Once we understood exactly if that information is needed,
389 // maybe totally remove this (or try to use it to do a real
390 // -gline-tables-only on Darwin.
391 for (const auto &Entry : Context.DMO.symbols()) {
392 const auto &Mapping = Entry.getValue();
393 if (Mapping.Size && Mapping.ObjectAddress)
394 Context.Ranges[*Mapping.ObjectAddress] = DebugMapObjectRange(
395 *Mapping.ObjectAddress + Mapping.Size,
396 int64_t(Mapping.BinaryAddress) - *Mapping.ObjectAddress);
400 void DwarfLinker::endDebugObject(LinkContext &Context) {
401 Context.Clear();
403 for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
404 (*I)->~DIEBlock();
405 for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
406 (*I)->~DIELoc();
408 DIEBlocks.clear();
409 DIELocs.clear();
410 DIEAlloc.Reset();
413 static bool isMachOPairedReloc(uint64_t RelocType, uint64_t Arch) {
414 switch (Arch) {
415 case Triple::x86:
416 return RelocType == MachO::GENERIC_RELOC_SECTDIFF ||
417 RelocType == MachO::GENERIC_RELOC_LOCAL_SECTDIFF;
418 case Triple::x86_64:
419 return RelocType == MachO::X86_64_RELOC_SUBTRACTOR;
420 case Triple::arm:
421 case Triple::thumb:
422 return RelocType == MachO::ARM_RELOC_SECTDIFF ||
423 RelocType == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
424 RelocType == MachO::ARM_RELOC_HALF ||
425 RelocType == MachO::ARM_RELOC_HALF_SECTDIFF;
426 case Triple::aarch64:
427 return RelocType == MachO::ARM64_RELOC_SUBTRACTOR;
428 default:
429 return false;
433 /// Iterate over the relocations of the given \p Section and
434 /// store the ones that correspond to debug map entries into the
435 /// ValidRelocs array.
436 void DwarfLinker::RelocationManager::findValidRelocsMachO(
437 const object::SectionRef &Section, const object::MachOObjectFile &Obj,
438 const DebugMapObject &DMO) {
439 Expected<StringRef> ContentsOrErr = Section.getContents();
440 if (!ContentsOrErr) {
441 consumeError(ContentsOrErr.takeError());
442 Linker.reportWarning("error reading section", DMO);
443 return;
445 DataExtractor Data(*ContentsOrErr, Obj.isLittleEndian(), 0);
446 bool SkipNext = false;
448 for (const object::RelocationRef &Reloc : Section.relocations()) {
449 if (SkipNext) {
450 SkipNext = false;
451 continue;
454 object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
455 MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
457 if (isMachOPairedReloc(Obj.getAnyRelocationType(MachOReloc),
458 Obj.getArch())) {
459 SkipNext = true;
460 Linker.reportWarning("unsupported relocation in debug_info section.",
461 DMO);
462 continue;
465 unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
466 uint64_t Offset64 = Reloc.getOffset();
467 if ((RelocSize != 4 && RelocSize != 8)) {
468 Linker.reportWarning("unsupported relocation in debug_info section.",
469 DMO);
470 continue;
472 uint64_t OffsetCopy = Offset64;
473 // Mach-o uses REL relocations, the addend is at the relocation offset.
474 uint64_t Addend = Data.getUnsigned(&OffsetCopy, RelocSize);
475 uint64_t SymAddress;
476 int64_t SymOffset;
478 if (Obj.isRelocationScattered(MachOReloc)) {
479 // The address of the base symbol for scattered relocations is
480 // stored in the reloc itself. The actual addend will store the
481 // base address plus the offset.
482 SymAddress = Obj.getScatteredRelocationValue(MachOReloc);
483 SymOffset = int64_t(Addend) - SymAddress;
484 } else {
485 SymAddress = Addend;
486 SymOffset = 0;
489 auto Sym = Reloc.getSymbol();
490 if (Sym != Obj.symbol_end()) {
491 Expected<StringRef> SymbolName = Sym->getName();
492 if (!SymbolName) {
493 consumeError(SymbolName.takeError());
494 Linker.reportWarning("error getting relocation symbol name.", DMO);
495 continue;
497 if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
498 ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
499 } else if (const auto *Mapping = DMO.lookupObjectAddress(SymAddress)) {
500 // Do not store the addend. The addend was the address of the symbol in
501 // the object file, the address in the binary that is stored in the debug
502 // map doesn't need to be offset.
503 ValidRelocs.emplace_back(Offset64, RelocSize, SymOffset, Mapping);
508 /// Dispatch the valid relocation finding logic to the
509 /// appropriate handler depending on the object file format.
510 bool DwarfLinker::RelocationManager::findValidRelocs(
511 const object::SectionRef &Section, const object::ObjectFile &Obj,
512 const DebugMapObject &DMO) {
513 // Dispatch to the right handler depending on the file type.
514 if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
515 findValidRelocsMachO(Section, *MachOObj, DMO);
516 else
517 Linker.reportWarning(
518 Twine("unsupported object file type: ") + Obj.getFileName(), DMO);
520 if (ValidRelocs.empty())
521 return false;
523 // Sort the relocations by offset. We will walk the DIEs linearly in
524 // the file, this allows us to just keep an index in the relocation
525 // array that we advance during our walk, rather than resorting to
526 // some associative container. See DwarfLinker::NextValidReloc.
527 llvm::sort(ValidRelocs);
528 return true;
531 /// Look for relocations in the debug_info section that match
532 /// entries in the debug map. These relocations will drive the Dwarf
533 /// link by indicating which DIEs refer to symbols present in the
534 /// linked binary.
535 /// \returns whether there are any valid relocations in the debug info.
536 bool DwarfLinker::RelocationManager::findValidRelocsInDebugInfo(
537 const object::ObjectFile &Obj, const DebugMapObject &DMO) {
538 // Find the debug_info section.
539 for (const object::SectionRef &Section : Obj.sections()) {
540 StringRef SectionName;
541 if (Expected<StringRef> NameOrErr = Section.getName())
542 SectionName = *NameOrErr;
543 else
544 consumeError(NameOrErr.takeError());
546 SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
547 if (SectionName != "debug_info")
548 continue;
549 return findValidRelocs(Section, Obj, DMO);
551 return false;
554 /// Checks that there is a relocation against an actual debug
555 /// map entry between \p StartOffset and \p NextOffset.
557 /// This function must be called with offsets in strictly ascending
558 /// order because it never looks back at relocations it already 'went past'.
559 /// \returns true and sets Info.InDebugMap if it is the case.
560 bool DwarfLinker::RelocationManager::hasValidRelocation(
561 uint64_t StartOffset, uint64_t EndOffset, CompileUnit::DIEInfo &Info) {
562 assert(NextValidReloc == 0 ||
563 StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
564 if (NextValidReloc >= ValidRelocs.size())
565 return false;
567 uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
569 // We might need to skip some relocs that we didn't consider. For
570 // example the high_pc of a discarded DIE might contain a reloc that
571 // is in the list because it actually corresponds to the start of a
572 // function that is in the debug map.
573 while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
574 RelocOffset = ValidRelocs[++NextValidReloc].Offset;
576 if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
577 return false;
579 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
580 const auto &Mapping = ValidReloc.Mapping->getValue();
581 const uint64_t BinaryAddress = Mapping.BinaryAddress;
582 const uint64_t ObjectAddress = Mapping.ObjectAddress
583 ? uint64_t(*Mapping.ObjectAddress)
584 : std::numeric_limits<uint64_t>::max();
585 if (Linker.Options.Verbose)
586 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
587 << "\t"
588 << format("0x%016" PRIx64 " => 0x%016" PRIx64 "\n", ObjectAddress,
589 BinaryAddress);
591 Info.AddrAdjust = BinaryAddress + ValidReloc.Addend;
592 if (Mapping.ObjectAddress)
593 Info.AddrAdjust -= ObjectAddress;
594 Info.InDebugMap = true;
595 return true;
598 /// Get the starting and ending (exclusive) offset for the
599 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
600 /// supposed to point to the position of the first attribute described
601 /// by \p Abbrev.
602 /// \return [StartOffset, EndOffset) as a pair.
603 static std::pair<uint64_t, uint64_t>
604 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
605 uint64_t Offset, const DWARFUnit &Unit) {
606 DataExtractor Data = Unit.getDebugInfoExtractor();
608 for (unsigned i = 0; i < Idx; ++i)
609 DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset,
610 Unit.getFormParams());
612 uint64_t End = Offset;
613 DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End,
614 Unit.getFormParams());
616 return std::make_pair(Offset, End);
619 /// Check if a variable describing DIE should be kept.
620 /// \returns updated TraversalFlags.
621 unsigned DwarfLinker::shouldKeepVariableDIE(RelocationManager &RelocMgr,
622 const DWARFDie &DIE,
623 CompileUnit &Unit,
624 CompileUnit::DIEInfo &MyInfo,
625 unsigned Flags) {
626 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
628 // Global variables with constant value can always be kept.
629 if (!(Flags & TF_InFunctionScope) &&
630 Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
631 MyInfo.InDebugMap = true;
632 return Flags | TF_Keep;
635 Optional<uint32_t> LocationIdx =
636 Abbrev->findAttributeIndex(dwarf::DW_AT_location);
637 if (!LocationIdx)
638 return Flags;
640 uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
641 const DWARFUnit &OrigUnit = Unit.getOrigUnit();
642 uint64_t LocationOffset, LocationEndOffset;
643 std::tie(LocationOffset, LocationEndOffset) =
644 getAttributeOffsets(Abbrev, *LocationIdx, Offset, OrigUnit);
646 // See if there is a relocation to a valid debug map entry inside
647 // this variable's location. The order is important here. We want to
648 // always check if the variable has a valid relocation, so that the
649 // DIEInfo is filled. However, we don't want a static variable in a
650 // function to force us to keep the enclosing function.
651 if (!RelocMgr.hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
652 (Flags & TF_InFunctionScope))
653 return Flags;
655 if (Options.Verbose) {
656 outs() << "Keeping variable DIE:";
657 DIDumpOptions DumpOpts;
658 DumpOpts.ChildRecurseDepth = 0;
659 DumpOpts.Verbose = Options.Verbose;
660 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
663 return Flags | TF_Keep;
666 /// Check if a function describing DIE should be kept.
667 /// \returns updated TraversalFlags.
668 unsigned DwarfLinker::shouldKeepSubprogramDIE(
669 RelocationManager &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
670 const DebugMapObject &DMO, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
671 unsigned Flags) {
672 const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
674 Flags |= TF_InFunctionScope;
676 Optional<uint32_t> LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
677 if (!LowPcIdx)
678 return Flags;
680 uint64_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
681 DWARFUnit &OrigUnit = Unit.getOrigUnit();
682 uint64_t LowPcOffset, LowPcEndOffset;
683 std::tie(LowPcOffset, LowPcEndOffset) =
684 getAttributeOffsets(Abbrev, *LowPcIdx, Offset, OrigUnit);
686 auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
687 assert(LowPc.hasValue() && "low_pc attribute is not an address.");
688 if (!LowPc ||
689 !RelocMgr.hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
690 return Flags;
692 if (Options.Verbose) {
693 outs() << "Keeping subprogram DIE:";
694 DIDumpOptions DumpOpts;
695 DumpOpts.ChildRecurseDepth = 0;
696 DumpOpts.Verbose = Options.Verbose;
697 DIE.dump(outs(), 8 /* Indent */, DumpOpts);
700 if (DIE.getTag() == dwarf::DW_TAG_label) {
701 if (Unit.hasLabelAt(*LowPc))
702 return Flags;
703 // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
704 // that don't fall into the CU's aranges. This is wrong IMO. Debug info
705 // generation bugs aside, this is really wrong in the case of labels, where
706 // a label marking the end of a function will have a PC == CU's high_pc.
707 if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
708 .getValueOr(UINT64_MAX) <= LowPc)
709 return Flags;
710 Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
711 return Flags | TF_Keep;
714 Flags |= TF_Keep;
716 Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
717 if (!HighPc) {
718 reportWarning("Function without high_pc. Range will be discarded.\n", DMO,
719 &DIE);
720 return Flags;
723 // Replace the debug map range with a more accurate one.
724 Ranges[*LowPc] = DebugMapObjectRange(*HighPc, MyInfo.AddrAdjust);
725 Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
726 return Flags;
729 /// Check if a DIE should be kept.
730 /// \returns updated TraversalFlags.
731 unsigned DwarfLinker::shouldKeepDIE(RelocationManager &RelocMgr,
732 RangesTy &Ranges, const DWARFDie &DIE,
733 const DebugMapObject &DMO,
734 CompileUnit &Unit,
735 CompileUnit::DIEInfo &MyInfo,
736 unsigned Flags) {
737 switch (DIE.getTag()) {
738 case dwarf::DW_TAG_constant:
739 case dwarf::DW_TAG_variable:
740 return shouldKeepVariableDIE(RelocMgr, DIE, Unit, MyInfo, Flags);
741 case dwarf::DW_TAG_subprogram:
742 case dwarf::DW_TAG_label:
743 return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, DMO, Unit, MyInfo,
744 Flags);
745 case dwarf::DW_TAG_base_type:
746 // DWARF Expressions may reference basic types, but scanning them
747 // is expensive. Basic types are tiny, so just keep all of them.
748 case dwarf::DW_TAG_imported_module:
749 case dwarf::DW_TAG_imported_declaration:
750 case dwarf::DW_TAG_imported_unit:
751 // We always want to keep these.
752 return Flags | TF_Keep;
753 default:
754 break;
757 return Flags;
760 /// Mark the passed DIE as well as all the ones it depends on
761 /// as kept.
763 /// This function is called by lookForDIEsToKeep on DIEs that are
764 /// newly discovered to be needed in the link. It recursively calls
765 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
766 /// TraversalFlags to inform it that it's not doing the primary DIE
767 /// tree walk.
768 void DwarfLinker::keepDIEAndDependencies(
769 RelocationManager &RelocMgr, RangesTy &Ranges, const UnitListTy &Units,
770 const DWARFDie &Die, CompileUnit::DIEInfo &MyInfo,
771 const DebugMapObject &DMO, CompileUnit &CU, bool UseODR) {
772 DWARFUnit &Unit = CU.getOrigUnit();
773 MyInfo.Keep = true;
775 // We're looking for incomplete types.
776 MyInfo.Incomplete = Die.getTag() != dwarf::DW_TAG_subprogram &&
777 Die.getTag() != dwarf::DW_TAG_member &&
778 dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0);
780 // First mark all the parent chain as kept.
781 unsigned AncestorIdx = MyInfo.ParentIdx;
782 while (!CU.getInfo(AncestorIdx).Keep) {
783 unsigned ODRFlag = UseODR ? TF_ODR : 0;
784 lookForDIEsToKeep(RelocMgr, Ranges, Units, Unit.getDIEAtIndex(AncestorIdx),
785 DMO, CU,
786 TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
787 AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
790 // Then we need to mark all the DIEs referenced by this DIE's
791 // attributes as kept.
792 DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
793 const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
794 uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
796 // Mark all DIEs referenced through attributes as kept.
797 for (const auto &AttrSpec : Abbrev->attributes()) {
798 DWARFFormValue Val(AttrSpec.Form);
799 if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
800 AttrSpec.Attr == dwarf::DW_AT_sibling) {
801 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
802 Unit.getFormParams());
803 continue;
806 Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
807 CompileUnit *ReferencedCU;
808 if (auto RefDie =
809 resolveDIEReference(*this, DMO, Units, Val, Die, ReferencedCU)) {
810 uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDie);
811 CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
812 bool IsModuleRef = Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() &&
813 Info.Ctxt->isDefinedInClangModule();
814 // If the referenced DIE has a DeclContext that has already been
815 // emitted, then do not keep the one in this CU. We'll link to
816 // the canonical DIE in cloneDieReferenceAttribute.
817 // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
818 // be necessary and could be advantageously replaced by
819 // ReferencedCU->hasODR() && CU.hasODR().
820 // FIXME: compatibility with dsymutil-classic. There is no
821 // reason not to unique ref_addr references.
822 if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && (UseODR || IsModuleRef) &&
823 Info.Ctxt &&
824 Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
825 Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
826 continue;
828 // Keep a module forward declaration if there is no definition.
829 if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
830 Info.Ctxt->getCanonicalDIEOffset()))
831 Info.Prune = false;
833 unsigned ODRFlag = UseODR ? TF_ODR : 0;
834 lookForDIEsToKeep(RelocMgr, Ranges, Units, RefDie, DMO, *ReferencedCU,
835 TF_Keep | TF_DependencyWalk | ODRFlag);
837 // The incomplete property is propagated if the current DIE is complete
838 // but references an incomplete DIE.
839 if (Info.Incomplete && !MyInfo.Incomplete &&
840 (Die.getTag() == dwarf::DW_TAG_typedef ||
841 Die.getTag() == dwarf::DW_TAG_member ||
842 Die.getTag() == dwarf::DW_TAG_reference_type ||
843 Die.getTag() == dwarf::DW_TAG_ptr_to_member_type ||
844 Die.getTag() == dwarf::DW_TAG_pointer_type))
845 MyInfo.Incomplete = true;
850 namespace {
851 /// This class represents an item in the work list. In addition to it's obvious
852 /// purpose of representing the state associated with a particular run of the
853 /// work loop, it also serves as a marker to indicate that we should run the
854 /// "continuation" code.
856 /// Originally, the latter was lambda which allowed arbitrary code to be run.
857 /// Because we always need to run the exact same code, it made more sense to
858 /// use a boolean and repurpose the already existing DIE field.
859 struct WorklistItem {
860 DWARFDie Die;
861 unsigned Flags;
862 bool IsContinuation;
863 CompileUnit::DIEInfo *ChildInfo = nullptr;
865 /// Construct a classic worklist item.
866 WorklistItem(DWARFDie Die, unsigned Flags)
867 : Die(Die), Flags(Flags), IsContinuation(false){};
869 /// Creates a continuation marker.
870 WorklistItem(DWARFDie Die) : Die(Die), IsContinuation(true){};
872 } // namespace
874 // Helper that updates the completeness of the current DIE. It depends on the
875 // fact that the incompletness of its children is already computed.
876 static void updateIncompleteness(const DWARFDie &Die,
877 CompileUnit::DIEInfo &ChildInfo,
878 CompileUnit &CU) {
879 // Only propagate incomplete members.
880 if (Die.getTag() != dwarf::DW_TAG_structure_type &&
881 Die.getTag() != dwarf::DW_TAG_class_type)
882 return;
884 unsigned Idx = CU.getOrigUnit().getDIEIndex(Die);
885 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
887 if (MyInfo.Incomplete)
888 return;
890 if (ChildInfo.Incomplete || ChildInfo.Prune)
891 MyInfo.Incomplete = true;
894 /// Recursively walk the \p DIE tree and look for DIEs to
895 /// keep. Store that information in \p CU's DIEInfo.
897 /// This function is the entry point of the DIE selection
898 /// algorithm. It is expected to walk the DIE tree in file order and
899 /// (though the mediation of its helper) call hasValidRelocation() on
900 /// each DIE that might be a 'root DIE' (See DwarfLinker class
901 /// comment).
902 /// While walking the dependencies of root DIEs, this function is
903 /// also called, but during these dependency walks the file order is
904 /// not respected. The TF_DependencyWalk flag tells us which kind of
905 /// traversal we are currently doing.
907 /// The return value indicates whether the DIE is incomplete.
908 void DwarfLinker::lookForDIEsToKeep(RelocationManager &RelocMgr,
909 RangesTy &Ranges, const UnitListTy &Units,
910 const DWARFDie &Die,
911 const DebugMapObject &DMO, CompileUnit &CU,
912 unsigned Flags) {
913 // LIFO work list.
914 SmallVector<WorklistItem, 4> Worklist;
915 Worklist.emplace_back(Die, Flags);
917 while (!Worklist.empty()) {
918 WorklistItem Current = Worklist.back();
919 Worklist.pop_back();
921 if (Current.IsContinuation) {
922 updateIncompleteness(Current.Die, *Current.ChildInfo, CU);
923 continue;
926 unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
927 CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
929 // At this point we are guaranteed to have a continuation marker before us
930 // in the worklist, except for the last DIE.
931 if (!Worklist.empty())
932 Worklist.back().ChildInfo = &MyInfo;
934 if (MyInfo.Prune)
935 continue;
937 // If the Keep flag is set, we are marking a required DIE's dependencies.
938 // If our target is already marked as kept, we're all set.
939 bool AlreadyKept = MyInfo.Keep;
940 if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
941 continue;
943 // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
944 // because it would screw up the relocation finding logic.
945 if (!(Current.Flags & TF_DependencyWalk))
946 Current.Flags = shouldKeepDIE(RelocMgr, Ranges, Current.Die, DMO, CU,
947 MyInfo, Current.Flags);
949 // If it is a newly kept DIE mark it as well as all its dependencies as
950 // kept.
951 if (!AlreadyKept && (Current.Flags & TF_Keep)) {
952 bool UseOdr = (Current.Flags & TF_DependencyWalk)
953 ? (Current.Flags & TF_ODR)
954 : CU.hasODR();
955 keepDIEAndDependencies(RelocMgr, Ranges, Units, Current.Die, MyInfo, DMO,
956 CU, UseOdr);
959 // The TF_ParentWalk flag tells us that we are currently walking up
960 // the parent chain of a required DIE, and we don't want to mark all
961 // the children of the parents as kept (consider for example a
962 // DW_TAG_namespace node in the parent chain). There are however a
963 // set of DIE types for which we want to ignore that directive and still
964 // walk their children.
965 if (dieNeedsChildrenToBeMeaningful(Current.Die.getTag()))
966 Current.Flags &= ~TF_ParentWalk;
968 if (!Current.Die.hasChildren() || (Current.Flags & TF_ParentWalk))
969 continue;
971 // Add children in reverse order to the worklist to effectively process
972 // them in order.
973 for (auto Child : reverse(Current.Die.children())) {
974 // Add continuation marker before every child to calculate incompleteness
975 // after the last child is processed. We can't store this information in
976 // the same item because we might have to process other continuations
977 // first.
978 Worklist.emplace_back(Current.Die);
979 Worklist.emplace_back(Child, Current.Flags);
984 /// Assign an abbreviation number to \p Abbrev.
986 /// Our DIEs get freed after every DebugMapObject has been processed,
987 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
988 /// the instances hold by the DIEs. When we encounter an abbreviation
989 /// that we don't know, we create a permanent copy of it.
990 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
991 // Check the set for priors.
992 FoldingSetNodeID ID;
993 Abbrev.Profile(ID);
994 void *InsertToken;
995 DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
997 // If it's newly added.
998 if (InSet) {
999 // Assign existing abbreviation number.
1000 Abbrev.setNumber(InSet->getNumber());
1001 } else {
1002 // Add to abbreviation list.
1003 Abbreviations.push_back(
1004 std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
1005 for (const auto &Attr : Abbrev.getData())
1006 Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
1007 AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
1008 // Assign the unique abbreviation number.
1009 Abbrev.setNumber(Abbreviations.size());
1010 Abbreviations.back()->setNumber(Abbreviations.size());
1014 unsigned DwarfLinker::DIECloner::cloneStringAttribute(
1015 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1016 const DWARFUnit &U, OffsetsStringPool &StringPool, AttributesInfo &Info) {
1017 // Switch everything to out of line strings.
1018 const char *String = *Val.getAsCString();
1019 auto StringEntry = StringPool.getEntry(String);
1021 // Update attributes info.
1022 if (AttrSpec.Attr == dwarf::DW_AT_name)
1023 Info.Name = StringEntry;
1024 else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
1025 AttrSpec.Attr == dwarf::DW_AT_linkage_name)
1026 Info.MangledName = StringEntry;
1028 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
1029 DIEInteger(StringEntry.getOffset()));
1031 return 4;
1034 unsigned DwarfLinker::DIECloner::cloneDieReferenceAttribute(
1035 DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
1036 unsigned AttrSize, const DWARFFormValue &Val, const DebugMapObject &DMO,
1037 CompileUnit &Unit) {
1038 const DWARFUnit &U = Unit.getOrigUnit();
1039 uint64_t Ref = *Val.getAsReference();
1040 DIE *NewRefDie = nullptr;
1041 CompileUnit *RefUnit = nullptr;
1042 DeclContext *Ctxt = nullptr;
1044 DWARFDie RefDie =
1045 resolveDIEReference(Linker, DMO, CompileUnits, Val, InputDIE, RefUnit);
1047 // If the referenced DIE is not found, drop the attribute.
1048 if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
1049 return 0;
1051 unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
1052 CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
1054 // If we already have emitted an equivalent DeclContext, just point
1055 // at it.
1056 if (isODRAttribute(AttrSpec.Attr)) {
1057 Ctxt = RefInfo.Ctxt;
1058 if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
1059 DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
1060 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1061 dwarf::DW_FORM_ref_addr, Attr);
1062 return U.getRefAddrByteSize();
1066 if (!RefInfo.Clone) {
1067 assert(Ref > InputDIE.getOffset());
1068 // We haven't cloned this DIE yet. Just create an empty one and
1069 // store it. It'll get really cloned when we process it.
1070 RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
1072 NewRefDie = RefInfo.Clone;
1074 if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
1075 (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
1076 // We cannot currently rely on a DIEEntry to emit ref_addr
1077 // references, because the implementation calls back to DwarfDebug
1078 // to find the unit offset. (We don't have a DwarfDebug)
1079 // FIXME: we should be able to design DIEEntry reliance on
1080 // DwarfDebug away.
1081 uint64_t Attr;
1082 if (Ref < InputDIE.getOffset()) {
1083 // We must have already cloned that DIE.
1084 uint32_t NewRefOffset =
1085 RefUnit->getStartOffset() + NewRefDie->getOffset();
1086 Attr = NewRefOffset;
1087 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1088 dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
1089 } else {
1090 // A forward reference. Note and fixup later.
1091 Attr = 0xBADDEF;
1092 Unit.noteForwardReference(
1093 NewRefDie, RefUnit, Ctxt,
1094 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1095 dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
1097 return U.getRefAddrByteSize();
1100 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1101 dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
1102 return AttrSize;
1105 void DwarfLinker::DIECloner::cloneExpression(
1106 DataExtractor &Data, DWARFExpression Expression, const DebugMapObject &DMO,
1107 CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
1108 using Encoding = DWARFExpression::Operation::Encoding;
1110 uint64_t OpOffset = 0;
1111 for (auto &Op : Expression) {
1112 auto Description = Op.getDescription();
1113 // DW_OP_const_type is variable-length and has 3
1114 // operands. DWARFExpression thus far only supports 2.
1115 auto Op0 = Description.Op[0];
1116 auto Op1 = Description.Op[1];
1117 if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
1118 (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
1119 Linker.reportWarning("Unsupported DW_OP encoding.", DMO);
1121 if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
1122 (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
1123 // This code assumes that the other non-typeref operand fits into 1 byte.
1124 assert(OpOffset < Op.getEndOffset());
1125 uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
1126 assert(ULEBsize <= 16);
1128 // Copy over the operation.
1129 OutputBuffer.push_back(Op.getCode());
1130 uint64_t RefOffset;
1131 if (Op1 == Encoding::SizeNA) {
1132 RefOffset = Op.getRawOperand(0);
1133 } else {
1134 OutputBuffer.push_back(Op.getRawOperand(0));
1135 RefOffset = Op.getRawOperand(1);
1137 auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
1138 uint32_t RefIdx = Unit.getOrigUnit().getDIEIndex(RefDie);
1139 CompileUnit::DIEInfo &Info = Unit.getInfo(RefIdx);
1140 uint32_t Offset = 0;
1141 if (DIE *Clone = Info.Clone)
1142 Offset = Clone->getOffset();
1143 else
1144 Linker.reportWarning("base type ref doesn't point to DW_TAG_base_type.",
1145 DMO);
1146 uint8_t ULEB[16];
1147 unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
1148 if (RealSize > ULEBsize) {
1149 // Emit the generic type as a fallback.
1150 RealSize = encodeULEB128(0, ULEB, ULEBsize);
1151 Linker.reportWarning("base type ref doesn't fit.", DMO);
1153 assert(RealSize == ULEBsize && "padding failed");
1154 ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1155 OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1156 } else {
1157 // Copy over everything else unmodified.
1158 StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
1159 OutputBuffer.append(Bytes.begin(), Bytes.end());
1161 OpOffset = Op.getEndOffset();
1165 unsigned DwarfLinker::DIECloner::cloneBlockAttribute(
1166 DIE &Die, const DebugMapObject &DMO, CompileUnit &Unit,
1167 AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
1168 bool IsLittleEndian) {
1169 DIEValueList *Attr;
1170 DIEValue Value;
1171 DIELoc *Loc = nullptr;
1172 DIEBlock *Block = nullptr;
1173 if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1174 Loc = new (DIEAlloc) DIELoc;
1175 Linker.DIELocs.push_back(Loc);
1176 } else {
1177 Block = new (DIEAlloc) DIEBlock;
1178 Linker.DIEBlocks.push_back(Block);
1180 Attr = Loc ? static_cast<DIEValueList *>(Loc)
1181 : static_cast<DIEValueList *>(Block);
1183 if (Loc)
1184 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1185 dwarf::Form(AttrSpec.Form), Loc);
1186 else
1187 Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1188 dwarf::Form(AttrSpec.Form), Block);
1190 // If the block is a DWARF Expression, clone it into the temporary
1191 // buffer using cloneExpression(), otherwise copy the data directly.
1192 SmallVector<uint8_t, 32> Buffer;
1193 ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1194 if (DWARFAttribute::mayHaveLocationDescription(AttrSpec.Attr) &&
1195 (Val.isFormClass(DWARFFormValue::FC_Block) ||
1196 Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1197 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1198 DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1199 IsLittleEndian, OrigUnit.getAddressByteSize());
1200 DWARFExpression Expr(Data, OrigUnit.getVersion(),
1201 OrigUnit.getAddressByteSize());
1202 cloneExpression(Data, Expr, DMO, Unit, Buffer);
1203 Bytes = Buffer;
1205 for (auto Byte : Bytes)
1206 Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1207 dwarf::DW_FORM_data1, DIEInteger(Byte));
1209 // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1210 // the DIE class, this if could be replaced by
1211 // Attr->setSize(Bytes.size()).
1212 if (Linker.Streamer) {
1213 auto *AsmPrinter = &Linker.Streamer->getAsmPrinter();
1214 if (Loc)
1215 Loc->ComputeSize(AsmPrinter);
1216 else
1217 Block->ComputeSize(AsmPrinter);
1219 Die.addValue(DIEAlloc, Value);
1220 return AttrSize;
1223 unsigned DwarfLinker::DIECloner::cloneAddressAttribute(
1224 DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1225 const CompileUnit &Unit, AttributesInfo &Info) {
1226 uint64_t Addr = *Val.getAsAddress();
1228 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1229 if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1230 Info.HasLowPc = true;
1231 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1232 dwarf::Form(AttrSpec.Form), DIEInteger(Addr));
1233 return Unit.getOrigUnit().getAddressByteSize();
1236 if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1237 if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1238 Die.getTag() == dwarf::DW_TAG_lexical_block)
1239 // The low_pc of a block or inline subroutine might get
1240 // relocated because it happens to match the low_pc of the
1241 // enclosing subprogram. To prevent issues with that, always use
1242 // the low_pc from the input DIE if relocations have been applied.
1243 Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
1244 ? Info.OrigLowPc
1245 : Addr) +
1246 Info.PCOffset;
1247 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1248 Addr = Unit.getLowPc();
1249 if (Addr == std::numeric_limits<uint64_t>::max())
1250 return 0;
1252 Info.HasLowPc = true;
1253 } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1254 if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1255 if (uint64_t HighPc = Unit.getHighPc())
1256 Addr = HighPc;
1257 else
1258 return 0;
1259 } else
1260 // If we have a high_pc recorded for the input DIE, use
1261 // it. Otherwise (when no relocations where applied) just use the
1262 // one we just decoded.
1263 Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1266 Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1267 static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
1268 return Unit.getOrigUnit().getAddressByteSize();
1271 unsigned DwarfLinker::DIECloner::cloneScalarAttribute(
1272 DIE &Die, const DWARFDie &InputDIE, const DebugMapObject &DMO,
1273 CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1274 unsigned AttrSize, AttributesInfo &Info) {
1275 uint64_t Value;
1277 if (LLVM_UNLIKELY(Linker.Options.Update)) {
1278 if (auto OptionalValue = Val.getAsUnsignedConstant())
1279 Value = *OptionalValue;
1280 else if (auto OptionalValue = Val.getAsSignedConstant())
1281 Value = *OptionalValue;
1282 else if (auto OptionalValue = Val.getAsSectionOffset())
1283 Value = *OptionalValue;
1284 else {
1285 Linker.reportWarning(
1286 "Unsupported scalar attribute form. Dropping attribute.", DMO,
1287 &InputDIE);
1288 return 0;
1290 if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1291 Info.IsDeclaration = true;
1292 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1293 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1294 return AttrSize;
1297 if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1298 Die.getTag() == dwarf::DW_TAG_compile_unit) {
1299 if (Unit.getLowPc() == -1ULL)
1300 return 0;
1301 // Dwarf >= 4 high_pc is an size, not an address.
1302 Value = Unit.getHighPc() - Unit.getLowPc();
1303 } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1304 Value = *Val.getAsSectionOffset();
1305 else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1306 Value = *Val.getAsSignedConstant();
1307 else if (auto OptionalValue = Val.getAsUnsignedConstant())
1308 Value = *OptionalValue;
1309 else {
1310 Linker.reportWarning(
1311 "Unsupported scalar attribute form. Dropping attribute.", DMO,
1312 &InputDIE);
1313 return 0;
1315 PatchLocation Patch =
1316 Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1317 dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1318 if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
1319 Unit.noteRangeAttribute(Die, Patch);
1320 Info.HasRanges = true;
1323 // A more generic way to check for location attributes would be
1324 // nice, but it's very unlikely that any other attribute needs a
1325 // location list.
1326 // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1327 else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1328 AttrSpec.Attr == dwarf::DW_AT_frame_base)
1329 Unit.noteLocationAttribute(Patch, Info.PCOffset);
1330 else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1331 Info.IsDeclaration = true;
1333 return AttrSize;
1336 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1337 /// value \p Val, and add it to \p Die.
1338 /// \returns the size of the cloned attribute.
1339 unsigned DwarfLinker::DIECloner::cloneAttribute(
1340 DIE &Die, const DWARFDie &InputDIE, const DebugMapObject &DMO,
1341 CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
1342 const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
1343 bool IsLittleEndian) {
1344 const DWARFUnit &U = Unit.getOrigUnit();
1346 switch (AttrSpec.Form) {
1347 case dwarf::DW_FORM_strp:
1348 case dwarf::DW_FORM_string:
1349 return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
1350 case dwarf::DW_FORM_ref_addr:
1351 case dwarf::DW_FORM_ref1:
1352 case dwarf::DW_FORM_ref2:
1353 case dwarf::DW_FORM_ref4:
1354 case dwarf::DW_FORM_ref8:
1355 return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1356 DMO, Unit);
1357 case dwarf::DW_FORM_block:
1358 case dwarf::DW_FORM_block1:
1359 case dwarf::DW_FORM_block2:
1360 case dwarf::DW_FORM_block4:
1361 case dwarf::DW_FORM_exprloc:
1362 return cloneBlockAttribute(Die, DMO, Unit, AttrSpec, Val, AttrSize,
1363 IsLittleEndian);
1364 case dwarf::DW_FORM_addr:
1365 return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1366 case dwarf::DW_FORM_data1:
1367 case dwarf::DW_FORM_data2:
1368 case dwarf::DW_FORM_data4:
1369 case dwarf::DW_FORM_data8:
1370 case dwarf::DW_FORM_udata:
1371 case dwarf::DW_FORM_sdata:
1372 case dwarf::DW_FORM_sec_offset:
1373 case dwarf::DW_FORM_flag:
1374 case dwarf::DW_FORM_flag_present:
1375 return cloneScalarAttribute(Die, InputDIE, DMO, Unit, AttrSpec, Val,
1376 AttrSize, Info);
1377 default:
1378 Linker.reportWarning(
1379 "Unsupported attribute form in cloneAttribute. Dropping.", DMO,
1380 &InputDIE);
1383 return 0;
1386 /// Apply the valid relocations found by findValidRelocs() to
1387 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
1388 /// in the debug_info section.
1390 /// Like for findValidRelocs(), this function must be called with
1391 /// monotonic \p BaseOffset values.
1393 /// \returns whether any reloc has been applied.
1394 bool DwarfLinker::RelocationManager::applyValidRelocs(
1395 MutableArrayRef<char> Data, uint64_t BaseOffset, bool IsLittleEndian) {
1396 assert((NextValidReloc == 0 ||
1397 BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
1398 "BaseOffset should only be increasing.");
1399 if (NextValidReloc >= ValidRelocs.size())
1400 return false;
1402 // Skip relocs that haven't been applied.
1403 while (NextValidReloc < ValidRelocs.size() &&
1404 ValidRelocs[NextValidReloc].Offset < BaseOffset)
1405 ++NextValidReloc;
1407 bool Applied = false;
1408 uint64_t EndOffset = BaseOffset + Data.size();
1409 while (NextValidReloc < ValidRelocs.size() &&
1410 ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
1411 ValidRelocs[NextValidReloc].Offset < EndOffset) {
1412 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1413 assert(ValidReloc.Offset - BaseOffset < Data.size());
1414 assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
1415 char Buf[8];
1416 uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
1417 Value += ValidReloc.Addend;
1418 for (unsigned i = 0; i != ValidReloc.Size; ++i) {
1419 unsigned Index = IsLittleEndian ? i : (ValidReloc.Size - i - 1);
1420 Buf[i] = uint8_t(Value >> (Index * 8));
1422 assert(ValidReloc.Size <= sizeof(Buf));
1423 memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
1424 Applied = true;
1427 return Applied;
1430 static bool isObjCSelector(StringRef Name) {
1431 return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1432 (Name[1] == '[');
1435 void DwarfLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1436 const DIE *Die,
1437 DwarfStringPoolEntryRef Name,
1438 OffsetsStringPool &StringPool,
1439 bool SkipPubSection) {
1440 assert(isObjCSelector(Name.getString()) && "not an objc selector");
1441 // Objective C method or class function.
1442 // "- [Class(Category) selector :withArg ...]"
1443 StringRef ClassNameStart(Name.getString().drop_front(2));
1444 size_t FirstSpace = ClassNameStart.find(' ');
1445 if (FirstSpace == StringRef::npos)
1446 return;
1448 StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
1449 if (!SelectorStart.size())
1450 return;
1452 StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
1453 Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
1455 // Add an entry for the class name that points to this
1456 // method/class function.
1457 StringRef ClassName(ClassNameStart.data(), FirstSpace);
1458 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
1460 if (ClassName[ClassName.size() - 1] == ')') {
1461 size_t OpenParens = ClassName.find('(');
1462 if (OpenParens != StringRef::npos) {
1463 StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
1464 Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
1465 SkipPubSection);
1467 std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
1468 // FIXME: The missing space here may be a bug, but
1469 // dsymutil-classic also does it this way.
1470 MethodNameNoCategory.append(SelectorStart);
1471 Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
1472 SkipPubSection);
1477 static bool
1478 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
1479 uint16_t Tag, bool InDebugMap, bool SkipPC,
1480 bool InFunctionScope) {
1481 switch (AttrSpec.Attr) {
1482 default:
1483 return false;
1484 case dwarf::DW_AT_low_pc:
1485 case dwarf::DW_AT_high_pc:
1486 case dwarf::DW_AT_ranges:
1487 return SkipPC;
1488 case dwarf::DW_AT_location:
1489 case dwarf::DW_AT_frame_base:
1490 // FIXME: for some reason dsymutil-classic keeps the location attributes
1491 // when they are of block type (i.e. not location lists). This is totally
1492 // wrong for globals where we will keep a wrong address. It is mostly
1493 // harmless for locals, but there is no point in keeping these anyway when
1494 // the function wasn't linked.
1495 return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
1496 !InDebugMap)) &&
1497 !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
1501 DIE *DwarfLinker::DIECloner::cloneDIE(
1502 const DWARFDie &InputDIE, const DebugMapObject &DMO, CompileUnit &Unit,
1503 OffsetsStringPool &StringPool, int64_t PCOffset, uint32_t OutOffset,
1504 unsigned Flags, bool IsLittleEndian, DIE *Die) {
1505 DWARFUnit &U = Unit.getOrigUnit();
1506 unsigned Idx = U.getDIEIndex(InputDIE);
1507 CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1509 // Should the DIE appear in the output?
1510 if (!Unit.getInfo(Idx).Keep)
1511 return nullptr;
1513 uint64_t Offset = InputDIE.getOffset();
1514 assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1515 if (!Die) {
1516 // The DIE might have been already created by a forward reference
1517 // (see cloneDieReferenceAttribute()).
1518 if (!Info.Clone)
1519 Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1520 Die = Info.Clone;
1523 assert(Die->getTag() == InputDIE.getTag());
1524 Die->setOffset(OutOffset);
1525 if ((Unit.hasODR() || Unit.isClangModule()) && !Info.Incomplete &&
1526 Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
1527 Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
1528 !Info.Ctxt->getCanonicalDIEOffset()) {
1529 // We are about to emit a DIE that is the root of its own valid
1530 // DeclContext tree. Make the current offset the canonical offset
1531 // for this context.
1532 Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1535 // Extract and clone every attribute.
1536 DWARFDataExtractor Data = U.getDebugInfoExtractor();
1537 // Point to the next DIE (generally there is always at least a NULL
1538 // entry after the current one). If this is a lone
1539 // DW_TAG_compile_unit without any children, point to the next unit.
1540 uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1541 ? U.getDIEAtIndex(Idx + 1).getOffset()
1542 : U.getNextUnitOffset();
1543 AttributesInfo AttrInfo;
1545 // We could copy the data only if we need to apply a relocation to it. After
1546 // testing, it seems there is no performance downside to doing the copy
1547 // unconditionally, and it makes the code simpler.
1548 SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1549 Data =
1550 DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1551 // Modify the copy with relocated addresses.
1552 if (RelocMgr.applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
1553 // If we applied relocations, we store the value of high_pc that was
1554 // potentially stored in the input DIE. If high_pc is an address
1555 // (Dwarf version == 2), then it might have been relocated to a
1556 // totally unrelated value (because the end address in the object
1557 // file might be start address of another function which got moved
1558 // independently by the linker). The computation of the actual
1559 // high_pc value is done in cloneAddressAttribute().
1560 AttrInfo.OrigHighPc =
1561 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
1562 // Also store the low_pc. It might get relocated in an
1563 // inline_subprogram that happens at the beginning of its
1564 // inlining function.
1565 AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
1566 std::numeric_limits<uint64_t>::max());
1569 // Reset the Offset to 0 as we will be working on the local copy of
1570 // the data.
1571 Offset = 0;
1573 const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1574 Offset += getULEB128Size(Abbrev->getCode());
1576 // We are entering a subprogram. Get and propagate the PCOffset.
1577 if (Die->getTag() == dwarf::DW_TAG_subprogram)
1578 PCOffset = Info.AddrAdjust;
1579 AttrInfo.PCOffset = PCOffset;
1581 if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1582 Flags |= TF_InFunctionScope;
1583 if (!Info.InDebugMap && LLVM_LIKELY(!Options.Update))
1584 Flags |= TF_SkipPC;
1587 bool Copied = false;
1588 for (const auto &AttrSpec : Abbrev->attributes()) {
1589 if (LLVM_LIKELY(!Options.Update) &&
1590 shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
1591 Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
1592 DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1593 U.getFormParams());
1594 // FIXME: dsymutil-classic keeps the old abbreviation around
1595 // even if it's not used. We can remove this (and the copyAbbrev
1596 // helper) as soon as bit-for-bit compatibility is not a goal anymore.
1597 if (!Copied) {
1598 copyAbbrev(*InputDIE.getAbbreviationDeclarationPtr(), Unit.hasODR());
1599 Copied = true;
1601 continue;
1604 DWARFFormValue Val(AttrSpec.Form);
1605 uint64_t AttrSize = Offset;
1606 Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1607 AttrSize = Offset - AttrSize;
1609 OutOffset += cloneAttribute(*Die, InputDIE, DMO, Unit, StringPool, Val,
1610 AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
1613 // Look for accelerator entries.
1614 uint16_t Tag = InputDIE.getTag();
1615 // FIXME: This is slightly wrong. An inline_subroutine without a
1616 // low_pc, but with AT_ranges might be interesting to get into the
1617 // accelerator tables too. For now stick with dsymutil's behavior.
1618 if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
1619 Tag != dwarf::DW_TAG_compile_unit &&
1620 getDIENames(InputDIE, AttrInfo, StringPool,
1621 Tag != dwarf::DW_TAG_inlined_subroutine)) {
1622 if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
1623 Unit.addNameAccelerator(Die, AttrInfo.MangledName,
1624 Tag == dwarf::DW_TAG_inlined_subroutine);
1625 if (AttrInfo.Name) {
1626 if (AttrInfo.NameWithoutTemplate)
1627 Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
1628 /* SkipPubSection */ true);
1629 Unit.addNameAccelerator(Die, AttrInfo.Name,
1630 Tag == dwarf::DW_TAG_inlined_subroutine);
1632 if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
1633 addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
1634 /* SkipPubSection =*/true);
1636 } else if (Tag == dwarf::DW_TAG_namespace) {
1637 if (!AttrInfo.Name)
1638 AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
1639 Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1640 } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
1641 getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
1642 AttrInfo.Name.getString()[0]) {
1643 uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, DMO);
1644 uint64_t RuntimeLang =
1645 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
1646 .getValueOr(0);
1647 bool ObjCClassIsImplementation =
1648 (RuntimeLang == dwarf::DW_LANG_ObjC ||
1649 RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
1650 dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
1651 .getValueOr(0);
1652 Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
1653 Hash);
1656 // Determine whether there are any children that we want to keep.
1657 bool HasChildren = false;
1658 for (auto Child : InputDIE.children()) {
1659 unsigned Idx = U.getDIEIndex(Child);
1660 if (Unit.getInfo(Idx).Keep) {
1661 HasChildren = true;
1662 break;
1666 DIEAbbrev NewAbbrev = Die->generateAbbrev();
1667 if (HasChildren)
1668 NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1669 // Assign a permanent abbrev number
1670 Linker.AssignAbbrev(NewAbbrev);
1671 Die->setAbbrevNumber(NewAbbrev.getNumber());
1673 // Add the size of the abbreviation number to the output offset.
1674 OutOffset += getULEB128Size(Die->getAbbrevNumber());
1676 if (!HasChildren) {
1677 // Update our size.
1678 Die->setSize(OutOffset - Die->getOffset());
1679 return Die;
1682 // Recursively clone children.
1683 for (auto Child : InputDIE.children()) {
1684 if (DIE *Clone = cloneDIE(Child, DMO, Unit, StringPool, PCOffset, OutOffset,
1685 Flags, IsLittleEndian)) {
1686 Die->addChild(Clone);
1687 OutOffset = Clone->getOffset() + Clone->getSize();
1691 // Account for the end of children marker.
1692 OutOffset += sizeof(int8_t);
1693 // Update our size.
1694 Die->setSize(OutOffset - Die->getOffset());
1695 return Die;
1698 /// Patch the input object file relevant debug_ranges entries
1699 /// and emit them in the output file. Update the relevant attributes
1700 /// to point at the new entries.
1701 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
1702 DWARFContext &OrigDwarf,
1703 const DebugMapObject &DMO) const {
1704 DWARFDebugRangeList RangeList;
1705 const auto &FunctionRanges = Unit.getFunctionRanges();
1706 unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1707 DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
1708 OrigDwarf.getDWARFObj().getRangesSection(),
1709 OrigDwarf.isLittleEndian(), AddressSize);
1710 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1711 DWARFUnit &OrigUnit = Unit.getOrigUnit();
1712 auto OrigUnitDie = OrigUnit.getUnitDIE(false);
1713 uint64_t OrigLowPc =
1714 dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
1715 // Ranges addresses are based on the unit's low_pc. Compute the
1716 // offset we need to apply to adapt to the new unit's low_pc.
1717 int64_t UnitPcOffset = 0;
1718 if (OrigLowPc != -1ULL)
1719 UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1721 for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1722 uint64_t Offset = RangeAttribute.get();
1723 RangeAttribute.set(Streamer->getRangesSectionSize());
1724 if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
1725 llvm::consumeError(std::move(E));
1726 reportWarning("invalid range list ignored.", DMO);
1727 RangeList.clear();
1729 const auto &Entries = RangeList.getEntries();
1730 if (!Entries.empty()) {
1731 const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1733 if (CurrRange == InvalidRange ||
1734 First.StartAddress + OrigLowPc < CurrRange.start() ||
1735 First.StartAddress + OrigLowPc >= CurrRange.stop()) {
1736 CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1737 if (CurrRange == InvalidRange ||
1738 CurrRange.start() > First.StartAddress + OrigLowPc) {
1739 reportWarning("no mapping for range.", DMO);
1740 continue;
1745 Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
1746 AddressSize);
1750 /// Generate the debug_aranges entries for \p Unit and if the
1751 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1752 /// contribution for this attribute.
1753 /// FIXME: this could actually be done right in patchRangesForUnit,
1754 /// but for the sake of initial bit-for-bit compatibility with legacy
1755 /// dsymutil, we have to do it in a delayed pass.
1756 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
1757 auto Attr = Unit.getUnitRangesAttribute();
1758 if (Attr)
1759 Attr->set(Streamer->getRangesSectionSize());
1760 Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
1763 /// Insert the new line info sequence \p Seq into the current
1764 /// set of already linked line info \p Rows.
1765 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1766 std::vector<DWARFDebugLine::Row> &Rows) {
1767 if (Seq.empty())
1768 return;
1770 if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1771 Rows.insert(Rows.end(), Seq.begin(), Seq.end());
1772 Seq.clear();
1773 return;
1776 object::SectionedAddress Front = Seq.front().Address;
1777 auto InsertPoint = partition_point(
1778 Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
1780 // FIXME: this only removes the unneeded end_sequence if the
1781 // sequences have been inserted in order. Using a global sort like
1782 // described in patchLineTableForUnit() and delaying the end_sequene
1783 // elimination to emitLineTableForUnit() we can get rid of all of them.
1784 if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1785 InsertPoint->EndSequence) {
1786 *InsertPoint = Seq.front();
1787 Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1788 } else {
1789 Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1792 Seq.clear();
1795 static void patchStmtList(DIE &Die, DIEInteger Offset) {
1796 for (auto &V : Die.values())
1797 if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1798 V = DIEValue(V.getAttribute(), V.getForm(), Offset);
1799 return;
1802 llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
1805 /// Extract the line table for \p Unit from \p OrigDwarf, and
1806 /// recreate a relocated version of these for the address ranges that
1807 /// are present in the binary.
1808 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
1809 DWARFContext &OrigDwarf,
1810 RangesTy &Ranges,
1811 const DebugMapObject &DMO) {
1812 DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
1813 auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1814 if (!StmtList)
1815 return;
1817 // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1818 if (auto *OutputDIE = Unit.getOutputUnitDIE())
1819 patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
1821 // Parse the original line info for the unit.
1822 DWARFDebugLine::LineTable LineTable;
1823 uint64_t StmtOffset = *StmtList;
1824 DWARFDataExtractor LineExtractor(
1825 OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
1826 OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
1827 if (Options.Translator)
1828 return Streamer->translateLineTable(LineExtractor, StmtOffset);
1830 Error Err = LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
1831 &Unit.getOrigUnit(), DWARFContext::dumpWarning);
1832 DWARFContext::dumpWarning(std::move(Err));
1834 // This vector is the output line table.
1835 std::vector<DWARFDebugLine::Row> NewRows;
1836 NewRows.reserve(LineTable.Rows.size());
1838 // Current sequence of rows being extracted, before being inserted
1839 // in NewRows.
1840 std::vector<DWARFDebugLine::Row> Seq;
1841 const auto &FunctionRanges = Unit.getFunctionRanges();
1842 auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1844 // FIXME: This logic is meant to generate exactly the same output as
1845 // Darwin's classic dsymutil. There is a nicer way to implement this
1846 // by simply putting all the relocated line info in NewRows and simply
1847 // sorting NewRows before passing it to emitLineTableForUnit. This
1848 // should be correct as sequences for a function should stay
1849 // together in the sorted output. There are a few corner cases that
1850 // look suspicious though, and that required to implement the logic
1851 // this way. Revisit that once initial validation is finished.
1853 // Iterate over the object file line info and extract the sequences
1854 // that correspond to linked functions.
1855 for (auto &Row : LineTable.Rows) {
1856 // Check whether we stepped out of the range. The range is
1857 // half-open, but consider accept the end address of the range if
1858 // it is marked as end_sequence in the input (because in that
1859 // case, the relocation offset is accurate and that entry won't
1860 // serve as the start of another function).
1861 if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() ||
1862 Row.Address.Address > CurrRange.stop() ||
1863 (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) {
1864 // We just stepped out of a known range. Insert a end_sequence
1865 // corresponding to the end of the range.
1866 uint64_t StopAddress = CurrRange != InvalidRange
1867 ? CurrRange.stop() + CurrRange.value()
1868 : -1ULL;
1869 CurrRange = FunctionRanges.find(Row.Address.Address);
1870 bool CurrRangeValid =
1871 CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address;
1872 if (!CurrRangeValid) {
1873 CurrRange = InvalidRange;
1874 if (StopAddress != -1ULL) {
1875 // Try harder by looking in the DebugMapObject function
1876 // ranges map. There are corner cases where this finds a
1877 // valid entry. It's unclear if this is right or wrong, but
1878 // for now do as dsymutil.
1879 // FIXME: Understand exactly what cases this addresses and
1880 // potentially remove it along with the Ranges map.
1881 auto Range = Ranges.lower_bound(Row.Address.Address);
1882 if (Range != Ranges.begin() && Range != Ranges.end())
1883 --Range;
1885 if (Range != Ranges.end() && Range->first <= Row.Address.Address &&
1886 Range->second.HighPC >= Row.Address.Address) {
1887 StopAddress = Row.Address.Address + Range->second.Offset;
1891 if (StopAddress != -1ULL && !Seq.empty()) {
1892 // Insert end sequence row with the computed end address, but
1893 // the same line as the previous one.
1894 auto NextLine = Seq.back();
1895 NextLine.Address.Address = StopAddress;
1896 NextLine.EndSequence = 1;
1897 NextLine.PrologueEnd = 0;
1898 NextLine.BasicBlock = 0;
1899 NextLine.EpilogueBegin = 0;
1900 Seq.push_back(NextLine);
1901 insertLineSequence(Seq, NewRows);
1904 if (!CurrRangeValid)
1905 continue;
1908 // Ignore empty sequences.
1909 if (Row.EndSequence && Seq.empty())
1910 continue;
1912 // Relocate row address and add it to the current sequence.
1913 Row.Address.Address += CurrRange.value();
1914 Seq.emplace_back(Row);
1916 if (Row.EndSequence)
1917 insertLineSequence(Seq, NewRows);
1920 // Finished extracting, now emit the line tables.
1921 // FIXME: LLVM hard-codes its prologue values. We just copy the
1922 // prologue over and that works because we act as both producer and
1923 // consumer. It would be nicer to have a real configurable line
1924 // table emitter.
1925 if (LineTable.Prologue.getVersion() < 2 ||
1926 LineTable.Prologue.getVersion() > 5 ||
1927 LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
1928 LineTable.Prologue.OpcodeBase > 13)
1929 reportWarning("line table parameters mismatch. Cannot emit.", DMO);
1930 else {
1931 uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
1932 // DWARF v5 has an extra 2 bytes of information before the header_length
1933 // field.
1934 if (LineTable.Prologue.getVersion() == 5)
1935 PrologueEnd += 2;
1936 StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
1937 MCDwarfLineTableParams Params;
1938 Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1939 Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1940 Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1941 Streamer->emitLineTableForUnit(Params,
1942 LineData.slice(*StmtList + 4, PrologueEnd),
1943 LineTable.Prologue.MinInstLength, NewRows,
1944 Unit.getOrigUnit().getAddressByteSize());
1948 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
1949 switch (Options.TheAccelTableKind) {
1950 case AccelTableKind::Apple:
1951 emitAppleAcceleratorEntriesForUnit(Unit);
1952 break;
1953 case AccelTableKind::Dwarf:
1954 emitDwarfAcceleratorEntriesForUnit(Unit);
1955 break;
1956 case AccelTableKind::Default:
1957 llvm_unreachable("The default must be updated to a concrete value.");
1958 break;
1962 void DwarfLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
1963 // Add namespaces.
1964 for (const auto &Namespace : Unit.getNamespaces())
1965 AppleNamespaces.addName(Namespace.Name,
1966 Namespace.Die->getOffset() + Unit.getStartOffset());
1968 /// Add names.
1969 if (!Options.Minimize)
1970 Streamer->emitPubNamesForUnit(Unit);
1971 for (const auto &Pubname : Unit.getPubnames())
1972 AppleNames.addName(Pubname.Name,
1973 Pubname.Die->getOffset() + Unit.getStartOffset());
1975 /// Add types.
1976 if (!Options.Minimize)
1977 Streamer->emitPubTypesForUnit(Unit);
1978 for (const auto &Pubtype : Unit.getPubtypes())
1979 AppleTypes.addName(
1980 Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
1981 Pubtype.Die->getTag(),
1982 Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1983 : 0,
1984 Pubtype.QualifiedNameHash);
1986 /// Add ObjC names.
1987 for (const auto &ObjC : Unit.getObjC())
1988 AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
1991 void DwarfLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
1992 for (const auto &Namespace : Unit.getNamespaces())
1993 DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
1994 Namespace.Die->getTag(), Unit.getUniqueID());
1995 for (const auto &Pubname : Unit.getPubnames())
1996 DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
1997 Pubname.Die->getTag(), Unit.getUniqueID());
1998 for (const auto &Pubtype : Unit.getPubtypes())
1999 DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
2000 Pubtype.Die->getTag(), Unit.getUniqueID());
2003 /// Read the frame info stored in the object, and emit the
2004 /// patched frame descriptions for the linked binary.
2006 /// This is actually pretty easy as the data of the CIEs and FDEs can
2007 /// be considered as black boxes and moved as is. The only thing to do
2008 /// is to patch the addresses in the headers.
2009 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2010 RangesTy &Ranges,
2011 DWARFContext &OrigDwarf,
2012 unsigned AddrSize) {
2013 StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
2014 if (FrameData.empty())
2015 return;
2017 DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2018 uint64_t InputOffset = 0;
2020 // Store the data of the CIEs defined in this object, keyed by their
2021 // offsets.
2022 DenseMap<uint64_t, StringRef> LocalCIES;
2024 while (Data.isValidOffset(InputOffset)) {
2025 uint64_t EntryOffset = InputOffset;
2026 uint32_t InitialLength = Data.getU32(&InputOffset);
2027 if (InitialLength == 0xFFFFFFFF)
2028 return reportWarning("Dwarf64 bits no supported", DMO);
2030 uint32_t CIEId = Data.getU32(&InputOffset);
2031 if (CIEId == 0xFFFFFFFF) {
2032 // This is a CIE, store it.
2033 StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2034 LocalCIES[EntryOffset] = CIEData;
2035 // The -4 is to account for the CIEId we just read.
2036 InputOffset += InitialLength - 4;
2037 continue;
2040 uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2042 // Some compilers seem to emit frame info that doesn't start at
2043 // the function entry point, thus we can't just lookup the address
2044 // in the debug map. Use the linker's range map to see if the FDE
2045 // describes something that we can relocate.
2046 auto Range = Ranges.upper_bound(Loc);
2047 if (Range != Ranges.begin())
2048 --Range;
2049 if (Range == Ranges.end() || Range->first > Loc ||
2050 Range->second.HighPC <= Loc) {
2051 // The +4 is to account for the size of the InitialLength field itself.
2052 InputOffset = EntryOffset + InitialLength + 4;
2053 continue;
2056 // This is an FDE, and we have a mapping.
2057 // Have we already emitted a corresponding CIE?
2058 StringRef CIEData = LocalCIES[CIEId];
2059 if (CIEData.empty())
2060 return reportWarning("Inconsistent debug_frame content. Dropping.", DMO);
2062 // Look if we already emitted a CIE that corresponds to the
2063 // referenced one (the CIE data is the key of that lookup).
2064 auto IteratorInserted = EmittedCIEs.insert(
2065 std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2066 // If there is no CIE yet for this ID, emit it.
2067 if (IteratorInserted.second ||
2068 // FIXME: dsymutil-classic only caches the last used CIE for
2069 // reuse. Mimic that behavior for now. Just removing that
2070 // second half of the condition and the LastCIEOffset variable
2071 // makes the code DTRT.
2072 LastCIEOffset != IteratorInserted.first->getValue()) {
2073 LastCIEOffset = Streamer->getFrameSectionSize();
2074 IteratorInserted.first->getValue() = LastCIEOffset;
2075 Streamer->emitCIE(CIEData);
2078 // Emit the FDE with updated address and CIE pointer.
2079 // (4 + AddrSize) is the size of the CIEId + initial_location
2080 // fields that will get reconstructed by emitFDE().
2081 unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
2082 Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
2083 Loc + Range->second.Offset,
2084 FrameData.substr(InputOffset, FDERemainingBytes));
2085 InputOffset += FDERemainingBytes;
2089 void DwarfLinker::DIECloner::copyAbbrev(
2090 const DWARFAbbreviationDeclaration &Abbrev, bool hasODR) {
2091 DIEAbbrev Copy(dwarf::Tag(Abbrev.getTag()),
2092 dwarf::Form(Abbrev.hasChildren()));
2094 for (const auto &Attr : Abbrev.attributes()) {
2095 uint16_t Form = Attr.Form;
2096 if (hasODR && isODRAttribute(Attr.Attr))
2097 Form = dwarf::DW_FORM_ref_addr;
2098 Copy.AddAttribute(dwarf::Attribute(Attr.Attr), dwarf::Form(Form));
2101 Linker.AssignAbbrev(Copy);
2104 uint32_t
2105 DwarfLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE, CompileUnit &U,
2106 const DebugMapObject &DMO,
2107 int ChildRecurseDepth) {
2108 const char *Name = nullptr;
2109 DWARFUnit *OrigUnit = &U.getOrigUnit();
2110 CompileUnit *CU = &U;
2111 Optional<DWARFFormValue> Ref;
2113 while (1) {
2114 if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
2115 Name = CurrentName;
2117 if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
2118 !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
2119 break;
2121 if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
2122 break;
2124 CompileUnit *RefCU;
2125 if (auto RefDIE =
2126 resolveDIEReference(Linker, DMO, CompileUnits, *Ref, DIE, RefCU)) {
2127 CU = RefCU;
2128 OrigUnit = &RefCU->getOrigUnit();
2129 DIE = RefDIE;
2133 unsigned Idx = OrigUnit->getDIEIndex(DIE);
2134 if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
2135 Name = "(anonymous namespace)";
2137 if (CU->getInfo(Idx).ParentIdx == 0 ||
2138 // FIXME: dsymutil-classic compatibility. Ignore modules.
2139 CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
2140 dwarf::DW_TAG_module)
2141 return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
2143 DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
2144 return djbHash(
2145 (Name ? Name : ""),
2146 djbHash((Name ? "::" : ""),
2147 hashFullyQualifiedName(Die, *CU, DMO, ++ChildRecurseDepth)));
2150 static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
2151 auto DwoId = dwarf::toUnsigned(
2152 CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2153 if (DwoId)
2154 return *DwoId;
2155 return 0;
2158 bool DwarfLinker::registerModuleReference(
2159 DWARFDie CUDie, const DWARFUnit &Unit, DebugMap &ModuleMap,
2160 const DebugMapObject &DMO, RangesTy &Ranges, OffsetsStringPool &StringPool,
2161 UniquingStringPool &UniquingStringPool, DeclContextTree &ODRContexts,
2162 uint64_t ModulesEndOffset, unsigned &UnitID, bool IsLittleEndian,
2163 unsigned Indent, bool Quiet) {
2164 std::string PCMfile = dwarf::toString(
2165 CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2166 if (PCMfile.empty())
2167 return false;
2169 // Clang module DWARF skeleton CUs abuse this for the path to the module.
2170 uint64_t DwoId = getDwoId(CUDie, Unit);
2172 std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2173 if (Name.empty()) {
2174 if (!Quiet)
2175 reportWarning("Anonymous module skeleton CU for " + PCMfile, DMO);
2176 return true;
2179 if (!Quiet && Options.Verbose) {
2180 outs().indent(Indent);
2181 outs() << "Found clang module reference " << PCMfile;
2184 auto Cached = ClangModules.find(PCMfile);
2185 if (Cached != ClangModules.end()) {
2186 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2187 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2188 // ASTFileSignatures will change randomly when a module is rebuilt.
2189 if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2190 reportWarning(Twine("hash mismatch: this object file was built against a "
2191 "different version of the module ") +
2192 PCMfile,
2193 DMO);
2194 if (!Quiet && Options.Verbose)
2195 outs() << " [cached].\n";
2196 return true;
2198 if (!Quiet && Options.Verbose)
2199 outs() << " ...\n";
2201 // Cyclic dependencies are disallowed by Clang, but we still
2202 // shouldn't run into an infinite loop, so mark it as processed now.
2203 ClangModules.insert({PCMfile, DwoId});
2205 if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, ModuleMap, DMO,
2206 Ranges, StringPool, UniquingStringPool,
2207 ODRContexts, ModulesEndOffset, UnitID,
2208 IsLittleEndian, Indent + 2, Quiet)) {
2209 consumeError(std::move(E));
2210 return false;
2212 return true;
2215 ErrorOr<const object::ObjectFile &>
2216 DwarfLinker::loadObject(const DebugMapObject &Obj, const DebugMap &Map) {
2217 auto ObjectEntry =
2218 BinHolder.getObjectEntry(Obj.getObjectFilename(), Obj.getTimestamp());
2219 if (!ObjectEntry) {
2220 auto Err = ObjectEntry.takeError();
2221 reportWarning(
2222 Twine(Obj.getObjectFilename()) + ": " + toString(std::move(Err)), Obj);
2223 return errorToErrorCode(std::move(Err));
2226 auto Object = ObjectEntry->getObject(Map.getTriple());
2227 if (!Object) {
2228 auto Err = Object.takeError();
2229 reportWarning(
2230 Twine(Obj.getObjectFilename()) + ": " + toString(std::move(Err)), Obj);
2231 return errorToErrorCode(std::move(Err));
2234 return *Object;
2237 Error DwarfLinker::loadClangModule(
2238 DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
2239 DebugMap &ModuleMap, const DebugMapObject &DMO, RangesTy &Ranges,
2240 OffsetsStringPool &StringPool, UniquingStringPool &UniquingStringPool,
2241 DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
2242 bool IsLittleEndian, unsigned Indent, bool Quiet) {
2243 /// Using a SmallString<0> because loadClangModule() is recursive.
2244 SmallString<0> Path(Options.PrependPath);
2245 if (sys::path::is_relative(Filename))
2246 resolveRelativeObjectPath(Path, CUDie);
2247 sys::path::append(Path, Filename);
2248 // Don't use the cached binary holder because we have no thread-safety
2249 // guarantee and the lifetime is limited.
2250 auto &Obj = ModuleMap.addDebugMapObject(
2251 Path, sys::TimePoint<std::chrono::seconds>(), MachO::N_OSO);
2252 auto ErrOrObj = loadObject(Obj, ModuleMap);
2253 if (!ErrOrObj) {
2254 // Try and emit more helpful warnings by applying some heuristics.
2255 StringRef ObjFile = DMO.getObjectFilename();
2256 bool isClangModule = sys::path::extension(Filename).equals(".pcm");
2257 bool isArchive = ObjFile.endswith(")");
2258 if (isClangModule) {
2259 StringRef ModuleCacheDir = sys::path::parent_path(Path);
2260 if (sys::fs::exists(ModuleCacheDir)) {
2261 // If the module's parent directory exists, we assume that the module
2262 // cache has expired and was pruned by clang. A more adventurous
2263 // dsymutil would invoke clang to rebuild the module now.
2264 if (!ModuleCacheHintDisplayed) {
2265 WithColor::note() << "The clang module cache may have expired since "
2266 "this object file was built. Rebuilding the "
2267 "object file will rebuild the module cache.\n";
2268 ModuleCacheHintDisplayed = true;
2270 } else if (isArchive) {
2271 // If the module cache directory doesn't exist at all and the object
2272 // file is inside a static library, we assume that the static library
2273 // was built on a different machine. We don't want to discourage module
2274 // debugging for convenience libraries within a project though.
2275 if (!ArchiveHintDisplayed) {
2276 WithColor::note()
2277 << "Linking a static library that was built with "
2278 "-gmodules, but the module cache was not found. "
2279 "Redistributable static libraries should never be "
2280 "built with module debugging enabled. The debug "
2281 "experience will be degraded due to incomplete "
2282 "debug information.\n";
2283 ArchiveHintDisplayed = true;
2287 return Error::success();
2290 std::unique_ptr<CompileUnit> Unit;
2292 // Setup access to the debug info.
2293 auto DwarfContext = DWARFContext::create(*ErrOrObj);
2294 RelocationManager RelocMgr(*this);
2296 for (const auto &CU : DwarfContext->compile_units()) {
2297 updateDwarfVersion(CU->getVersion());
2298 // Recursively get all modules imported by this one.
2299 auto CUDie = CU->getUnitDIE(false);
2300 if (!CUDie)
2301 continue;
2302 if (!registerModuleReference(CUDie, *CU, ModuleMap, DMO, Ranges, StringPool,
2303 UniquingStringPool, ODRContexts,
2304 ModulesEndOffset, UnitID, IsLittleEndian,
2305 Indent, Quiet)) {
2306 if (Unit) {
2307 std::string Err =
2308 (Filename +
2309 ": Clang modules are expected to have exactly 1 compile unit.\n")
2310 .str();
2311 error(Err);
2312 return make_error<StringError>(Err, inconvertibleErrorCode());
2314 // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2315 // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2316 // ASTFileSignatures will change randomly when a module is rebuilt.
2317 uint64_t PCMDwoId = getDwoId(CUDie, *CU);
2318 if (PCMDwoId != DwoId) {
2319 if (!Quiet && Options.Verbose)
2320 reportWarning(
2321 Twine("hash mismatch: this object file was built against a "
2322 "different version of the module ") +
2323 Filename,
2324 DMO);
2325 // Update the cache entry with the DwoId of the module loaded from disk.
2326 ClangModules[Filename] = PCMDwoId;
2329 // Add this module.
2330 Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
2331 ModuleName);
2332 Unit->setHasInterestingContent();
2333 analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(),
2334 UniquingStringPool, ODRContexts, ModulesEndOffset,
2335 ParseableSwiftInterfaces,
2336 [&](const Twine &Warning, const DWARFDie &DIE) {
2337 reportWarning(Warning, DMO, &DIE);
2339 // Keep everything.
2340 Unit->markEverythingAsKept();
2343 if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
2344 return Error::success();
2345 if (!Quiet && Options.Verbose) {
2346 outs().indent(Indent);
2347 outs() << "cloning .debug_info from " << Filename << "\n";
2350 UnitListTy CompileUnits;
2351 CompileUnits.push_back(std::move(Unit));
2352 DIECloner(*this, RelocMgr, DIEAlloc, CompileUnits, Options)
2353 .cloneAllCompileUnits(*DwarfContext, DMO, Ranges, StringPool,
2354 IsLittleEndian);
2355 return Error::success();
2358 void DwarfLinker::DIECloner::cloneAllCompileUnits(
2359 DWARFContext &DwarfContext, const DebugMapObject &DMO, RangesTy &Ranges,
2360 OffsetsStringPool &StringPool, bool IsLittleEndian) {
2361 if (!Linker.Streamer)
2362 return;
2364 for (auto &CurrentUnit : CompileUnits) {
2365 auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2366 CurrentUnit->setStartOffset(Linker.OutputDebugInfoSize);
2367 if (!InputDIE) {
2368 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
2369 continue;
2371 if (CurrentUnit->getInfo(0).Keep) {
2372 // Clone the InputDIE into your Unit DIE in our compile unit since it
2373 // already has a DIE inside of it.
2374 CurrentUnit->createOutputDIE();
2375 cloneDIE(InputDIE, DMO, *CurrentUnit, StringPool, 0 /* PC offset */,
2376 11 /* Unit Header size */, 0, IsLittleEndian,
2377 CurrentUnit->getOutputUnitDIE());
2380 Linker.OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset();
2382 if (Linker.Options.NoOutput)
2383 continue;
2385 // FIXME: for compatibility with the classic dsymutil, we emit
2386 // an empty line table for the unit, even if the unit doesn't
2387 // actually exist in the DIE tree.
2388 if (LLVM_LIKELY(!Linker.Options.Update) || Linker.Options.Translator)
2389 Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, Ranges, DMO);
2391 Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2393 if (LLVM_UNLIKELY(Linker.Options.Update))
2394 continue;
2396 Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, DMO);
2397 auto ProcessExpr = [&](StringRef Bytes, SmallVectorImpl<uint8_t> &Buffer) {
2398 DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2399 DataExtractor Data(Bytes, IsLittleEndian, OrigUnit.getAddressByteSize());
2400 cloneExpression(Data,
2401 DWARFExpression(Data, OrigUnit.getVersion(),
2402 OrigUnit.getAddressByteSize()),
2403 DMO, *CurrentUnit, Buffer);
2405 Linker.Streamer->emitLocationsForUnit(*CurrentUnit, DwarfContext,
2406 ProcessExpr);
2409 if (Linker.Options.NoOutput)
2410 return;
2412 // Emit all the compile unit's debug information.
2413 for (auto &CurrentUnit : CompileUnits) {
2414 if (LLVM_LIKELY(!Linker.Options.Update))
2415 Linker.generateUnitRanges(*CurrentUnit);
2417 CurrentUnit->fixupForwardReferences();
2419 if (!CurrentUnit->getOutputUnitDIE())
2420 continue;
2422 Linker.Streamer->emitCompileUnitHeader(*CurrentUnit);
2423 Linker.Streamer->emitDIE(*CurrentUnit->getOutputUnitDIE());
2427 void DwarfLinker::updateAccelKind(DWARFContext &Dwarf) {
2428 if (Options.TheAccelTableKind != AccelTableKind::Default)
2429 return;
2431 auto &DwarfObj = Dwarf.getDWARFObj();
2433 if (!AtLeastOneDwarfAccelTable &&
2434 (!DwarfObj.getAppleNamesSection().Data.empty() ||
2435 !DwarfObj.getAppleTypesSection().Data.empty() ||
2436 !DwarfObj.getAppleNamespacesSection().Data.empty() ||
2437 !DwarfObj.getAppleObjCSection().Data.empty())) {
2438 AtLeastOneAppleAccelTable = true;
2441 if (!AtLeastOneDwarfAccelTable &&
2442 !DwarfObj.getNamesSection().Data.empty()) {
2443 AtLeastOneDwarfAccelTable = true;
2447 bool DwarfLinker::emitPaperTrailWarnings(const DebugMapObject &DMO,
2448 const DebugMap &Map,
2449 OffsetsStringPool &StringPool) {
2450 if (DMO.getWarnings().empty() || !DMO.empty())
2451 return false;
2453 Streamer->switchToDebugInfoSection(/* Version */ 2);
2454 DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
2455 CUDie->setOffset(11);
2456 StringRef Producer = StringPool.internString("dsymutil");
2457 StringRef File = StringPool.internString(DMO.getObjectFilename());
2458 CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
2459 DIEInteger(StringPool.getStringOffset(Producer)));
2460 DIEBlock *String = new (DIEAlloc) DIEBlock();
2461 DIEBlocks.push_back(String);
2462 for (auto &C : File)
2463 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2464 DIEInteger(C));
2465 String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2466 DIEInteger(0));
2468 CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
2469 for (const auto &Warning : DMO.getWarnings()) {
2470 DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
2471 ConstDie.addValue(
2472 DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
2473 DIEInteger(StringPool.getStringOffset("dsymutil_warning")));
2474 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
2475 DIEInteger(1));
2476 ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
2477 DIEInteger(StringPool.getStringOffset(Warning)));
2479 unsigned Size = 4 /* FORM_strp */ + File.size() + 1 +
2480 DMO.getWarnings().size() * (4 + 1 + 4) +
2481 1 /* End of children */;
2482 DIEAbbrev Abbrev = CUDie->generateAbbrev();
2483 AssignAbbrev(Abbrev);
2484 CUDie->setAbbrevNumber(Abbrev.getNumber());
2485 Size += getULEB128Size(Abbrev.getNumber());
2486 // Abbreviation ordering needed for classic compatibility.
2487 for (auto &Child : CUDie->children()) {
2488 Abbrev = Child.generateAbbrev();
2489 AssignAbbrev(Abbrev);
2490 Child.setAbbrevNumber(Abbrev.getNumber());
2491 Size += getULEB128Size(Abbrev.getNumber());
2493 CUDie->setSize(Size);
2494 auto &Asm = Streamer->getAsmPrinter();
2495 Asm.emitInt32(11 + CUDie->getSize() - 4);
2496 Asm.emitInt16(2);
2497 Asm.emitInt32(0);
2498 Asm.emitInt8(Map.getTriple().isArch64Bit() ? 8 : 4);
2499 Streamer->emitDIE(*CUDie);
2500 OutputDebugInfoSize += 11 /* Header */ + Size;
2502 return true;
2505 static Error copySwiftInterfaces(
2506 const std::map<std::string, std::string> &ParseableSwiftInterfaces,
2507 StringRef Architecture, const LinkOptions &Options) {
2508 std::error_code EC;
2509 SmallString<128> InputPath;
2510 SmallString<128> Path;
2511 sys::path::append(Path, *Options.ResourceDir, "Swift", Architecture);
2512 if ((EC = sys::fs::create_directories(Path.str(), true,
2513 sys::fs::perms::all_all)))
2514 return make_error<StringError>(
2515 "cannot create directory: " + toString(errorCodeToError(EC)), EC);
2516 unsigned BaseLength = Path.size();
2518 for (auto &I : ParseableSwiftInterfaces) {
2519 StringRef ModuleName = I.first;
2520 StringRef InterfaceFile = I.second;
2521 if (!Options.PrependPath.empty()) {
2522 InputPath.clear();
2523 sys::path::append(InputPath, Options.PrependPath, InterfaceFile);
2524 InterfaceFile = InputPath;
2526 sys::path::append(Path, ModuleName);
2527 Path.append(".swiftinterface");
2528 if (Options.Verbose)
2529 outs() << "copy parseable Swift interface " << InterfaceFile << " -> "
2530 << Path.str() << '\n';
2532 // copy_file attempts an APFS clone first, so this should be cheap.
2533 if ((EC = sys::fs::copy_file(InterfaceFile, Path.str())))
2534 warn(Twine("cannot copy parseable Swift interface ") +
2535 InterfaceFile + ": " +
2536 toString(errorCodeToError(EC)));
2537 Path.resize(BaseLength);
2539 return Error::success();
2542 bool DwarfLinker::link(const DebugMap &Map) {
2543 if (!createStreamer(Map.getTriple(), OutFile))
2544 return false;
2546 // Size of the DIEs (and headers) generated for the linked output.
2547 OutputDebugInfoSize = 0;
2548 // A unique ID that identifies each compile unit.
2549 unsigned UnitID = 0;
2550 DebugMap ModuleMap(Map.getTriple(), Map.getBinaryPath());
2552 // First populate the data structure we need for each iteration of the
2553 // parallel loop.
2554 unsigned NumObjects = Map.getNumberOfObjects();
2555 std::vector<LinkContext> ObjectContexts;
2556 ObjectContexts.reserve(NumObjects);
2557 for (const auto &Obj : Map.objects()) {
2558 ObjectContexts.emplace_back(Map, *this, *Obj.get());
2559 LinkContext &LC = ObjectContexts.back();
2560 if (LC.ObjectFile)
2561 updateAccelKind(*LC.DwarfContext);
2564 // This Dwarf string pool which is only used for uniquing. This one should
2565 // never be used for offsets as its not thread-safe or predictable.
2566 UniquingStringPool UniquingStringPool;
2568 // This Dwarf string pool which is used for emission. It must be used
2569 // serially as the order of calling getStringOffset matters for
2570 // reproducibility.
2571 OffsetsStringPool OffsetsStringPool(Options.Translator);
2573 // ODR Contexts for the link.
2574 DeclContextTree ODRContexts;
2576 // If we haven't decided on an accelerator table kind yet, we base ourselves
2577 // on the DWARF we have seen so far. At this point we haven't pulled in debug
2578 // information from modules yet, so it is technically possible that they
2579 // would affect the decision. However, as they're built with the same
2580 // compiler and flags, it is safe to assume that they will follow the
2581 // decision made here.
2582 if (Options.TheAccelTableKind == AccelTableKind::Default) {
2583 if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
2584 Options.TheAccelTableKind = AccelTableKind::Dwarf;
2585 else
2586 Options.TheAccelTableKind = AccelTableKind::Apple;
2589 for (LinkContext &LinkContext : ObjectContexts) {
2590 if (Options.Verbose)
2591 outs() << "DEBUG MAP OBJECT: " << LinkContext.DMO.getObjectFilename()
2592 << "\n";
2594 // N_AST objects (swiftmodule files) should get dumped directly into the
2595 // appropriate DWARF section.
2596 if (LinkContext.DMO.getType() == MachO::N_AST) {
2597 StringRef File = LinkContext.DMO.getObjectFilename();
2598 auto ErrorOrMem = MemoryBuffer::getFile(File);
2599 if (!ErrorOrMem) {
2600 warn("Could not open '" + File + "'\n");
2601 continue;
2603 sys::fs::file_status Stat;
2604 if (auto Err = sys::fs::status(File, Stat)) {
2605 warn(Err.message());
2606 continue;
2608 if (!Options.NoTimestamp) {
2609 // The modification can have sub-second precision so we need to cast
2610 // away the extra precision that's not present in the debug map.
2611 auto ModificationTime =
2612 std::chrono::time_point_cast<std::chrono::seconds>(
2613 Stat.getLastModificationTime());
2614 if (ModificationTime != LinkContext.DMO.getTimestamp()) {
2615 // Not using the helper here as we can easily stream TimePoint<>.
2616 WithColor::warning()
2617 << "Timestamp mismatch for " << File << ": "
2618 << Stat.getLastModificationTime() << " and "
2619 << sys::TimePoint<>(LinkContext.DMO.getTimestamp()) << "\n";
2620 continue;
2624 // Copy the module into the .swift_ast section.
2625 if (!Options.NoOutput)
2626 Streamer->emitSwiftAST((*ErrorOrMem)->getBuffer());
2627 continue;
2630 if (emitPaperTrailWarnings(LinkContext.DMO, Map, OffsetsStringPool))
2631 continue;
2633 if (!LinkContext.ObjectFile)
2634 continue;
2636 // Look for relocations that correspond to debug map entries.
2638 if (LLVM_LIKELY(!Options.Update) &&
2639 !LinkContext.RelocMgr.findValidRelocsInDebugInfo(
2640 *LinkContext.ObjectFile, LinkContext.DMO)) {
2641 if (Options.Verbose)
2642 outs() << "No valid relocations found. Skipping.\n";
2644 // Clear this ObjFile entry as a signal to other loops that we should not
2645 // process this iteration.
2646 LinkContext.ObjectFile = nullptr;
2647 continue;
2650 // Setup access to the debug info.
2651 if (!LinkContext.DwarfContext)
2652 continue;
2654 startDebugObject(LinkContext);
2656 // In a first phase, just read in the debug info and load all clang modules.
2657 LinkContext.CompileUnits.reserve(
2658 LinkContext.DwarfContext->getNumCompileUnits());
2660 for (const auto &CU : LinkContext.DwarfContext->compile_units()) {
2661 updateDwarfVersion(CU->getVersion());
2662 auto CUDie = CU->getUnitDIE(false);
2663 if (Options.Verbose) {
2664 outs() << "Input compilation unit:";
2665 DIDumpOptions DumpOpts;
2666 DumpOpts.ChildRecurseDepth = 0;
2667 DumpOpts.Verbose = Options.Verbose;
2668 CUDie.dump(outs(), 0, DumpOpts);
2670 if (CUDie && !LLVM_UNLIKELY(Options.Update))
2671 registerModuleReference(CUDie, *CU, ModuleMap, LinkContext.DMO,
2672 LinkContext.Ranges, OffsetsStringPool,
2673 UniquingStringPool, ODRContexts, 0, UnitID,
2674 LinkContext.DwarfContext->isLittleEndian());
2678 // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2679 if (MaxDwarfVersion == 0)
2680 MaxDwarfVersion = 3;
2682 // At this point we know how much data we have emitted. We use this value to
2683 // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2684 // is already emitted, without being affected by canonical die offsets set
2685 // later. This prevents undeterminism when analyze and clone execute
2686 // concurrently, as clone set the canonical DIE offset and analyze reads it.
2687 const uint64_t ModulesEndOffset = OutputDebugInfoSize;
2689 // These variables manage the list of processed object files.
2690 // The mutex and condition variable are to ensure that this is thread safe.
2691 std::mutex ProcessedFilesMutex;
2692 std::condition_variable ProcessedFilesConditionVariable;
2693 BitVector ProcessedFiles(NumObjects, false);
2695 // Analyzing the context info is particularly expensive so it is executed in
2696 // parallel with emitting the previous compile unit.
2697 auto AnalyzeLambda = [&](size_t i) {
2698 auto &LinkContext = ObjectContexts[i];
2700 if (!LinkContext.ObjectFile || !LinkContext.DwarfContext)
2701 return;
2703 for (const auto &CU : LinkContext.DwarfContext->compile_units()) {
2704 updateDwarfVersion(CU->getVersion());
2705 // The !registerModuleReference() condition effectively skips
2706 // over fully resolved skeleton units. This second pass of
2707 // registerModuleReferences doesn't do any new work, but it
2708 // will collect top-level errors, which are suppressed. Module
2709 // warnings were already displayed in the first iteration.
2710 bool Quiet = true;
2711 auto CUDie = CU->getUnitDIE(false);
2712 if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
2713 !registerModuleReference(CUDie, *CU, ModuleMap, LinkContext.DMO,
2714 LinkContext.Ranges, OffsetsStringPool,
2715 UniquingStringPool, ODRContexts,
2716 ModulesEndOffset, UnitID, Quiet)) {
2717 LinkContext.CompileUnits.push_back(std::make_unique<CompileUnit>(
2718 *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
2722 // Now build the DIE parent links that we will use during the next phase.
2723 for (auto &CurrentUnit : LinkContext.CompileUnits) {
2724 auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
2725 if (!CUDie)
2726 continue;
2727 analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
2728 *CurrentUnit, &ODRContexts.getRoot(),
2729 UniquingStringPool, ODRContexts, ModulesEndOffset,
2730 ParseableSwiftInterfaces,
2731 [&](const Twine &Warning, const DWARFDie &DIE) {
2732 reportWarning(Warning, LinkContext.DMO, &DIE);
2737 // And then the remaining work in serial again.
2738 // Note, although this loop runs in serial, it can run in parallel with
2739 // the analyzeContextInfo loop so long as we process files with indices >=
2740 // than those processed by analyzeContextInfo.
2741 auto CloneLambda = [&](size_t i) {
2742 auto &LinkContext = ObjectContexts[i];
2743 if (!LinkContext.ObjectFile)
2744 return;
2746 // Then mark all the DIEs that need to be present in the linked output
2747 // and collect some information about them.
2748 // Note that this loop can not be merged with the previous one because
2749 // cross-cu references require the ParentIdx to be setup for every CU in
2750 // the object file before calling this.
2751 if (LLVM_UNLIKELY(Options.Update)) {
2752 for (auto &CurrentUnit : LinkContext.CompileUnits)
2753 CurrentUnit->markEverythingAsKept();
2754 Streamer->copyInvariantDebugSection(*LinkContext.ObjectFile);
2755 } else {
2756 for (auto &CurrentUnit : LinkContext.CompileUnits)
2757 lookForDIEsToKeep(LinkContext.RelocMgr, LinkContext.Ranges,
2758 LinkContext.CompileUnits,
2759 CurrentUnit->getOrigUnit().getUnitDIE(),
2760 LinkContext.DMO, *CurrentUnit, 0);
2763 // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2764 // array again (in the same way findValidRelocsInDebugInfo() did). We
2765 // need to reset the NextValidReloc index to the beginning.
2766 LinkContext.RelocMgr.resetValidRelocs();
2767 if (LinkContext.RelocMgr.hasValidRelocs() || LLVM_UNLIKELY(Options.Update))
2768 DIECloner(*this, LinkContext.RelocMgr, DIEAlloc, LinkContext.CompileUnits,
2769 Options)
2770 .cloneAllCompileUnits(*LinkContext.DwarfContext, LinkContext.DMO,
2771 LinkContext.Ranges, OffsetsStringPool,
2772 LinkContext.DwarfContext->isLittleEndian());
2773 if (!Options.NoOutput && !LinkContext.CompileUnits.empty() &&
2774 LLVM_LIKELY(!Options.Update))
2775 patchFrameInfoForObject(
2776 LinkContext.DMO, LinkContext.Ranges, *LinkContext.DwarfContext,
2777 LinkContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
2779 // Clean-up before starting working on the next object.
2780 endDebugObject(LinkContext);
2783 auto EmitLambda = [&]() {
2784 // Emit everything that's global.
2785 if (!Options.NoOutput) {
2786 Streamer->emitAbbrevs(Abbreviations, MaxDwarfVersion);
2787 Streamer->emitStrings(OffsetsStringPool);
2788 switch (Options.TheAccelTableKind) {
2789 case AccelTableKind::Apple:
2790 Streamer->emitAppleNames(AppleNames);
2791 Streamer->emitAppleNamespaces(AppleNamespaces);
2792 Streamer->emitAppleTypes(AppleTypes);
2793 Streamer->emitAppleObjc(AppleObjc);
2794 break;
2795 case AccelTableKind::Dwarf:
2796 Streamer->emitDebugNames(DebugNames);
2797 break;
2798 case AccelTableKind::Default:
2799 llvm_unreachable("Default should have already been resolved.");
2800 break;
2805 auto AnalyzeAll = [&]() {
2806 for (unsigned i = 0, e = NumObjects; i != e; ++i) {
2807 AnalyzeLambda(i);
2809 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2810 ProcessedFiles.set(i);
2811 ProcessedFilesConditionVariable.notify_one();
2815 auto CloneAll = [&]() {
2816 for (unsigned i = 0, e = NumObjects; i != e; ++i) {
2818 std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2819 if (!ProcessedFiles[i]) {
2820 ProcessedFilesConditionVariable.wait(
2821 LockGuard, [&]() { return ProcessedFiles[i]; });
2825 CloneLambda(i);
2827 EmitLambda();
2830 // To limit memory usage in the single threaded case, analyze and clone are
2831 // run sequentially so the LinkContext is freed after processing each object
2832 // in endDebugObject.
2833 if (Options.Threads == 1) {
2834 for (unsigned i = 0, e = NumObjects; i != e; ++i) {
2835 AnalyzeLambda(i);
2836 CloneLambda(i);
2838 EmitLambda();
2839 } else {
2840 ThreadPool pool(2);
2841 pool.async(AnalyzeAll);
2842 pool.async(CloneAll);
2843 pool.wait();
2846 if (Options.NoOutput)
2847 return true;
2849 if (Options.ResourceDir && !ParseableSwiftInterfaces.empty()) {
2850 StringRef ArchName = Triple::getArchTypeName(Map.getTriple().getArch());
2851 if (auto E =
2852 copySwiftInterfaces(ParseableSwiftInterfaces, ArchName, Options))
2853 return error(toString(std::move(E)));
2856 return Streamer->finish(Map, Options.Translator);
2857 } // namespace dsymutil
2859 bool linkDwarf(raw_fd_ostream &OutFile, BinaryHolder &BinHolder,
2860 const DebugMap &DM, LinkOptions Options) {
2861 DwarfLinker Linker(OutFile, BinHolder, std::move(Options));
2862 return Linker.link(DM);
2865 } // namespace dsymutil
2866 } // namespace llvm