1 //=== DWARFLinker.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/DWARFLinker/DWARFLinker.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/BitVector.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/CodeGen/NonRelocatableStringpool.h"
14 #include "llvm/DWARFLinker/DWARFLinkerDeclContext.h"
15 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
16 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
21 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
22 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
24 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
25 #include "llvm/MC/MCDwarf.h"
26 #include "llvm/Support/DataExtractor.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ErrorOr.h"
30 #include "llvm/Support/FormatVariadic.h"
31 #include "llvm/Support/LEB128.h"
32 #include "llvm/Support/Path.h"
33 #include "llvm/Support/ThreadPool.h"
34 #include <vector>
35 
36 namespace llvm {
37 
38 /// Hold the input and output of the debug info size in bytes.
39 struct DebugInfoSize {
40   uint64_t Input;
41   uint64_t Output;
42 };
43 
44 /// Compute the total size of the debug info.
45 static uint64_t getDebugInfoSize(DWARFContext &Dwarf) {
46   uint64_t Size = 0;
47   for (auto &Unit : Dwarf.compile_units()) {
48     Size += Unit->getLength();
49   }
50   return Size;
51 }
52 
53 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
54 /// CompileUnit object instead.
55 static CompileUnit *getUnitForOffset(const UnitListTy &Units, uint64_t Offset) {
56   auto CU = llvm::upper_bound(
57       Units, Offset, [](uint64_t LHS, const std::unique_ptr<CompileUnit> &RHS) {
58         return LHS < RHS->getOrigUnit().getNextUnitOffset();
59       });
60   return CU != Units.end() ? CU->get() : nullptr;
61 }
62 
63 /// Resolve the DIE attribute reference that has been extracted in \p RefValue.
64 /// The resulting DIE might be in another CompileUnit which is stored into \p
65 /// ReferencedCU. \returns null if resolving fails for any reason.
66 DWARFDie DWARFLinker::resolveDIEReference(const DWARFFile &File,
67                                           const UnitListTy &Units,
68                                           const DWARFFormValue &RefValue,
69                                           const DWARFDie &DIE,
70                                           CompileUnit *&RefCU) {
71   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
72   uint64_t RefOffset = *RefValue.getAsReference();
73   if ((RefCU = getUnitForOffset(Units, RefOffset)))
74     if (const auto RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset)) {
75       // In a file with broken references, an attribute might point to a NULL
76       // DIE.
77       if (!RefDie.isNULL())
78         return RefDie;
79     }
80 
81   reportWarning("could not find referenced DIE", File, &DIE);
82   return DWARFDie();
83 }
84 
85 /// \returns whether the passed \a Attr type might contain a DIE reference
86 /// suitable for ODR uniquing.
87 static bool isODRAttribute(uint16_t Attr) {
88   switch (Attr) {
89   default:
90     return false;
91   case dwarf::DW_AT_type:
92   case dwarf::DW_AT_containing_type:
93   case dwarf::DW_AT_specification:
94   case dwarf::DW_AT_abstract_origin:
95   case dwarf::DW_AT_import:
96     return true;
97   }
98   llvm_unreachable("Improper attribute.");
99 }
100 
101 static bool isTypeTag(uint16_t Tag) {
102   switch (Tag) {
103   case dwarf::DW_TAG_array_type:
104   case dwarf::DW_TAG_class_type:
105   case dwarf::DW_TAG_enumeration_type:
106   case dwarf::DW_TAG_pointer_type:
107   case dwarf::DW_TAG_reference_type:
108   case dwarf::DW_TAG_string_type:
109   case dwarf::DW_TAG_structure_type:
110   case dwarf::DW_TAG_subroutine_type:
111   case dwarf::DW_TAG_typedef:
112   case dwarf::DW_TAG_union_type:
113   case dwarf::DW_TAG_ptr_to_member_type:
114   case dwarf::DW_TAG_set_type:
115   case dwarf::DW_TAG_subrange_type:
116   case dwarf::DW_TAG_base_type:
117   case dwarf::DW_TAG_const_type:
118   case dwarf::DW_TAG_constant:
119   case dwarf::DW_TAG_file_type:
120   case dwarf::DW_TAG_namelist:
121   case dwarf::DW_TAG_packed_type:
122   case dwarf::DW_TAG_volatile_type:
123   case dwarf::DW_TAG_restrict_type:
124   case dwarf::DW_TAG_atomic_type:
125   case dwarf::DW_TAG_interface_type:
126   case dwarf::DW_TAG_unspecified_type:
127   case dwarf::DW_TAG_shared_type:
128   case dwarf::DW_TAG_immutable_type:
129     return true;
130   default:
131     break;
132   }
133   return false;
134 }
135 
136 AddressesMap::~AddressesMap() = default;
137 
138 DwarfEmitter::~DwarfEmitter() = default;
139 
140 static Optional<StringRef> StripTemplateParameters(StringRef Name) {
141   // We are looking for template parameters to strip from Name. e.g.
142   //
143   //  operator<<B>
144   //
145   // We look for > at the end but if it does not contain any < then we
146   // have something like operator>>. We check for the operator<=> case.
147   if (!Name.endswith(">") || Name.count("<") == 0 || Name.endswith("<=>"))
148     return {};
149 
150   // How many < until we have the start of the template parameters.
151   size_t NumLeftAnglesToSkip = 1;
152 
153   // If we have operator<=> then we need to skip its < as well.
154   NumLeftAnglesToSkip += Name.count("<=>");
155 
156   size_t RightAngleCount = Name.count('>');
157   size_t LeftAngleCount = Name.count('<');
158 
159   // If we have more < than > we have operator< or operator<<
160   // we to account for their < as well.
161   if (LeftAngleCount > RightAngleCount)
162     NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
163 
164   size_t StartOfTemplate = 0;
165   while (NumLeftAnglesToSkip--)
166     StartOfTemplate = Name.find('<', StartOfTemplate) + 1;
167 
168   return Name.substr(0, StartOfTemplate - 1);
169 }
170 
171 bool DWARFLinker::DIECloner::getDIENames(const DWARFDie &Die,
172                                          AttributesInfo &Info,
173                                          OffsetsStringPool &StringPool,
174                                          bool StripTemplate) {
175   // This function will be called on DIEs having low_pcs and
176   // ranges. As getting the name might be more expansive, filter out
177   // blocks directly.
178   if (Die.getTag() == dwarf::DW_TAG_lexical_block)
179     return false;
180 
181   if (!Info.MangledName)
182     if (const char *MangledName = Die.getLinkageName())
183       Info.MangledName = StringPool.getEntry(MangledName);
184 
185   if (!Info.Name)
186     if (const char *Name = Die.getShortName())
187       Info.Name = StringPool.getEntry(Name);
188 
189   if (!Info.MangledName)
190     Info.MangledName = Info.Name;
191 
192   if (StripTemplate && Info.Name && Info.MangledName != Info.Name) {
193     StringRef Name = Info.Name.getString();
194     if (Optional<StringRef> StrippedName = StripTemplateParameters(Name))
195       Info.NameWithoutTemplate = StringPool.getEntry(*StrippedName);
196   }
197 
198   return Info.Name || Info.MangledName;
199 }
200 
201 /// Resolve the relative path to a build artifact referenced by DWARF by
202 /// applying DW_AT_comp_dir.
203 static void resolveRelativeObjectPath(SmallVectorImpl<char> &Buf, DWARFDie CU) {
204   sys::path::append(Buf, dwarf::toString(CU.find(dwarf::DW_AT_comp_dir), ""));
205 }
206 
207 /// Collect references to parseable Swift interfaces in imported
208 /// DW_TAG_module blocks.
209 static void analyzeImportedModule(
210     const DWARFDie &DIE, CompileUnit &CU,
211     swiftInterfacesMap *ParseableSwiftInterfaces,
212     std::function<void(const Twine &, const DWARFDie &)> ReportWarning) {
213   if (CU.getLanguage() != dwarf::DW_LANG_Swift)
214     return;
215 
216   if (!ParseableSwiftInterfaces)
217     return;
218 
219   StringRef Path = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_include_path));
220   if (!Path.endswith(".swiftinterface"))
221     return;
222   // Don't track interfaces that are part of the SDK.
223   StringRef SysRoot = dwarf::toStringRef(DIE.find(dwarf::DW_AT_LLVM_sysroot));
224   if (SysRoot.empty())
225     SysRoot = CU.getSysRoot();
226   if (!SysRoot.empty() && Path.startswith(SysRoot))
227     return;
228   Optional<const char*> Name = dwarf::toString(DIE.find(dwarf::DW_AT_name));
229   if (!Name)
230     return;
231   auto &Entry = (*ParseableSwiftInterfaces)[*Name];
232   // The prepend path is applied later when copying.
233   DWARFDie CUDie = CU.getOrigUnit().getUnitDIE();
234   SmallString<128> ResolvedPath;
235   if (sys::path::is_relative(Path))
236     resolveRelativeObjectPath(ResolvedPath, CUDie);
237   sys::path::append(ResolvedPath, Path);
238   if (!Entry.empty() && Entry != ResolvedPath)
239     ReportWarning(Twine("Conflicting parseable interfaces for Swift Module ") +
240                       *Name + ": " + Entry + " and " + Path,
241                   DIE);
242   Entry = std::string(ResolvedPath.str());
243 }
244 
245 /// The distinct types of work performed by the work loop in
246 /// analyzeContextInfo.
247 enum class ContextWorklistItemType : uint8_t {
248   AnalyzeContextInfo,
249   UpdateChildPruning,
250   UpdatePruning,
251 };
252 
253 /// This class represents an item in the work list. The type defines what kind
254 /// of work needs to be performed when processing the current item. Everything
255 /// but the Type and Die fields are optional based on the type.
256 struct ContextWorklistItem {
257   DWARFDie Die;
258   unsigned ParentIdx;
259   union {
260     CompileUnit::DIEInfo *OtherInfo;
261     DeclContext *Context;
262   };
263   ContextWorklistItemType Type;
264   bool InImportedModule;
265 
266   ContextWorklistItem(DWARFDie Die, ContextWorklistItemType T,
267                       CompileUnit::DIEInfo *OtherInfo = nullptr)
268       : Die(Die), ParentIdx(0), OtherInfo(OtherInfo), Type(T),
269         InImportedModule(false) {}
270 
271   ContextWorklistItem(DWARFDie Die, DeclContext *Context, unsigned ParentIdx,
272                       bool InImportedModule)
273       : Die(Die), ParentIdx(ParentIdx), Context(Context),
274         Type(ContextWorklistItemType::AnalyzeContextInfo),
275         InImportedModule(InImportedModule) {}
276 };
277 
278 static bool updatePruning(const DWARFDie &Die, CompileUnit &CU,
279                           uint64_t ModulesEndOffset) {
280   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
281 
282   // Prune this DIE if it is either a forward declaration inside a
283   // DW_TAG_module or a DW_TAG_module that contains nothing but
284   // forward declarations.
285   Info.Prune &= (Die.getTag() == dwarf::DW_TAG_module) ||
286                 (isTypeTag(Die.getTag()) &&
287                  dwarf::toUnsigned(Die.find(dwarf::DW_AT_declaration), 0));
288 
289   // Only prune forward declarations inside a DW_TAG_module for which a
290   // definition exists elsewhere.
291   if (ModulesEndOffset == 0)
292     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset();
293   else
294     Info.Prune &= Info.Ctxt && Info.Ctxt->getCanonicalDIEOffset() > 0 &&
295                   Info.Ctxt->getCanonicalDIEOffset() <= ModulesEndOffset;
296 
297   return Info.Prune;
298 }
299 
300 static void updateChildPruning(const DWARFDie &Die, CompileUnit &CU,
301                                CompileUnit::DIEInfo &ChildInfo) {
302   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
303   Info.Prune &= ChildInfo.Prune;
304 }
305 
306 /// Recursive helper to build the global DeclContext information and
307 /// gather the child->parent relationships in the original compile unit.
308 ///
309 /// This function uses the same work list approach as lookForDIEsToKeep.
310 ///
311 /// \return true when this DIE and all of its children are only
312 /// forward declarations to types defined in external clang modules
313 /// (i.e., forward declarations that are children of a DW_TAG_module).
314 static bool analyzeContextInfo(
315     const DWARFDie &DIE, unsigned ParentIdx, CompileUnit &CU,
316     DeclContext *CurrentDeclContext, DeclContextTree &Contexts,
317     uint64_t ModulesEndOffset, swiftInterfacesMap *ParseableSwiftInterfaces,
318     std::function<void(const Twine &, const DWARFDie &)> ReportWarning,
319     bool InImportedModule = false) {
320   // LIFO work list.
321   std::vector<ContextWorklistItem> Worklist;
322   Worklist.emplace_back(DIE, CurrentDeclContext, ParentIdx, InImportedModule);
323 
324   while (!Worklist.empty()) {
325     ContextWorklistItem Current = Worklist.back();
326     Worklist.pop_back();
327 
328     switch (Current.Type) {
329     case ContextWorklistItemType::UpdatePruning:
330       updatePruning(Current.Die, CU, ModulesEndOffset);
331       continue;
332     case ContextWorklistItemType::UpdateChildPruning:
333       updateChildPruning(Current.Die, CU, *Current.OtherInfo);
334       continue;
335     case ContextWorklistItemType::AnalyzeContextInfo:
336       break;
337     }
338 
339     unsigned Idx = CU.getOrigUnit().getDIEIndex(Current.Die);
340     CompileUnit::DIEInfo &Info = CU.getInfo(Idx);
341 
342     // Clang imposes an ODR on modules(!) regardless of the language:
343     //  "The module-id should consist of only a single identifier,
344     //   which provides the name of the module being defined. Each
345     //   module shall have a single definition."
346     //
347     // This does not extend to the types inside the modules:
348     //  "[I]n C, this implies that if two structs are defined in
349     //   different submodules with the same name, those two types are
350     //   distinct types (but may be compatible types if their
351     //   definitions match)."
352     //
353     // We treat non-C++ modules like namespaces for this reason.
354     if (Current.Die.getTag() == dwarf::DW_TAG_module &&
355         Current.ParentIdx == 0 &&
356         dwarf::toString(Current.Die.find(dwarf::DW_AT_name), "") !=
357             CU.getClangModuleName()) {
358       Current.InImportedModule = true;
359       analyzeImportedModule(Current.Die, CU, ParseableSwiftInterfaces,
360                             ReportWarning);
361     }
362 
363     Info.ParentIdx = Current.ParentIdx;
364     Info.InModuleScope = CU.isClangModule() || Current.InImportedModule;
365     if (CU.hasODR() || Info.InModuleScope) {
366       if (Current.Context) {
367         auto PtrInvalidPair = Contexts.getChildDeclContext(
368             *Current.Context, Current.Die, CU, Info.InModuleScope);
369         Current.Context = PtrInvalidPair.getPointer();
370         Info.Ctxt =
371             PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
372         if (Info.Ctxt)
373           Info.Ctxt->setDefinedInClangModule(Info.InModuleScope);
374       } else
375         Info.Ctxt = Current.Context = nullptr;
376     }
377 
378     Info.Prune = Current.InImportedModule;
379     // Add children in reverse order to the worklist to effectively process
380     // them in order.
381     Worklist.emplace_back(Current.Die, ContextWorklistItemType::UpdatePruning);
382     for (auto Child : reverse(Current.Die.children())) {
383       CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
384       Worklist.emplace_back(
385           Current.Die, ContextWorklistItemType::UpdateChildPruning, &ChildInfo);
386       Worklist.emplace_back(Child, Current.Context, Idx,
387                             Current.InImportedModule);
388     }
389   }
390 
391   return CU.getInfo(DIE).Prune;
392 }
393 
394 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
395   switch (Tag) {
396   default:
397     return false;
398   case dwarf::DW_TAG_class_type:
399   case dwarf::DW_TAG_common_block:
400   case dwarf::DW_TAG_lexical_block:
401   case dwarf::DW_TAG_structure_type:
402   case dwarf::DW_TAG_subprogram:
403   case dwarf::DW_TAG_subroutine_type:
404   case dwarf::DW_TAG_union_type:
405     return true;
406   }
407   llvm_unreachable("Invalid Tag");
408 }
409 
410 void DWARFLinker::cleanupAuxiliarryData(LinkContext &Context) {
411   Context.clear();
412 
413   for (DIEBlock *I : DIEBlocks)
414     I->~DIEBlock();
415   for (DIELoc *I : DIELocs)
416     I->~DIELoc();
417 
418   DIEBlocks.clear();
419   DIELocs.clear();
420   DIEAlloc.Reset();
421 }
422 
423 /// Check if a variable describing DIE should be kept.
424 /// \returns updated TraversalFlags.
425 unsigned DWARFLinker::shouldKeepVariableDIE(AddressesMap &RelocMgr,
426                                             const DWARFDie &DIE,
427                                             CompileUnit::DIEInfo &MyInfo,
428                                             unsigned Flags) {
429   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
430 
431   // Global variables with constant value can always be kept.
432   if (!(Flags & TF_InFunctionScope) &&
433       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value)) {
434     MyInfo.InDebugMap = true;
435     return Flags | TF_Keep;
436   }
437 
438   // See if there is a relocation to a valid debug map entry inside this
439   // variable's location. The order is important here. We want to always check
440   // if the variable has a valid relocation, so that the DIEInfo is filled.
441   // However, we don't want a static variable in a function to force us to keep
442   // the enclosing function, unless requested explicitly.
443   const bool HasLiveMemoryLocation = RelocMgr.isLiveVariable(DIE, MyInfo);
444   if (!HasLiveMemoryLocation || ((Flags & TF_InFunctionScope) &&
445                                  !LLVM_UNLIKELY(Options.KeepFunctionForStatic)))
446     return Flags;
447 
448   if (Options.Verbose) {
449     outs() << "Keeping variable DIE:";
450     DIDumpOptions DumpOpts;
451     DumpOpts.ChildRecurseDepth = 0;
452     DumpOpts.Verbose = Options.Verbose;
453     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
454   }
455 
456   return Flags | TF_Keep;
457 }
458 
459 /// Check if a function describing DIE should be kept.
460 /// \returns updated TraversalFlags.
461 unsigned DWARFLinker::shouldKeepSubprogramDIE(
462     AddressesMap &RelocMgr, RangesTy &Ranges, const DWARFDie &DIE,
463     const DWARFFile &File, CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
464     unsigned Flags) {
465   Flags |= TF_InFunctionScope;
466 
467   auto LowPc = dwarf::toAddress(DIE.find(dwarf::DW_AT_low_pc));
468   if (!LowPc)
469     return Flags;
470 
471   assert(LowPc && "low_pc attribute is not an address.");
472   if (!RelocMgr.isLiveSubprogram(DIE, MyInfo))
473     return Flags;
474 
475   if (Options.Verbose) {
476     outs() << "Keeping subprogram DIE:";
477     DIDumpOptions DumpOpts;
478     DumpOpts.ChildRecurseDepth = 0;
479     DumpOpts.Verbose = Options.Verbose;
480     DIE.dump(outs(), 8 /* Indent */, DumpOpts);
481   }
482 
483   if (DIE.getTag() == dwarf::DW_TAG_label) {
484     if (Unit.hasLabelAt(*LowPc))
485       return Flags;
486 
487     DWARFUnit &OrigUnit = Unit.getOrigUnit();
488     // FIXME: dsymutil-classic compat. dsymutil-classic doesn't consider labels
489     // that don't fall into the CU's aranges. This is wrong IMO. Debug info
490     // generation bugs aside, this is really wrong in the case of labels, where
491     // a label marking the end of a function will have a PC == CU's high_pc.
492     if (dwarf::toAddress(OrigUnit.getUnitDIE().find(dwarf::DW_AT_high_pc))
493             .value_or(UINT64_MAX) <= LowPc)
494       return Flags;
495     Unit.addLabelLowPc(*LowPc, MyInfo.AddrAdjust);
496     return Flags | TF_Keep;
497   }
498 
499   Flags |= TF_Keep;
500 
501   Optional<uint64_t> HighPc = DIE.getHighPC(*LowPc);
502   if (!HighPc) {
503     reportWarning("Function without high_pc. Range will be discarded.\n", File,
504                   &DIE);
505     return Flags;
506   }
507 
508   // Replace the debug map range with a more accurate one.
509   Ranges[*LowPc] = ObjFileAddressRange(*HighPc, MyInfo.AddrAdjust);
510   Unit.addFunctionRange(*LowPc, *HighPc, MyInfo.AddrAdjust);
511   return Flags;
512 }
513 
514 /// Check if a DIE should be kept.
515 /// \returns updated TraversalFlags.
516 unsigned DWARFLinker::shouldKeepDIE(AddressesMap &RelocMgr, RangesTy &Ranges,
517                                     const DWARFDie &DIE, const DWARFFile &File,
518                                     CompileUnit &Unit,
519                                     CompileUnit::DIEInfo &MyInfo,
520                                     unsigned Flags) {
521   switch (DIE.getTag()) {
522   case dwarf::DW_TAG_constant:
523   case dwarf::DW_TAG_variable:
524     return shouldKeepVariableDIE(RelocMgr, DIE, MyInfo, Flags);
525   case dwarf::DW_TAG_subprogram:
526   case dwarf::DW_TAG_label:
527     return shouldKeepSubprogramDIE(RelocMgr, Ranges, DIE, File, Unit, MyInfo,
528                                    Flags);
529   case dwarf::DW_TAG_base_type:
530     // DWARF Expressions may reference basic types, but scanning them
531     // is expensive. Basic types are tiny, so just keep all of them.
532   case dwarf::DW_TAG_imported_module:
533   case dwarf::DW_TAG_imported_declaration:
534   case dwarf::DW_TAG_imported_unit:
535     // We always want to keep these.
536     return Flags | TF_Keep;
537   default:
538     break;
539   }
540 
541   return Flags;
542 }
543 
544 /// Helper that updates the completeness of the current DIE based on the
545 /// completeness of one of its children. It depends on the incompleteness of
546 /// the children already being computed.
547 static void updateChildIncompleteness(const DWARFDie &Die, CompileUnit &CU,
548                                       CompileUnit::DIEInfo &ChildInfo) {
549   switch (Die.getTag()) {
550   case dwarf::DW_TAG_structure_type:
551   case dwarf::DW_TAG_class_type:
552   case dwarf::DW_TAG_union_type:
553     break;
554   default:
555     return;
556   }
557 
558   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
559 
560   if (ChildInfo.Incomplete || ChildInfo.Prune)
561     MyInfo.Incomplete = true;
562 }
563 
564 /// Helper that updates the completeness of the current DIE based on the
565 /// completeness of the DIEs it references. It depends on the incompleteness of
566 /// the referenced DIE already being computed.
567 static void updateRefIncompleteness(const DWARFDie &Die, CompileUnit &CU,
568                                     CompileUnit::DIEInfo &RefInfo) {
569   switch (Die.getTag()) {
570   case dwarf::DW_TAG_typedef:
571   case dwarf::DW_TAG_member:
572   case dwarf::DW_TAG_reference_type:
573   case dwarf::DW_TAG_ptr_to_member_type:
574   case dwarf::DW_TAG_pointer_type:
575     break;
576   default:
577     return;
578   }
579 
580   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Die);
581 
582   if (MyInfo.Incomplete)
583     return;
584 
585   if (RefInfo.Incomplete)
586     MyInfo.Incomplete = true;
587 }
588 
589 /// Look at the children of the given DIE and decide whether they should be
590 /// kept.
591 void DWARFLinker::lookForChildDIEsToKeep(
592     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
593     SmallVectorImpl<WorklistItem> &Worklist) {
594   // The TF_ParentWalk flag tells us that we are currently walking up the
595   // parent chain of a required DIE, and we don't want to mark all the children
596   // of the parents as kept (consider for example a DW_TAG_namespace node in
597   // the parent chain). There are however a set of DIE types for which we want
598   // to ignore that directive and still walk their children.
599   if (dieNeedsChildrenToBeMeaningful(Die.getTag()))
600     Flags &= ~DWARFLinker::TF_ParentWalk;
601 
602   // We're finished if this DIE has no children or we're walking the parent
603   // chain.
604   if (!Die.hasChildren() || (Flags & DWARFLinker::TF_ParentWalk))
605     return;
606 
607   // Add children in reverse order to the worklist to effectively process them
608   // in order.
609   for (auto Child : reverse(Die.children())) {
610     // Add a worklist item before every child to calculate incompleteness right
611     // after the current child is processed.
612     CompileUnit::DIEInfo &ChildInfo = CU.getInfo(Child);
613     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateChildIncompleteness,
614                           &ChildInfo);
615     Worklist.emplace_back(Child, CU, Flags);
616   }
617 }
618 
619 static bool isODRCanonicalCandidate(const DWARFDie &Die, CompileUnit &CU) {
620   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
621 
622   if (!Info.Ctxt || (Die.getTag() == dwarf::DW_TAG_namespace))
623     return false;
624 
625   if (!CU.hasODR() && !Info.InModuleScope)
626     return false;
627 
628   return !Info.Incomplete && Info.Ctxt != CU.getInfo(Info.ParentIdx).Ctxt;
629 }
630 
631 void DWARFLinker::markODRCanonicalDie(const DWARFDie &Die, CompileUnit &CU) {
632   CompileUnit::DIEInfo &Info = CU.getInfo(Die);
633 
634   Info.ODRMarkingDone = true;
635   if (Info.Keep && isODRCanonicalCandidate(Die, CU) &&
636       !Info.Ctxt->hasCanonicalDIE())
637     Info.Ctxt->setHasCanonicalDIE();
638 }
639 
640 /// Look at DIEs referenced by the given DIE and decide whether they should be
641 /// kept. All DIEs referenced though attributes should be kept.
642 void DWARFLinker::lookForRefDIEsToKeep(
643     const DWARFDie &Die, CompileUnit &CU, unsigned Flags,
644     const UnitListTy &Units, const DWARFFile &File,
645     SmallVectorImpl<WorklistItem> &Worklist) {
646   bool UseOdr = (Flags & DWARFLinker::TF_DependencyWalk)
647                     ? (Flags & DWARFLinker::TF_ODR)
648                     : CU.hasODR();
649   DWARFUnit &Unit = CU.getOrigUnit();
650   DWARFDataExtractor Data = Unit.getDebugInfoExtractor();
651   const auto *Abbrev = Die.getAbbreviationDeclarationPtr();
652   uint64_t Offset = Die.getOffset() + getULEB128Size(Abbrev->getCode());
653 
654   SmallVector<std::pair<DWARFDie, CompileUnit &>, 4> ReferencedDIEs;
655   for (const auto &AttrSpec : Abbrev->attributes()) {
656     DWARFFormValue Val(AttrSpec.Form);
657     if (!Val.isFormClass(DWARFFormValue::FC_Reference) ||
658         AttrSpec.Attr == dwarf::DW_AT_sibling) {
659       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
660                                 Unit.getFormParams());
661       continue;
662     }
663 
664     Val.extractValue(Data, &Offset, Unit.getFormParams(), &Unit);
665     CompileUnit *ReferencedCU;
666     if (auto RefDie =
667             resolveDIEReference(File, Units, Val, Die, ReferencedCU)) {
668       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefDie);
669       // If the referenced DIE has a DeclContext that has already been
670       // emitted, then do not keep the one in this CU. We'll link to
671       // the canonical DIE in cloneDieReferenceAttribute.
672       //
673       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
674       // be necessary and could be advantageously replaced by
675       // ReferencedCU->hasODR() && CU.hasODR().
676       //
677       // FIXME: compatibility with dsymutil-classic. There is no
678       // reason not to unique ref_addr references.
679       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr &&
680           isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
681           Info.Ctxt->hasCanonicalDIE())
682         continue;
683 
684       // Keep a module forward declaration if there is no definition.
685       if (!(isODRAttribute(AttrSpec.Attr) && Info.Ctxt &&
686             Info.Ctxt->hasCanonicalDIE()))
687         Info.Prune = false;
688       ReferencedDIEs.emplace_back(RefDie, *ReferencedCU);
689     }
690   }
691 
692   unsigned ODRFlag = UseOdr ? DWARFLinker::TF_ODR : 0;
693 
694   // Add referenced DIEs in reverse order to the worklist to effectively
695   // process them in order.
696   for (auto &P : reverse(ReferencedDIEs)) {
697     // Add a worklist item before every child to calculate incompleteness right
698     // after the current child is processed.
699     CompileUnit::DIEInfo &Info = P.second.getInfo(P.first);
700     Worklist.emplace_back(Die, CU, WorklistItemType::UpdateRefIncompleteness,
701                           &Info);
702     Worklist.emplace_back(P.first, P.second,
703                           DWARFLinker::TF_Keep |
704                               DWARFLinker::TF_DependencyWalk | ODRFlag);
705   }
706 }
707 
708 /// Look at the parent of the given DIE and decide whether they should be kept.
709 void DWARFLinker::lookForParentDIEsToKeep(
710     unsigned AncestorIdx, CompileUnit &CU, unsigned Flags,
711     SmallVectorImpl<WorklistItem> &Worklist) {
712   // Stop if we encounter an ancestor that's already marked as kept.
713   if (CU.getInfo(AncestorIdx).Keep)
714     return;
715 
716   DWARFUnit &Unit = CU.getOrigUnit();
717   DWARFDie ParentDIE = Unit.getDIEAtIndex(AncestorIdx);
718   Worklist.emplace_back(CU.getInfo(AncestorIdx).ParentIdx, CU, Flags);
719   Worklist.emplace_back(ParentDIE, CU, Flags);
720 }
721 
722 /// Recursively walk the \p DIE tree and look for DIEs to keep. Store that
723 /// information in \p CU's DIEInfo.
724 ///
725 /// This function is the entry point of the DIE selection algorithm. It is
726 /// expected to walk the DIE tree in file order and (though the mediation of
727 /// its helper) call hasValidRelocation() on each DIE that might be a 'root
728 /// DIE' (See DwarfLinker class comment).
729 ///
730 /// While walking the dependencies of root DIEs, this function is also called,
731 /// but during these dependency walks the file order is not respected. The
732 /// TF_DependencyWalk flag tells us which kind of traversal we are currently
733 /// doing.
734 ///
735 /// The recursive algorithm is implemented iteratively as a work list because
736 /// very deep recursion could exhaust the stack for large projects. The work
737 /// list acts as a scheduler for different types of work that need to be
738 /// performed.
739 ///
740 /// The recursive nature of the algorithm is simulated by running the "main"
741 /// algorithm (LookForDIEsToKeep) followed by either looking at more DIEs
742 /// (LookForChildDIEsToKeep, LookForRefDIEsToKeep, LookForParentDIEsToKeep) or
743 /// fixing up a computed property (UpdateChildIncompleteness,
744 /// UpdateRefIncompleteness).
745 ///
746 /// The return value indicates whether the DIE is incomplete.
747 void DWARFLinker::lookForDIEsToKeep(AddressesMap &AddressesMap,
748                                     RangesTy &Ranges, const UnitListTy &Units,
749                                     const DWARFDie &Die, const DWARFFile &File,
750                                     CompileUnit &Cu, unsigned Flags) {
751   // LIFO work list.
752   SmallVector<WorklistItem, 4> Worklist;
753   Worklist.emplace_back(Die, Cu, Flags);
754 
755   while (!Worklist.empty()) {
756     WorklistItem Current = Worklist.pop_back_val();
757 
758     // Look at the worklist type to decide what kind of work to perform.
759     switch (Current.Type) {
760     case WorklistItemType::UpdateChildIncompleteness:
761       updateChildIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
762       continue;
763     case WorklistItemType::UpdateRefIncompleteness:
764       updateRefIncompleteness(Current.Die, Current.CU, *Current.OtherInfo);
765       continue;
766     case WorklistItemType::LookForChildDIEsToKeep:
767       lookForChildDIEsToKeep(Current.Die, Current.CU, Current.Flags, Worklist);
768       continue;
769     case WorklistItemType::LookForRefDIEsToKeep:
770       lookForRefDIEsToKeep(Current.Die, Current.CU, Current.Flags, Units, File,
771                            Worklist);
772       continue;
773     case WorklistItemType::LookForParentDIEsToKeep:
774       lookForParentDIEsToKeep(Current.AncestorIdx, Current.CU, Current.Flags,
775                               Worklist);
776       continue;
777     case WorklistItemType::MarkODRCanonicalDie:
778       markODRCanonicalDie(Current.Die, Current.CU);
779       continue;
780     case WorklistItemType::LookForDIEsToKeep:
781       break;
782     }
783 
784     unsigned Idx = Current.CU.getOrigUnit().getDIEIndex(Current.Die);
785     CompileUnit::DIEInfo &MyInfo = Current.CU.getInfo(Idx);
786 
787     if (MyInfo.Prune)
788       continue;
789 
790     // If the Keep flag is set, we are marking a required DIE's dependencies.
791     // If our target is already marked as kept, we're all set.
792     bool AlreadyKept = MyInfo.Keep;
793     if ((Current.Flags & TF_DependencyWalk) && AlreadyKept)
794       continue;
795 
796     // We must not call shouldKeepDIE while called from keepDIEAndDependencies,
797     // because it would screw up the relocation finding logic.
798     if (!(Current.Flags & TF_DependencyWalk))
799       Current.Flags = shouldKeepDIE(AddressesMap, Ranges, Current.Die, File,
800                                     Current.CU, MyInfo, Current.Flags);
801 
802     // We need to mark context for the canonical die in the end of normal
803     // traversing(not TF_DependencyWalk) or after normal traversing if die
804     // was not marked as kept.
805     if (!(Current.Flags & TF_DependencyWalk) ||
806         (MyInfo.ODRMarkingDone && !MyInfo.Keep)) {
807       if (Current.CU.hasODR() || MyInfo.InModuleScope)
808         Worklist.emplace_back(Current.Die, Current.CU,
809                               WorklistItemType::MarkODRCanonicalDie);
810     }
811 
812     // Finish by looking for child DIEs. Because of the LIFO worklist we need
813     // to schedule that work before any subsequent items are added to the
814     // worklist.
815     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
816                           WorklistItemType::LookForChildDIEsToKeep);
817 
818     if (AlreadyKept || !(Current.Flags & TF_Keep))
819       continue;
820 
821     // If it is a newly kept DIE mark it as well as all its dependencies as
822     // kept.
823     MyInfo.Keep = true;
824 
825     // We're looking for incomplete types.
826     MyInfo.Incomplete =
827         Current.Die.getTag() != dwarf::DW_TAG_subprogram &&
828         Current.Die.getTag() != dwarf::DW_TAG_member &&
829         dwarf::toUnsigned(Current.Die.find(dwarf::DW_AT_declaration), 0);
830 
831     // After looking at the parent chain, look for referenced DIEs. Because of
832     // the LIFO worklist we need to schedule that work before any subsequent
833     // items are added to the worklist.
834     Worklist.emplace_back(Current.Die, Current.CU, Current.Flags,
835                           WorklistItemType::LookForRefDIEsToKeep);
836 
837     bool UseOdr = (Current.Flags & TF_DependencyWalk) ? (Current.Flags & TF_ODR)
838                                                       : Current.CU.hasODR();
839     unsigned ODRFlag = UseOdr ? TF_ODR : 0;
840     unsigned ParFlags = TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag;
841 
842     // Now schedule the parent walk.
843     Worklist.emplace_back(MyInfo.ParentIdx, Current.CU, ParFlags);
844   }
845 }
846 
847 /// Assign an abbreviation number to \p Abbrev.
848 ///
849 /// Our DIEs get freed after every DebugMapObject has been processed,
850 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
851 /// the instances hold by the DIEs. When we encounter an abbreviation
852 /// that we don't know, we create a permanent copy of it.
853 void DWARFLinker::assignAbbrev(DIEAbbrev &Abbrev) {
854   // Check the set for priors.
855   FoldingSetNodeID ID;
856   Abbrev.Profile(ID);
857   void *InsertToken;
858   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
859 
860   // If it's newly added.
861   if (InSet) {
862     // Assign existing abbreviation number.
863     Abbrev.setNumber(InSet->getNumber());
864   } else {
865     // Add to abbreviation list.
866     Abbreviations.push_back(
867         std::make_unique<DIEAbbrev>(Abbrev.getTag(), Abbrev.hasChildren()));
868     for (const auto &Attr : Abbrev.getData())
869       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
870     AbbreviationsSet.InsertNode(Abbreviations.back().get(), InsertToken);
871     // Assign the unique abbreviation number.
872     Abbrev.setNumber(Abbreviations.size());
873     Abbreviations.back()->setNumber(Abbreviations.size());
874   }
875 }
876 
877 unsigned DWARFLinker::DIECloner::cloneStringAttribute(
878     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
879     const DWARFUnit &, OffsetsStringPool &StringPool, AttributesInfo &Info) {
880   Optional<const char *> String = dwarf::toString(Val);
881   if (!String)
882     return 0;
883 
884   // Switch everything to out of line strings.
885   auto StringEntry = StringPool.getEntry(*String);
886 
887   // Update attributes info.
888   if (AttrSpec.Attr == dwarf::DW_AT_name)
889     Info.Name = StringEntry;
890   else if (AttrSpec.Attr == dwarf::DW_AT_MIPS_linkage_name ||
891            AttrSpec.Attr == dwarf::DW_AT_linkage_name)
892     Info.MangledName = StringEntry;
893 
894   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
895                DIEInteger(StringEntry.getOffset()));
896 
897   return 4;
898 }
899 
900 unsigned DWARFLinker::DIECloner::cloneDieReferenceAttribute(
901     DIE &Die, const DWARFDie &InputDIE, AttributeSpec AttrSpec,
902     unsigned AttrSize, const DWARFFormValue &Val, const DWARFFile &File,
903     CompileUnit &Unit) {
904   const DWARFUnit &U = Unit.getOrigUnit();
905   uint64_t Ref = *Val.getAsReference();
906 
907   DIE *NewRefDie = nullptr;
908   CompileUnit *RefUnit = nullptr;
909 
910   DWARFDie RefDie =
911       Linker.resolveDIEReference(File, CompileUnits, Val, InputDIE, RefUnit);
912 
913   // If the referenced DIE is not found,  drop the attribute.
914   if (!RefDie || AttrSpec.Attr == dwarf::DW_AT_sibling)
915     return 0;
916 
917   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(RefDie);
918 
919   // If we already have emitted an equivalent DeclContext, just point
920   // at it.
921   if (isODRAttribute(AttrSpec.Attr) && RefInfo.Ctxt &&
922       RefInfo.Ctxt->getCanonicalDIEOffset()) {
923     assert(RefInfo.Ctxt->hasCanonicalDIE() &&
924            "Offset to canonical die is set, but context is not marked");
925     DIEInteger Attr(RefInfo.Ctxt->getCanonicalDIEOffset());
926     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
927                  dwarf::DW_FORM_ref_addr, Attr);
928     return U.getRefAddrByteSize();
929   }
930 
931   if (!RefInfo.Clone) {
932     assert(Ref > InputDIE.getOffset());
933     // We haven't cloned this DIE yet. Just create an empty one and
934     // store it. It'll get really cloned when we process it.
935     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie.getTag()));
936   }
937   NewRefDie = RefInfo.Clone;
938 
939   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
940       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
941     // We cannot currently rely on a DIEEntry to emit ref_addr
942     // references, because the implementation calls back to DwarfDebug
943     // to find the unit offset. (We don't have a DwarfDebug)
944     // FIXME: we should be able to design DIEEntry reliance on
945     // DwarfDebug away.
946     uint64_t Attr;
947     if (Ref < InputDIE.getOffset()) {
948       // We must have already cloned that DIE.
949       uint32_t NewRefOffset =
950           RefUnit->getStartOffset() + NewRefDie->getOffset();
951       Attr = NewRefOffset;
952       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
953                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
954     } else {
955       // A forward reference. Note and fixup later.
956       Attr = 0xBADDEF;
957       Unit.noteForwardReference(
958           NewRefDie, RefUnit, RefInfo.Ctxt,
959           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
960                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
961     }
962     return U.getRefAddrByteSize();
963   }
964 
965   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
966                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
967 
968   return AttrSize;
969 }
970 
971 void DWARFLinker::DIECloner::cloneExpression(
972     DataExtractor &Data, DWARFExpression Expression, const DWARFFile &File,
973     CompileUnit &Unit, SmallVectorImpl<uint8_t> &OutputBuffer) {
974   using Encoding = DWARFExpression::Operation::Encoding;
975 
976   uint64_t OpOffset = 0;
977   for (auto &Op : Expression) {
978     auto Description = Op.getDescription();
979     // DW_OP_const_type is variable-length and has 3
980     // operands. DWARFExpression thus far only supports 2.
981     auto Op0 = Description.Op[0];
982     auto Op1 = Description.Op[1];
983     if ((Op0 == Encoding::BaseTypeRef && Op1 != Encoding::SizeNA) ||
984         (Op1 == Encoding::BaseTypeRef && Op0 != Encoding::Size1))
985       Linker.reportWarning("Unsupported DW_OP encoding.", File);
986 
987     if ((Op0 == Encoding::BaseTypeRef && Op1 == Encoding::SizeNA) ||
988         (Op1 == Encoding::BaseTypeRef && Op0 == Encoding::Size1)) {
989       // This code assumes that the other non-typeref operand fits into 1 byte.
990       assert(OpOffset < Op.getEndOffset());
991       uint32_t ULEBsize = Op.getEndOffset() - OpOffset - 1;
992       assert(ULEBsize <= 16);
993 
994       // Copy over the operation.
995       OutputBuffer.push_back(Op.getCode());
996       uint64_t RefOffset;
997       if (Op1 == Encoding::SizeNA) {
998         RefOffset = Op.getRawOperand(0);
999       } else {
1000         OutputBuffer.push_back(Op.getRawOperand(0));
1001         RefOffset = Op.getRawOperand(1);
1002       }
1003       uint32_t Offset = 0;
1004       // Look up the base type. For DW_OP_convert, the operand may be 0 to
1005       // instead indicate the generic type. The same holds for
1006       // DW_OP_reinterpret, which is currently not supported.
1007       if (RefOffset > 0 || Op.getCode() != dwarf::DW_OP_convert) {
1008         RefOffset += Unit.getOrigUnit().getOffset();
1009         auto RefDie = Unit.getOrigUnit().getDIEForOffset(RefOffset);
1010         CompileUnit::DIEInfo &Info = Unit.getInfo(RefDie);
1011         if (DIE *Clone = Info.Clone)
1012           Offset = Clone->getOffset();
1013         else
1014           Linker.reportWarning(
1015               "base type ref doesn't point to DW_TAG_base_type.", File);
1016       }
1017       uint8_t ULEB[16];
1018       unsigned RealSize = encodeULEB128(Offset, ULEB, ULEBsize);
1019       if (RealSize > ULEBsize) {
1020         // Emit the generic type as a fallback.
1021         RealSize = encodeULEB128(0, ULEB, ULEBsize);
1022         Linker.reportWarning("base type ref doesn't fit.", File);
1023       }
1024       assert(RealSize == ULEBsize && "padding failed");
1025       ArrayRef<uint8_t> ULEBbytes(ULEB, ULEBsize);
1026       OutputBuffer.append(ULEBbytes.begin(), ULEBbytes.end());
1027     } else {
1028       // Copy over everything else unmodified.
1029       StringRef Bytes = Data.getData().slice(OpOffset, Op.getEndOffset());
1030       OutputBuffer.append(Bytes.begin(), Bytes.end());
1031     }
1032     OpOffset = Op.getEndOffset();
1033   }
1034 }
1035 
1036 unsigned DWARFLinker::DIECloner::cloneBlockAttribute(
1037     DIE &Die, const DWARFFile &File, CompileUnit &Unit, AttributeSpec AttrSpec,
1038     const DWARFFormValue &Val, unsigned AttrSize, bool IsLittleEndian) {
1039   DIEValueList *Attr;
1040   DIEValue Value;
1041   DIELoc *Loc = nullptr;
1042   DIEBlock *Block = nullptr;
1043   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
1044     Loc = new (DIEAlloc) DIELoc;
1045     Linker.DIELocs.push_back(Loc);
1046   } else {
1047     Block = new (DIEAlloc) DIEBlock;
1048     Linker.DIEBlocks.push_back(Block);
1049   }
1050   Attr = Loc ? static_cast<DIEValueList *>(Loc)
1051              : static_cast<DIEValueList *>(Block);
1052 
1053   if (Loc)
1054     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1055                      dwarf::Form(AttrSpec.Form), Loc);
1056   else
1057     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
1058                      dwarf::Form(AttrSpec.Form), Block);
1059 
1060   // If the block is a DWARF Expression, clone it into the temporary
1061   // buffer using cloneExpression(), otherwise copy the data directly.
1062   SmallVector<uint8_t, 32> Buffer;
1063   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
1064   if (DWARFAttribute::mayHaveLocationExpr(AttrSpec.Attr) &&
1065       (Val.isFormClass(DWARFFormValue::FC_Block) ||
1066        Val.isFormClass(DWARFFormValue::FC_Exprloc))) {
1067     DWARFUnit &OrigUnit = Unit.getOrigUnit();
1068     DataExtractor Data(StringRef((const char *)Bytes.data(), Bytes.size()),
1069                        IsLittleEndian, OrigUnit.getAddressByteSize());
1070     DWARFExpression Expr(Data, OrigUnit.getAddressByteSize(),
1071                          OrigUnit.getFormParams().Format);
1072     cloneExpression(Data, Expr, File, Unit, Buffer);
1073     Bytes = Buffer;
1074   }
1075   for (auto Byte : Bytes)
1076     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
1077                    dwarf::DW_FORM_data1, DIEInteger(Byte));
1078 
1079   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
1080   // the DIE class, this "if" could be replaced by
1081   // Attr->setSize(Bytes.size()).
1082   if (Loc)
1083     Loc->setSize(Bytes.size());
1084   else
1085     Block->setSize(Bytes.size());
1086 
1087   Die.addValue(DIEAlloc, Value);
1088   return AttrSize;
1089 }
1090 
1091 unsigned DWARFLinker::DIECloner::cloneAddressAttribute(
1092     DIE &Die, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1093     const CompileUnit &Unit, AttributesInfo &Info) {
1094   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1095     if (AttrSpec.Attr == dwarf::DW_AT_low_pc)
1096       Info.HasLowPc = true;
1097     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1098                  dwarf::Form(AttrSpec.Form), DIEInteger(Val.getRawUValue()));
1099     return Unit.getOrigUnit().getAddressByteSize();
1100   }
1101 
1102   dwarf::Form Form = AttrSpec.Form;
1103   uint64_t Addr = 0;
1104   if (Form == dwarf::DW_FORM_addrx) {
1105     if (Optional<uint64_t> AddrOffsetSectionBase =
1106             Unit.getOrigUnit().getAddrOffsetSectionBase()) {
1107       uint64_t StartOffset = *AddrOffsetSectionBase + Val.getRawUValue();
1108       uint64_t EndOffset =
1109           StartOffset + Unit.getOrigUnit().getAddressByteSize();
1110       if (llvm::Expected<uint64_t> RelocAddr =
1111               ObjFile.Addresses->relocateIndexedAddr(StartOffset, EndOffset))
1112         Addr = *RelocAddr;
1113       else
1114         Linker.reportWarning(toString(RelocAddr.takeError()), ObjFile);
1115     } else
1116       Linker.reportWarning("no base offset for address table", ObjFile);
1117 
1118     // If this is an indexed address emit the debug_info address.
1119     Form = dwarf::DW_FORM_addr;
1120   } else
1121     Addr = *Val.getAsAddress();
1122 
1123   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
1124     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
1125         Die.getTag() == dwarf::DW_TAG_lexical_block ||
1126         Die.getTag() == dwarf::DW_TAG_label) {
1127       // The low_pc of a block or inline subroutine might get
1128       // relocated because it happens to match the low_pc of the
1129       // enclosing subprogram. To prevent issues with that, always use
1130       // the low_pc from the input DIE if relocations have been applied.
1131       Addr = (Info.OrigLowPc != std::numeric_limits<uint64_t>::max()
1132                   ? Info.OrigLowPc
1133                   : Addr) +
1134              Info.PCOffset;
1135     } else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1136       Addr = Unit.getLowPc();
1137       if (Addr == std::numeric_limits<uint64_t>::max())
1138         return 0;
1139     }
1140     Info.HasLowPc = true;
1141   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
1142     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
1143       if (uint64_t HighPc = Unit.getHighPc())
1144         Addr = HighPc;
1145       else
1146         return 0;
1147     } else
1148       // If we have a high_pc recorded for the input DIE, use
1149       // it. Otherwise (when no relocations where applied) just use the
1150       // one we just decoded.
1151       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
1152   } else if (AttrSpec.Attr == dwarf::DW_AT_call_return_pc) {
1153     // Relocate a return PC address within a call site entry.
1154     if (Die.getTag() == dwarf::DW_TAG_call_site)
1155       Addr = (Info.OrigCallReturnPc ? Info.OrigCallReturnPc : Addr) +
1156              Info.PCOffset;
1157   } else if (AttrSpec.Attr == dwarf::DW_AT_call_pc) {
1158     // Relocate the address of a branch instruction within a call site entry.
1159     if (Die.getTag() == dwarf::DW_TAG_call_site)
1160       Addr = (Info.OrigCallPc ? Info.OrigCallPc : Addr) + Info.PCOffset;
1161   }
1162 
1163   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
1164                static_cast<dwarf::Form>(Form), DIEInteger(Addr));
1165   return Unit.getOrigUnit().getAddressByteSize();
1166 }
1167 
1168 unsigned DWARFLinker::DIECloner::cloneScalarAttribute(
1169     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1170     CompileUnit &Unit, AttributeSpec AttrSpec, const DWARFFormValue &Val,
1171     unsigned AttrSize, AttributesInfo &Info) {
1172   uint64_t Value;
1173 
1174   if (LLVM_UNLIKELY(Linker.Options.Update)) {
1175     if (auto OptionalValue = Val.getAsUnsignedConstant())
1176       Value = *OptionalValue;
1177     else if (auto OptionalValue = Val.getAsSignedConstant())
1178       Value = *OptionalValue;
1179     else if (auto OptionalValue = Val.getAsSectionOffset())
1180       Value = *OptionalValue;
1181     else {
1182       Linker.reportWarning(
1183           "Unsupported scalar attribute form. Dropping attribute.", File,
1184           &InputDIE);
1185       return 0;
1186     }
1187     if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1188       Info.IsDeclaration = true;
1189     Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1190                  dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1191     return AttrSize;
1192   }
1193 
1194   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
1195       Die.getTag() == dwarf::DW_TAG_compile_unit) {
1196     if (Unit.getLowPc() == -1ULL)
1197       return 0;
1198     // Dwarf >= 4 high_pc is an size, not an address.
1199     Value = Unit.getHighPc() - Unit.getLowPc();
1200   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
1201     Value = *Val.getAsSectionOffset();
1202   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
1203     Value = *Val.getAsSignedConstant();
1204   else if (auto OptionalValue = Val.getAsUnsignedConstant())
1205     Value = *OptionalValue;
1206   else {
1207     Linker.reportWarning(
1208         "Unsupported scalar attribute form. Dropping attribute.", File,
1209         &InputDIE);
1210     return 0;
1211   }
1212   PatchLocation Patch =
1213       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
1214                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
1215   if (AttrSpec.Attr == dwarf::DW_AT_ranges) {
1216     Unit.noteRangeAttribute(Die, Patch);
1217     Info.HasRanges = true;
1218   }
1219 
1220   // A more generic way to check for location attributes would be
1221   // nice, but it's very unlikely that any other attribute needs a
1222   // location list.
1223   // FIXME: use DWARFAttribute::mayHaveLocationDescription().
1224   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
1225            AttrSpec.Attr == dwarf::DW_AT_frame_base) {
1226     Unit.noteLocationAttribute(Patch, Info.PCOffset);
1227   } else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
1228     Info.IsDeclaration = true;
1229 
1230   return AttrSize;
1231 }
1232 
1233 /// Clone \p InputDIE's attribute described by \p AttrSpec with
1234 /// value \p Val, and add it to \p Die.
1235 /// \returns the size of the cloned attribute.
1236 unsigned DWARFLinker::DIECloner::cloneAttribute(
1237     DIE &Die, const DWARFDie &InputDIE, const DWARFFile &File,
1238     CompileUnit &Unit, OffsetsStringPool &StringPool, const DWARFFormValue &Val,
1239     const AttributeSpec AttrSpec, unsigned AttrSize, AttributesInfo &Info,
1240     bool IsLittleEndian) {
1241   const DWARFUnit &U = Unit.getOrigUnit();
1242 
1243   switch (AttrSpec.Form) {
1244   case dwarf::DW_FORM_strp:
1245   case dwarf::DW_FORM_string:
1246   case dwarf::DW_FORM_strx:
1247   case dwarf::DW_FORM_strx1:
1248   case dwarf::DW_FORM_strx2:
1249   case dwarf::DW_FORM_strx3:
1250   case dwarf::DW_FORM_strx4:
1251     return cloneStringAttribute(Die, AttrSpec, Val, U, StringPool, Info);
1252   case dwarf::DW_FORM_ref_addr:
1253   case dwarf::DW_FORM_ref1:
1254   case dwarf::DW_FORM_ref2:
1255   case dwarf::DW_FORM_ref4:
1256   case dwarf::DW_FORM_ref8:
1257     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
1258                                       File, Unit);
1259   case dwarf::DW_FORM_block:
1260   case dwarf::DW_FORM_block1:
1261   case dwarf::DW_FORM_block2:
1262   case dwarf::DW_FORM_block4:
1263   case dwarf::DW_FORM_exprloc:
1264     return cloneBlockAttribute(Die, File, Unit, AttrSpec, Val, AttrSize,
1265                                IsLittleEndian);
1266   case dwarf::DW_FORM_addr:
1267   case dwarf::DW_FORM_addrx:
1268     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
1269   case dwarf::DW_FORM_data1:
1270   case dwarf::DW_FORM_data2:
1271   case dwarf::DW_FORM_data4:
1272   case dwarf::DW_FORM_data8:
1273   case dwarf::DW_FORM_udata:
1274   case dwarf::DW_FORM_sdata:
1275   case dwarf::DW_FORM_sec_offset:
1276   case dwarf::DW_FORM_flag:
1277   case dwarf::DW_FORM_flag_present:
1278     return cloneScalarAttribute(Die, InputDIE, File, Unit, AttrSpec, Val,
1279                                 AttrSize, Info);
1280   default:
1281     Linker.reportWarning("Unsupported attribute form " +
1282                              dwarf::FormEncodingString(AttrSpec.Form) +
1283                              " in cloneAttribute. Dropping.",
1284                          File, &InputDIE);
1285   }
1286 
1287   return 0;
1288 }
1289 
1290 static bool isObjCSelector(StringRef Name) {
1291   return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1292          (Name[1] == '[');
1293 }
1294 
1295 void DWARFLinker::DIECloner::addObjCAccelerator(CompileUnit &Unit,
1296                                                 const DIE *Die,
1297                                                 DwarfStringPoolEntryRef Name,
1298                                                 OffsetsStringPool &StringPool,
1299                                                 bool SkipPubSection) {
1300   assert(isObjCSelector(Name.getString()) && "not an objc selector");
1301   // Objective C method or class function.
1302   // "- [Class(Category) selector :withArg ...]"
1303   StringRef ClassNameStart(Name.getString().drop_front(2));
1304   size_t FirstSpace = ClassNameStart.find(' ');
1305   if (FirstSpace == StringRef::npos)
1306     return;
1307 
1308   StringRef SelectorStart(ClassNameStart.data() + FirstSpace + 1);
1309   if (!SelectorStart.size())
1310     return;
1311 
1312   StringRef Selector(SelectorStart.data(), SelectorStart.size() - 1);
1313   Unit.addNameAccelerator(Die, StringPool.getEntry(Selector), SkipPubSection);
1314 
1315   // Add an entry for the class name that points to this
1316   // method/class function.
1317   StringRef ClassName(ClassNameStart.data(), FirstSpace);
1318   Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassName), SkipPubSection);
1319 
1320   if (ClassName[ClassName.size() - 1] == ')') {
1321     size_t OpenParens = ClassName.find('(');
1322     if (OpenParens != StringRef::npos) {
1323       StringRef ClassNameNoCategory(ClassName.data(), OpenParens);
1324       Unit.addObjCAccelerator(Die, StringPool.getEntry(ClassNameNoCategory),
1325                               SkipPubSection);
1326 
1327       std::string MethodNameNoCategory(Name.getString().data(), OpenParens + 2);
1328       // FIXME: The missing space here may be a bug, but
1329       //        dsymutil-classic also does it this way.
1330       MethodNameNoCategory.append(std::string(SelectorStart));
1331       Unit.addNameAccelerator(Die, StringPool.getEntry(MethodNameNoCategory),
1332                               SkipPubSection);
1333     }
1334   }
1335 }
1336 
1337 static bool
1338 shouldSkipAttribute(DWARFAbbreviationDeclaration::AttributeSpec AttrSpec,
1339                     uint16_t Tag, bool InDebugMap, bool SkipPC,
1340                     bool InFunctionScope) {
1341   switch (AttrSpec.Attr) {
1342   default:
1343     return false;
1344   case dwarf::DW_AT_low_pc:
1345   case dwarf::DW_AT_high_pc:
1346   case dwarf::DW_AT_ranges:
1347     return SkipPC;
1348   case dwarf::DW_AT_str_offsets_base:
1349     // FIXME: Use the string offset table with Dwarf 5.
1350     return true;
1351   case dwarf::DW_AT_location:
1352   case dwarf::DW_AT_frame_base:
1353     // FIXME: for some reason dsymutil-classic keeps the location attributes
1354     // when they are of block type (i.e. not location lists). This is totally
1355     // wrong for globals where we will keep a wrong address. It is mostly
1356     // harmless for locals, but there is no point in keeping these anyway when
1357     // the function wasn't linked.
1358     return (SkipPC || (!InFunctionScope && Tag == dwarf::DW_TAG_variable &&
1359                        !InDebugMap)) &&
1360            !DWARFFormValue(AttrSpec.Form).isFormClass(DWARFFormValue::FC_Block);
1361   }
1362 }
1363 
1364 DIE *DWARFLinker::DIECloner::cloneDIE(const DWARFDie &InputDIE,
1365                                       const DWARFFile &File, CompileUnit &Unit,
1366                                       OffsetsStringPool &StringPool,
1367                                       int64_t PCOffset, uint32_t OutOffset,
1368                                       unsigned Flags, bool IsLittleEndian,
1369                                       DIE *Die) {
1370   DWARFUnit &U = Unit.getOrigUnit();
1371   unsigned Idx = U.getDIEIndex(InputDIE);
1372   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
1373 
1374   // Should the DIE appear in the output?
1375   if (!Unit.getInfo(Idx).Keep)
1376     return nullptr;
1377 
1378   uint64_t Offset = InputDIE.getOffset();
1379   assert(!(Die && Info.Clone) && "Can't supply a DIE and a cloned DIE");
1380   if (!Die) {
1381     // The DIE might have been already created by a forward reference
1382     // (see cloneDieReferenceAttribute()).
1383     if (!Info.Clone)
1384       Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
1385     Die = Info.Clone;
1386   }
1387 
1388   assert(Die->getTag() == InputDIE.getTag());
1389   Die->setOffset(OutOffset);
1390   if (isODRCanonicalCandidate(InputDIE, Unit) && Info.Ctxt &&
1391       (Info.Ctxt->getCanonicalDIEOffset() == 0)) {
1392     if (!Info.Ctxt->hasCanonicalDIE())
1393       Info.Ctxt->setHasCanonicalDIE();
1394     // We are about to emit a DIE that is the root of its own valid
1395     // DeclContext tree. Make the current offset the canonical offset
1396     // for this context.
1397     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
1398   }
1399 
1400   // Extract and clone every attribute.
1401   DWARFDataExtractor Data = U.getDebugInfoExtractor();
1402   // Point to the next DIE (generally there is always at least a NULL
1403   // entry after the current one). If this is a lone
1404   // DW_TAG_compile_unit without any children, point to the next unit.
1405   uint64_t NextOffset = (Idx + 1 < U.getNumDIEs())
1406                             ? U.getDIEAtIndex(Idx + 1).getOffset()
1407                             : U.getNextUnitOffset();
1408   AttributesInfo AttrInfo;
1409 
1410   // We could copy the data only if we need to apply a relocation to it. After
1411   // testing, it seems there is no performance downside to doing the copy
1412   // unconditionally, and it makes the code simpler.
1413   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
1414   Data =
1415       DWARFDataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
1416 
1417   // Modify the copy with relocated addresses.
1418   if (ObjFile.Addresses->applyValidRelocs(DIECopy, Offset,
1419                                           Data.isLittleEndian())) {
1420     // If we applied relocations, we store the value of high_pc that was
1421     // potentially stored in the input DIE. If high_pc is an address
1422     // (Dwarf version == 2), then it might have been relocated to a
1423     // totally unrelated value (because the end address in the object
1424     // file might be start address of another function which got moved
1425     // independently by the linker). The computation of the actual
1426     // high_pc value is done in cloneAddressAttribute().
1427     AttrInfo.OrigHighPc =
1428         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_high_pc), 0);
1429     // Also store the low_pc. It might get relocated in an
1430     // inline_subprogram that happens at the beginning of its
1431     // inlining function.
1432     AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
1433                                           std::numeric_limits<uint64_t>::max());
1434     AttrInfo.OrigCallReturnPc =
1435         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_return_pc), 0);
1436     AttrInfo.OrigCallPc =
1437         dwarf::toAddress(InputDIE.find(dwarf::DW_AT_call_pc), 0);
1438   }
1439 
1440   // Reset the Offset to 0 as we will be working on the local copy of
1441   // the data.
1442   Offset = 0;
1443 
1444   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
1445   Offset += getULEB128Size(Abbrev->getCode());
1446 
1447   // We are entering a subprogram. Get and propagate the PCOffset.
1448   if (Die->getTag() == dwarf::DW_TAG_subprogram)
1449     PCOffset = Info.AddrAdjust;
1450   AttrInfo.PCOffset = PCOffset;
1451 
1452   if (Abbrev->getTag() == dwarf::DW_TAG_subprogram) {
1453     Flags |= TF_InFunctionScope;
1454     if (!Info.InDebugMap && LLVM_LIKELY(!Update))
1455       Flags |= TF_SkipPC;
1456   } else if (Abbrev->getTag() == dwarf::DW_TAG_variable) {
1457     // Function-local globals could be in the debug map even when the function
1458     // is not, e.g., inlined functions.
1459     if ((Flags & TF_InFunctionScope) && Info.InDebugMap)
1460       Flags &= ~TF_SkipPC;
1461   }
1462 
1463   for (const auto &AttrSpec : Abbrev->attributes()) {
1464     if (LLVM_LIKELY(!Update) &&
1465         shouldSkipAttribute(AttrSpec, Die->getTag(), Info.InDebugMap,
1466                             Flags & TF_SkipPC, Flags & TF_InFunctionScope)) {
1467       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset,
1468                                 U.getFormParams());
1469       continue;
1470     }
1471 
1472     DWARFFormValue Val(AttrSpec.Form);
1473     uint64_t AttrSize = Offset;
1474     Val.extractValue(Data, &Offset, U.getFormParams(), &U);
1475     AttrSize = Offset - AttrSize;
1476 
1477     OutOffset += cloneAttribute(*Die, InputDIE, File, Unit, StringPool, Val,
1478                                 AttrSpec, AttrSize, AttrInfo, IsLittleEndian);
1479   }
1480 
1481   // Look for accelerator entries.
1482   uint16_t Tag = InputDIE.getTag();
1483   // FIXME: This is slightly wrong. An inline_subroutine without a
1484   // low_pc, but with AT_ranges might be interesting to get into the
1485   // accelerator tables too. For now stick with dsymutil's behavior.
1486   if ((Info.InDebugMap || AttrInfo.HasLowPc || AttrInfo.HasRanges) &&
1487       Tag != dwarf::DW_TAG_compile_unit &&
1488       getDIENames(InputDIE, AttrInfo, StringPool,
1489                   Tag != dwarf::DW_TAG_inlined_subroutine)) {
1490     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
1491       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
1492                               Tag == dwarf::DW_TAG_inlined_subroutine);
1493     if (AttrInfo.Name) {
1494       if (AttrInfo.NameWithoutTemplate)
1495         Unit.addNameAccelerator(Die, AttrInfo.NameWithoutTemplate,
1496                                 /* SkipPubSection */ true);
1497       Unit.addNameAccelerator(Die, AttrInfo.Name,
1498                               Tag == dwarf::DW_TAG_inlined_subroutine);
1499     }
1500     if (AttrInfo.Name && isObjCSelector(AttrInfo.Name.getString()))
1501       addObjCAccelerator(Unit, Die, AttrInfo.Name, StringPool,
1502                          /* SkipPubSection =*/true);
1503 
1504   } else if (Tag == dwarf::DW_TAG_namespace) {
1505     if (!AttrInfo.Name)
1506       AttrInfo.Name = StringPool.getEntry("(anonymous namespace)");
1507     Unit.addNamespaceAccelerator(Die, AttrInfo.Name);
1508   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
1509              getDIENames(InputDIE, AttrInfo, StringPool) && AttrInfo.Name &&
1510              AttrInfo.Name.getString()[0]) {
1511     uint32_t Hash = hashFullyQualifiedName(InputDIE, Unit, File);
1512     uint64_t RuntimeLang =
1513         dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_runtime_class))
1514             .value_or(0);
1515     bool ObjCClassIsImplementation =
1516         (RuntimeLang == dwarf::DW_LANG_ObjC ||
1517          RuntimeLang == dwarf::DW_LANG_ObjC_plus_plus) &&
1518         dwarf::toUnsigned(InputDIE.find(dwarf::DW_AT_APPLE_objc_complete_type))
1519             .value_or(0);
1520     Unit.addTypeAccelerator(Die, AttrInfo.Name, ObjCClassIsImplementation,
1521                             Hash);
1522   }
1523 
1524   // Determine whether there are any children that we want to keep.
1525   bool HasChildren = false;
1526   for (auto Child : InputDIE.children()) {
1527     unsigned Idx = U.getDIEIndex(Child);
1528     if (Unit.getInfo(Idx).Keep) {
1529       HasChildren = true;
1530       break;
1531     }
1532   }
1533 
1534   DIEAbbrev NewAbbrev = Die->generateAbbrev();
1535   if (HasChildren)
1536     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
1537   // Assign a permanent abbrev number
1538   Linker.assignAbbrev(NewAbbrev);
1539   Die->setAbbrevNumber(NewAbbrev.getNumber());
1540 
1541   // Add the size of the abbreviation number to the output offset.
1542   OutOffset += getULEB128Size(Die->getAbbrevNumber());
1543 
1544   if (!HasChildren) {
1545     // Update our size.
1546     Die->setSize(OutOffset - Die->getOffset());
1547     return Die;
1548   }
1549 
1550   // Recursively clone children.
1551   for (auto Child : InputDIE.children()) {
1552     if (DIE *Clone = cloneDIE(Child, File, Unit, StringPool, PCOffset,
1553                               OutOffset, Flags, IsLittleEndian)) {
1554       Die->addChild(Clone);
1555       OutOffset = Clone->getOffset() + Clone->getSize();
1556     }
1557   }
1558 
1559   // Account for the end of children marker.
1560   OutOffset += sizeof(int8_t);
1561   // Update our size.
1562   Die->setSize(OutOffset - Die->getOffset());
1563   return Die;
1564 }
1565 
1566 /// Patch the input object file relevant debug_ranges entries
1567 /// and emit them in the output file. Update the relevant attributes
1568 /// to point at the new entries.
1569 void DWARFLinker::patchRangesForUnit(const CompileUnit &Unit,
1570                                      DWARFContext &OrigDwarf,
1571                                      const DWARFFile &File) const {
1572   DWARFDebugRangeList RangeList;
1573   const auto &FunctionRanges = Unit.getFunctionRanges();
1574   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
1575   DWARFDataExtractor RangeExtractor(OrigDwarf.getDWARFObj(),
1576                                     OrigDwarf.getDWARFObj().getRangesSection(),
1577                                     OrigDwarf.isLittleEndian(), AddressSize);
1578   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1579   DWARFUnit &OrigUnit = Unit.getOrigUnit();
1580   auto OrigUnitDie = OrigUnit.getUnitDIE(false);
1581   uint64_t OrigLowPc =
1582       dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc), -1ULL);
1583   // Ranges addresses are based on the unit's low_pc. Compute the
1584   // offset we need to apply to adapt to the new unit's low_pc.
1585   int64_t UnitPcOffset = 0;
1586   if (OrigLowPc != -1ULL)
1587     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
1588 
1589   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
1590     uint64_t Offset = RangeAttribute.get();
1591     RangeAttribute.set(TheDwarfEmitter->getRangesSectionSize());
1592     if (Error E = RangeList.extract(RangeExtractor, &Offset)) {
1593       llvm::consumeError(std::move(E));
1594       reportWarning("invalid range list ignored.", File);
1595       RangeList.clear();
1596     }
1597     const auto &Entries = RangeList.getEntries();
1598     if (!Entries.empty()) {
1599       const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
1600 
1601       if (CurrRange == InvalidRange ||
1602           First.StartAddress + OrigLowPc < CurrRange.start() ||
1603           First.StartAddress + OrigLowPc >= CurrRange.stop()) {
1604         CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
1605         if (CurrRange == InvalidRange ||
1606             CurrRange.start() > First.StartAddress + OrigLowPc) {
1607           reportWarning("no mapping for range.", File);
1608           continue;
1609         }
1610       }
1611     }
1612 
1613     TheDwarfEmitter->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange,
1614                                        Entries, AddressSize);
1615   }
1616 }
1617 
1618 /// Generate the debug_aranges entries for \p Unit and if the
1619 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
1620 /// contribution for this attribute.
1621 /// FIXME: this could actually be done right in patchRangesForUnit,
1622 /// but for the sake of initial bit-for-bit compatibility with legacy
1623 /// dsymutil, we have to do it in a delayed pass.
1624 void DWARFLinker::generateUnitRanges(CompileUnit &Unit) const {
1625   auto Attr = Unit.getUnitRangesAttribute();
1626   if (Attr)
1627     Attr->set(TheDwarfEmitter->getRangesSectionSize());
1628   TheDwarfEmitter->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
1629 }
1630 
1631 /// Insert the new line info sequence \p Seq into the current
1632 /// set of already linked line info \p Rows.
1633 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
1634                                std::vector<DWARFDebugLine::Row> &Rows) {
1635   if (Seq.empty())
1636     return;
1637 
1638   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
1639     llvm::append_range(Rows, Seq);
1640     Seq.clear();
1641     return;
1642   }
1643 
1644   object::SectionedAddress Front = Seq.front().Address;
1645   auto InsertPoint = partition_point(
1646       Rows, [=](const DWARFDebugLine::Row &O) { return O.Address < Front; });
1647 
1648   // FIXME: this only removes the unneeded end_sequence if the
1649   // sequences have been inserted in order. Using a global sort like
1650   // described in patchLineTableForUnit() and delaying the end_sequene
1651   // elimination to emitLineTableForUnit() we can get rid of all of them.
1652   if (InsertPoint != Rows.end() && InsertPoint->Address == Front &&
1653       InsertPoint->EndSequence) {
1654     *InsertPoint = Seq.front();
1655     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
1656   } else {
1657     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
1658   }
1659 
1660   Seq.clear();
1661 }
1662 
1663 static void patchStmtList(DIE &Die, DIEInteger Offset) {
1664   for (auto &V : Die.values())
1665     if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
1666       V = DIEValue(V.getAttribute(), V.getForm(), Offset);
1667       return;
1668     }
1669 
1670   llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
1671 }
1672 
1673 /// Extract the line table for \p Unit from \p OrigDwarf, and
1674 /// recreate a relocated version of these for the address ranges that
1675 /// are present in the binary.
1676 void DWARFLinker::patchLineTableForUnit(CompileUnit &Unit,
1677                                         DWARFContext &OrigDwarf,
1678                                         const DWARFFile &File) {
1679   DWARFDie CUDie = Unit.getOrigUnit().getUnitDIE();
1680   auto StmtList = dwarf::toSectionOffset(CUDie.find(dwarf::DW_AT_stmt_list));
1681   if (!StmtList)
1682     return;
1683 
1684   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
1685   if (auto *OutputDIE = Unit.getOutputUnitDIE())
1686     patchStmtList(*OutputDIE,
1687                   DIEInteger(TheDwarfEmitter->getLineSectionSize()));
1688 
1689   RangesTy &Ranges = File.Addresses->getValidAddressRanges();
1690 
1691   // Parse the original line info for the unit.
1692   DWARFDebugLine::LineTable LineTable;
1693   uint64_t StmtOffset = *StmtList;
1694   DWARFDataExtractor LineExtractor(
1695       OrigDwarf.getDWARFObj(), OrigDwarf.getDWARFObj().getLineSection(),
1696       OrigDwarf.isLittleEndian(), Unit.getOrigUnit().getAddressByteSize());
1697   if (needToTranslateStrings())
1698     return TheDwarfEmitter->translateLineTable(LineExtractor, StmtOffset);
1699 
1700   if (Error Err =
1701           LineTable.parse(LineExtractor, &StmtOffset, OrigDwarf,
1702                           &Unit.getOrigUnit(), OrigDwarf.getWarningHandler()))
1703     OrigDwarf.getWarningHandler()(std::move(Err));
1704 
1705   // This vector is the output line table.
1706   std::vector<DWARFDebugLine::Row> NewRows;
1707   NewRows.reserve(LineTable.Rows.size());
1708 
1709   // Current sequence of rows being extracted, before being inserted
1710   // in NewRows.
1711   std::vector<DWARFDebugLine::Row> Seq;
1712   const auto &FunctionRanges = Unit.getFunctionRanges();
1713   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
1714 
1715   // FIXME: This logic is meant to generate exactly the same output as
1716   // Darwin's classic dsymutil. There is a nicer way to implement this
1717   // by simply putting all the relocated line info in NewRows and simply
1718   // sorting NewRows before passing it to emitLineTableForUnit. This
1719   // should be correct as sequences for a function should stay
1720   // together in the sorted output. There are a few corner cases that
1721   // look suspicious though, and that required to implement the logic
1722   // this way. Revisit that once initial validation is finished.
1723 
1724   // Iterate over the object file line info and extract the sequences
1725   // that correspond to linked functions.
1726   for (auto &Row : LineTable.Rows) {
1727     // Check whether we stepped out of the range. The range is
1728     // half-open, but consider accept the end address of the range if
1729     // it is marked as end_sequence in the input (because in that
1730     // case, the relocation offset is accurate and that entry won't
1731     // serve as the start of another function).
1732     if (CurrRange == InvalidRange || Row.Address.Address < CurrRange.start() ||
1733         Row.Address.Address > CurrRange.stop() ||
1734         (Row.Address.Address == CurrRange.stop() && !Row.EndSequence)) {
1735       // We just stepped out of a known range. Insert a end_sequence
1736       // corresponding to the end of the range.
1737       uint64_t StopAddress = CurrRange != InvalidRange
1738                                  ? CurrRange.stop() + CurrRange.value()
1739                                  : -1ULL;
1740       CurrRange = FunctionRanges.find(Row.Address.Address);
1741       bool CurrRangeValid =
1742           CurrRange != InvalidRange && CurrRange.start() <= Row.Address.Address;
1743       if (!CurrRangeValid) {
1744         CurrRange = InvalidRange;
1745         if (StopAddress != -1ULL) {
1746           // Try harder by looking in the Address ranges map.
1747           // There are corner cases where this finds a
1748           // valid entry. It's unclear if this is right or wrong, but
1749           // for now do as dsymutil.
1750           // FIXME: Understand exactly what cases this addresses and
1751           // potentially remove it along with the Ranges map.
1752           auto Range = Ranges.lower_bound(Row.Address.Address);
1753           if (Range != Ranges.begin() && Range != Ranges.end())
1754             --Range;
1755 
1756           if (Range != Ranges.end() && Range->first <= Row.Address.Address &&
1757               Range->second.HighPC >= Row.Address.Address) {
1758             StopAddress = Row.Address.Address + Range->second.Offset;
1759           }
1760         }
1761       }
1762       if (StopAddress != -1ULL && !Seq.empty()) {
1763         // Insert end sequence row with the computed end address, but
1764         // the same line as the previous one.
1765         auto NextLine = Seq.back();
1766         NextLine.Address.Address = StopAddress;
1767         NextLine.EndSequence = 1;
1768         NextLine.PrologueEnd = 0;
1769         NextLine.BasicBlock = 0;
1770         NextLine.EpilogueBegin = 0;
1771         Seq.push_back(NextLine);
1772         insertLineSequence(Seq, NewRows);
1773       }
1774 
1775       if (!CurrRangeValid)
1776         continue;
1777     }
1778 
1779     // Ignore empty sequences.
1780     if (Row.EndSequence && Seq.empty())
1781       continue;
1782 
1783     // Relocate row address and add it to the current sequence.
1784     Row.Address.Address += CurrRange.value();
1785     Seq.emplace_back(Row);
1786 
1787     if (Row.EndSequence)
1788       insertLineSequence(Seq, NewRows);
1789   }
1790 
1791   // Finished extracting, now emit the line tables.
1792   // FIXME: LLVM hard-codes its prologue values. We just copy the
1793   // prologue over and that works because we act as both producer and
1794   // consumer. It would be nicer to have a real configurable line
1795   // table emitter.
1796   if (LineTable.Prologue.getVersion() < 2 ||
1797       LineTable.Prologue.getVersion() > 5 ||
1798       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
1799       LineTable.Prologue.OpcodeBase > 13)
1800     reportWarning("line table parameters mismatch. Cannot emit.", File);
1801   else {
1802     uint32_t PrologueEnd = *StmtList + 10 + LineTable.Prologue.PrologueLength;
1803     // DWARF v5 has an extra 2 bytes of information before the header_length
1804     // field.
1805     if (LineTable.Prologue.getVersion() == 5)
1806       PrologueEnd += 2;
1807     StringRef LineData = OrigDwarf.getDWARFObj().getLineSection().Data;
1808     MCDwarfLineTableParams Params;
1809     Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
1810     Params.DWARF2LineBase = LineTable.Prologue.LineBase;
1811     Params.DWARF2LineRange = LineTable.Prologue.LineRange;
1812     TheDwarfEmitter->emitLineTableForUnit(
1813         Params, LineData.slice(*StmtList + 4, PrologueEnd),
1814         LineTable.Prologue.MinInstLength, NewRows,
1815         Unit.getOrigUnit().getAddressByteSize());
1816   }
1817 }
1818 
1819 void DWARFLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
1820   switch (Options.TheAccelTableKind) {
1821   case DwarfLinkerAccelTableKind::None:
1822     // Nothing to do.
1823     break;
1824   case DwarfLinkerAccelTableKind::Apple:
1825     emitAppleAcceleratorEntriesForUnit(Unit);
1826     break;
1827   case DwarfLinkerAccelTableKind::Dwarf:
1828     emitDwarfAcceleratorEntriesForUnit(Unit);
1829     break;
1830   case DwarfLinkerAccelTableKind::Pub:
1831     emitPubAcceleratorEntriesForUnit(Unit);
1832     break;
1833   case DwarfLinkerAccelTableKind::Default:
1834     llvm_unreachable("The default must be updated to a concrete value.");
1835     break;
1836   }
1837 }
1838 
1839 void DWARFLinker::emitAppleAcceleratorEntriesForUnit(CompileUnit &Unit) {
1840   // Add namespaces.
1841   for (const auto &Namespace : Unit.getNamespaces())
1842     AppleNamespaces.addName(Namespace.Name,
1843                             Namespace.Die->getOffset() + Unit.getStartOffset());
1844 
1845   /// Add names.
1846   for (const auto &Pubname : Unit.getPubnames())
1847     AppleNames.addName(Pubname.Name,
1848                        Pubname.Die->getOffset() + Unit.getStartOffset());
1849 
1850   /// Add types.
1851   for (const auto &Pubtype : Unit.getPubtypes())
1852     AppleTypes.addName(
1853         Pubtype.Name, Pubtype.Die->getOffset() + Unit.getStartOffset(),
1854         Pubtype.Die->getTag(),
1855         Pubtype.ObjcClassImplementation ? dwarf::DW_FLAG_type_implementation
1856                                         : 0,
1857         Pubtype.QualifiedNameHash);
1858 
1859   /// Add ObjC names.
1860   for (const auto &ObjC : Unit.getObjC())
1861     AppleObjc.addName(ObjC.Name, ObjC.Die->getOffset() + Unit.getStartOffset());
1862 }
1863 
1864 void DWARFLinker::emitDwarfAcceleratorEntriesForUnit(CompileUnit &Unit) {
1865   for (const auto &Namespace : Unit.getNamespaces())
1866     DebugNames.addName(Namespace.Name, Namespace.Die->getOffset(),
1867                        Namespace.Die->getTag(), Unit.getUniqueID());
1868   for (const auto &Pubname : Unit.getPubnames())
1869     DebugNames.addName(Pubname.Name, Pubname.Die->getOffset(),
1870                        Pubname.Die->getTag(), Unit.getUniqueID());
1871   for (const auto &Pubtype : Unit.getPubtypes())
1872     DebugNames.addName(Pubtype.Name, Pubtype.Die->getOffset(),
1873                        Pubtype.Die->getTag(), Unit.getUniqueID());
1874 }
1875 
1876 void DWARFLinker::emitPubAcceleratorEntriesForUnit(CompileUnit &Unit) {
1877   TheDwarfEmitter->emitPubNamesForUnit(Unit);
1878   TheDwarfEmitter->emitPubTypesForUnit(Unit);
1879 }
1880 
1881 /// Read the frame info stored in the object, and emit the
1882 /// patched frame descriptions for the resulting file.
1883 ///
1884 /// This is actually pretty easy as the data of the CIEs and FDEs can
1885 /// be considered as black boxes and moved as is. The only thing to do
1886 /// is to patch the addresses in the headers.
1887 void DWARFLinker::patchFrameInfoForObject(const DWARFFile &File,
1888                                           RangesTy &Ranges,
1889                                           DWARFContext &OrigDwarf,
1890                                           unsigned AddrSize) {
1891   StringRef FrameData = OrigDwarf.getDWARFObj().getFrameSection().Data;
1892   if (FrameData.empty())
1893     return;
1894 
1895   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
1896   uint64_t InputOffset = 0;
1897 
1898   // Store the data of the CIEs defined in this object, keyed by their
1899   // offsets.
1900   DenseMap<uint64_t, StringRef> LocalCIES;
1901 
1902   while (Data.isValidOffset(InputOffset)) {
1903     uint64_t EntryOffset = InputOffset;
1904     uint32_t InitialLength = Data.getU32(&InputOffset);
1905     if (InitialLength == 0xFFFFFFFF)
1906       return reportWarning("Dwarf64 bits no supported", File);
1907 
1908     uint32_t CIEId = Data.getU32(&InputOffset);
1909     if (CIEId == 0xFFFFFFFF) {
1910       // This is a CIE, store it.
1911       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
1912       LocalCIES[EntryOffset] = CIEData;
1913       // The -4 is to account for the CIEId we just read.
1914       InputOffset += InitialLength - 4;
1915       continue;
1916     }
1917 
1918     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
1919 
1920     // Some compilers seem to emit frame info that doesn't start at
1921     // the function entry point, thus we can't just lookup the address
1922     // in the debug map. Use the AddressInfo's range map to see if the FDE
1923     // describes something that we can relocate.
1924     auto Range = Ranges.upper_bound(Loc);
1925     if (Range != Ranges.begin())
1926       --Range;
1927     if (Range == Ranges.end() || Range->first > Loc ||
1928         Range->second.HighPC <= Loc) {
1929       // The +4 is to account for the size of the InitialLength field itself.
1930       InputOffset = EntryOffset + InitialLength + 4;
1931       continue;
1932     }
1933 
1934     // This is an FDE, and we have a mapping.
1935     // Have we already emitted a corresponding CIE?
1936     StringRef CIEData = LocalCIES[CIEId];
1937     if (CIEData.empty())
1938       return reportWarning("Inconsistent debug_frame content. Dropping.", File);
1939 
1940     // Look if we already emitted a CIE that corresponds to the
1941     // referenced one (the CIE data is the key of that lookup).
1942     auto IteratorInserted = EmittedCIEs.insert(
1943         std::make_pair(CIEData, TheDwarfEmitter->getFrameSectionSize()));
1944     // If there is no CIE yet for this ID, emit it.
1945     if (IteratorInserted.second) {
1946       LastCIEOffset = TheDwarfEmitter->getFrameSectionSize();
1947       IteratorInserted.first->getValue() = LastCIEOffset;
1948       TheDwarfEmitter->emitCIE(CIEData);
1949     }
1950 
1951     // Emit the FDE with updated address and CIE pointer.
1952     // (4 + AddrSize) is the size of the CIEId + initial_location
1953     // fields that will get reconstructed by emitFDE().
1954     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
1955     TheDwarfEmitter->emitFDE(IteratorInserted.first->getValue(), AddrSize,
1956                              Loc + Range->second.Offset,
1957                              FrameData.substr(InputOffset, FDERemainingBytes));
1958     InputOffset += FDERemainingBytes;
1959   }
1960 }
1961 
1962 uint32_t DWARFLinker::DIECloner::hashFullyQualifiedName(DWARFDie DIE,
1963                                                         CompileUnit &U,
1964                                                         const DWARFFile &File,
1965                                                         int ChildRecurseDepth) {
1966   const char *Name = nullptr;
1967   DWARFUnit *OrigUnit = &U.getOrigUnit();
1968   CompileUnit *CU = &U;
1969   Optional<DWARFFormValue> Ref;
1970 
1971   while (true) {
1972     if (const char *CurrentName = DIE.getName(DINameKind::ShortName))
1973       Name = CurrentName;
1974 
1975     if (!(Ref = DIE.find(dwarf::DW_AT_specification)) &&
1976         !(Ref = DIE.find(dwarf::DW_AT_abstract_origin)))
1977       break;
1978 
1979     if (!Ref->isFormClass(DWARFFormValue::FC_Reference))
1980       break;
1981 
1982     CompileUnit *RefCU;
1983     if (auto RefDIE =
1984             Linker.resolveDIEReference(File, CompileUnits, *Ref, DIE, RefCU)) {
1985       CU = RefCU;
1986       OrigUnit = &RefCU->getOrigUnit();
1987       DIE = RefDIE;
1988     }
1989   }
1990 
1991   unsigned Idx = OrigUnit->getDIEIndex(DIE);
1992   if (!Name && DIE.getTag() == dwarf::DW_TAG_namespace)
1993     Name = "(anonymous namespace)";
1994 
1995   if (CU->getInfo(Idx).ParentIdx == 0 ||
1996       // FIXME: dsymutil-classic compatibility. Ignore modules.
1997       CU->getOrigUnit().getDIEAtIndex(CU->getInfo(Idx).ParentIdx).getTag() ==
1998           dwarf::DW_TAG_module)
1999     return djbHash(Name ? Name : "", djbHash(ChildRecurseDepth ? "" : "::"));
2000 
2001   DWARFDie Die = OrigUnit->getDIEAtIndex(CU->getInfo(Idx).ParentIdx);
2002   return djbHash(
2003       (Name ? Name : ""),
2004       djbHash((Name ? "::" : ""),
2005               hashFullyQualifiedName(Die, *CU, File, ++ChildRecurseDepth)));
2006 }
2007 
2008 static uint64_t getDwoId(const DWARFDie &CUDie, const DWARFUnit &Unit) {
2009   auto DwoId = dwarf::toUnsigned(
2010       CUDie.find({dwarf::DW_AT_dwo_id, dwarf::DW_AT_GNU_dwo_id}));
2011   if (DwoId)
2012     return *DwoId;
2013   return 0;
2014 }
2015 
2016 static std::string remapPath(StringRef Path,
2017                              const objectPrefixMap &ObjectPrefixMap) {
2018   if (ObjectPrefixMap.empty())
2019     return Path.str();
2020 
2021   SmallString<256> p = Path;
2022   for (const auto &Entry : ObjectPrefixMap)
2023     if (llvm::sys::path::replace_path_prefix(p, Entry.first, Entry.second))
2024       break;
2025   return p.str().str();
2026 }
2027 
2028 bool DWARFLinker::registerModuleReference(DWARFDie CUDie, const DWARFUnit &Unit,
2029                                           const DWARFFile &File,
2030                                           OffsetsStringPool &StringPool,
2031                                           DeclContextTree &ODRContexts,
2032                                           uint64_t ModulesEndOffset,
2033                                           unsigned &UnitID, bool IsLittleEndian,
2034                                           unsigned Indent, bool Quiet) {
2035   std::string PCMfile = dwarf::toString(
2036       CUDie.find({dwarf::DW_AT_dwo_name, dwarf::DW_AT_GNU_dwo_name}), "");
2037   if (PCMfile.empty())
2038     return false;
2039   if (Options.ObjectPrefixMap)
2040     PCMfile = remapPath(PCMfile, *Options.ObjectPrefixMap);
2041 
2042   // Clang module DWARF skeleton CUs abuse this for the path to the module.
2043   uint64_t DwoId = getDwoId(CUDie, Unit);
2044 
2045   std::string Name = dwarf::toString(CUDie.find(dwarf::DW_AT_name), "");
2046   if (Name.empty()) {
2047     if (!Quiet)
2048       reportWarning("Anonymous module skeleton CU for " + PCMfile, File);
2049     return true;
2050   }
2051 
2052   if (!Quiet && Options.Verbose) {
2053     outs().indent(Indent);
2054     outs() << "Found clang module reference " << PCMfile;
2055   }
2056 
2057   auto Cached = ClangModules.find(PCMfile);
2058   if (Cached != ClangModules.end()) {
2059     // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2060     // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2061     // ASTFileSignatures will change randomly when a module is rebuilt.
2062     if (!Quiet && Options.Verbose && (Cached->second != DwoId))
2063       reportWarning(Twine("hash mismatch: this object file was built against a "
2064                           "different version of the module ") +
2065                         PCMfile,
2066                     File);
2067     if (!Quiet && Options.Verbose)
2068       outs() << " [cached].\n";
2069     return true;
2070   }
2071   if (!Quiet && Options.Verbose)
2072     outs() << " ...\n";
2073 
2074   // Cyclic dependencies are disallowed by Clang, but we still
2075   // shouldn't run into an infinite loop, so mark it as processed now.
2076   ClangModules.insert({PCMfile, DwoId});
2077 
2078   if (Error E = loadClangModule(CUDie, PCMfile, Name, DwoId, File, StringPool,
2079                                 ODRContexts, ModulesEndOffset, UnitID,
2080                                 IsLittleEndian, Indent + 2, Quiet)) {
2081     consumeError(std::move(E));
2082     return false;
2083   }
2084   return true;
2085 }
2086 
2087 Error DWARFLinker::loadClangModule(
2088     DWARFDie CUDie, StringRef Filename, StringRef ModuleName, uint64_t DwoId,
2089     const DWARFFile &File, OffsetsStringPool &StringPool,
2090     DeclContextTree &ODRContexts, uint64_t ModulesEndOffset, unsigned &UnitID,
2091     bool IsLittleEndian, unsigned Indent, bool Quiet) {
2092   /// Using a SmallString<0> because loadClangModule() is recursive.
2093   SmallString<0> Path(Options.PrependPath);
2094   if (sys::path::is_relative(Filename))
2095     resolveRelativeObjectPath(Path, CUDie);
2096   sys::path::append(Path, Filename);
2097   // Don't use the cached binary holder because we have no thread-safety
2098   // guarantee and the lifetime is limited.
2099 
2100   if (Options.ObjFileLoader == nullptr)
2101     return Error::success();
2102 
2103   auto ErrOrObj = Options.ObjFileLoader(File.FileName, Path);
2104   if (!ErrOrObj)
2105     return Error::success();
2106 
2107   std::unique_ptr<CompileUnit> Unit;
2108 
2109   for (const auto &CU : ErrOrObj->Dwarf->compile_units()) {
2110     updateDwarfVersion(CU->getVersion());
2111     // Recursively get all modules imported by this one.
2112     auto CUDie = CU->getUnitDIE(false);
2113     if (!CUDie)
2114       continue;
2115     if (!registerModuleReference(CUDie, *CU, File, StringPool, ODRContexts,
2116                                  ModulesEndOffset, UnitID, IsLittleEndian,
2117                                  Indent, Quiet)) {
2118       if (Unit) {
2119         std::string Err =
2120             (Filename +
2121              ": Clang modules are expected to have exactly 1 compile unit.\n")
2122                 .str();
2123         reportError(Err, File);
2124         return make_error<StringError>(Err, inconvertibleErrorCode());
2125       }
2126       // FIXME: Until PR27449 (https://llvm.org/bugs/show_bug.cgi?id=27449) is
2127       // fixed in clang, only warn about DWO_id mismatches in verbose mode.
2128       // ASTFileSignatures will change randomly when a module is rebuilt.
2129       uint64_t PCMDwoId = getDwoId(CUDie, *CU);
2130       if (PCMDwoId != DwoId) {
2131         if (!Quiet && Options.Verbose)
2132           reportWarning(
2133               Twine("hash mismatch: this object file was built against a "
2134                     "different version of the module ") +
2135                   Filename,
2136               File);
2137         // Update the cache entry with the DwoId of the module loaded from disk.
2138         ClangModules[Filename] = PCMDwoId;
2139       }
2140 
2141       // Add this module.
2142       Unit = std::make_unique<CompileUnit>(*CU, UnitID++, !Options.NoODR,
2143                                            ModuleName);
2144       analyzeContextInfo(CUDie, 0, *Unit, &ODRContexts.getRoot(), ODRContexts,
2145                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2146                          [&](const Twine &Warning, const DWARFDie &DIE) {
2147                            reportWarning(Warning, File, &DIE);
2148                          });
2149       // Keep everything.
2150       Unit->markEverythingAsKept();
2151     }
2152   }
2153   assert(Unit && "CompileUnit is not set!");
2154   if (!Unit->getOrigUnit().getUnitDIE().hasChildren())
2155     return Error::success();
2156   if (!Quiet && Options.Verbose) {
2157     outs().indent(Indent);
2158     outs() << "cloning .debug_info from " << Filename << "\n";
2159   }
2160 
2161   UnitListTy CompileUnits;
2162   CompileUnits.push_back(std::move(Unit));
2163   assert(TheDwarfEmitter);
2164   DIECloner(*this, TheDwarfEmitter, *ErrOrObj, DIEAlloc, CompileUnits,
2165             Options.Update)
2166       .cloneAllCompileUnits(*(ErrOrObj->Dwarf), File, StringPool,
2167                             IsLittleEndian);
2168   return Error::success();
2169 }
2170 
2171 uint64_t DWARFLinker::DIECloner::cloneAllCompileUnits(
2172     DWARFContext &DwarfContext, const DWARFFile &File,
2173     OffsetsStringPool &StringPool, bool IsLittleEndian) {
2174   uint64_t OutputDebugInfoSize =
2175       Linker.Options.NoOutput ? 0 : Emitter->getDebugInfoSectionSize();
2176   const uint64_t StartOutputDebugInfoSize = OutputDebugInfoSize;
2177 
2178   for (auto &CurrentUnit : CompileUnits) {
2179     const uint16_t DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2180     const uint32_t UnitHeaderSize = DwarfVersion >= 5 ? 12 : 11;
2181     auto InputDIE = CurrentUnit->getOrigUnit().getUnitDIE();
2182     CurrentUnit->setStartOffset(OutputDebugInfoSize);
2183     if (!InputDIE) {
2184       OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2185       continue;
2186     }
2187     if (CurrentUnit->getInfo(0).Keep) {
2188       // Clone the InputDIE into your Unit DIE in our compile unit since it
2189       // already has a DIE inside of it.
2190       CurrentUnit->createOutputDIE();
2191       cloneDIE(InputDIE, File, *CurrentUnit, StringPool, 0 /* PC offset */,
2192                UnitHeaderSize, 0, IsLittleEndian,
2193                CurrentUnit->getOutputUnitDIE());
2194     }
2195 
2196     OutputDebugInfoSize = CurrentUnit->computeNextUnitOffset(DwarfVersion);
2197 
2198     if (!Linker.Options.NoOutput) {
2199       assert(Emitter);
2200 
2201       if (LLVM_LIKELY(!Linker.Options.Update) ||
2202           Linker.needToTranslateStrings())
2203         Linker.patchLineTableForUnit(*CurrentUnit, DwarfContext, File);
2204 
2205       Linker.emitAcceleratorEntriesForUnit(*CurrentUnit);
2206 
2207       if (LLVM_UNLIKELY(Linker.Options.Update))
2208         continue;
2209 
2210       Linker.patchRangesForUnit(*CurrentUnit, DwarfContext, File);
2211       auto ProcessExpr = [&](StringRef Bytes,
2212                              SmallVectorImpl<uint8_t> &Buffer) {
2213         DWARFUnit &OrigUnit = CurrentUnit->getOrigUnit();
2214         DataExtractor Data(Bytes, IsLittleEndian,
2215                            OrigUnit.getAddressByteSize());
2216         cloneExpression(Data,
2217                         DWARFExpression(Data, OrigUnit.getAddressByteSize(),
2218                                         OrigUnit.getFormParams().Format),
2219                         File, *CurrentUnit, Buffer);
2220       };
2221       Emitter->emitLocationsForUnit(*CurrentUnit, DwarfContext, ProcessExpr);
2222     }
2223   }
2224 
2225   if (!Linker.Options.NoOutput) {
2226     assert(Emitter);
2227     // Emit all the compile unit's debug information.
2228     for (auto &CurrentUnit : CompileUnits) {
2229       if (LLVM_LIKELY(!Linker.Options.Update))
2230         Linker.generateUnitRanges(*CurrentUnit);
2231 
2232       CurrentUnit->fixupForwardReferences();
2233 
2234       if (!CurrentUnit->getOutputUnitDIE())
2235         continue;
2236 
2237       unsigned DwarfVersion = CurrentUnit->getOrigUnit().getVersion();
2238 
2239       assert(Emitter->getDebugInfoSectionSize() ==
2240              CurrentUnit->getStartOffset());
2241       Emitter->emitCompileUnitHeader(*CurrentUnit, DwarfVersion);
2242       Emitter->emitDIE(*CurrentUnit->getOutputUnitDIE());
2243       assert(Emitter->getDebugInfoSectionSize() ==
2244              CurrentUnit->computeNextUnitOffset(DwarfVersion));
2245     }
2246   }
2247 
2248   return OutputDebugInfoSize - StartOutputDebugInfoSize;
2249 }
2250 
2251 void DWARFLinker::updateAccelKind(DWARFContext &Dwarf) {
2252   if (Options.TheAccelTableKind != DwarfLinkerAccelTableKind::Default)
2253     return;
2254 
2255   auto &DwarfObj = Dwarf.getDWARFObj();
2256 
2257   if (!AtLeastOneDwarfAccelTable &&
2258       (!DwarfObj.getAppleNamesSection().Data.empty() ||
2259        !DwarfObj.getAppleTypesSection().Data.empty() ||
2260        !DwarfObj.getAppleNamespacesSection().Data.empty() ||
2261        !DwarfObj.getAppleObjCSection().Data.empty())) {
2262     AtLeastOneAppleAccelTable = true;
2263   }
2264 
2265   if (!AtLeastOneDwarfAccelTable && !DwarfObj.getNamesSection().Data.empty()) {
2266     AtLeastOneDwarfAccelTable = true;
2267   }
2268 }
2269 
2270 bool DWARFLinker::emitPaperTrailWarnings(const DWARFFile &File,
2271                                          OffsetsStringPool &StringPool) {
2272 
2273   if (File.Warnings.empty())
2274     return false;
2275 
2276   DIE *CUDie = DIE::get(DIEAlloc, dwarf::DW_TAG_compile_unit);
2277   CUDie->setOffset(11);
2278   StringRef Producer;
2279   StringRef WarningHeader;
2280 
2281   switch (DwarfLinkerClientID) {
2282   case DwarfLinkerClient::Dsymutil:
2283     Producer = StringPool.internString("dsymutil");
2284     WarningHeader = "dsymutil_warning";
2285     break;
2286 
2287   default:
2288     Producer = StringPool.internString("dwarfopt");
2289     WarningHeader = "dwarfopt_warning";
2290     break;
2291   }
2292 
2293   StringRef FileName = StringPool.internString(File.FileName);
2294   CUDie->addValue(DIEAlloc, dwarf::DW_AT_producer, dwarf::DW_FORM_strp,
2295                   DIEInteger(StringPool.getStringOffset(Producer)));
2296   DIEBlock *String = new (DIEAlloc) DIEBlock();
2297   DIEBlocks.push_back(String);
2298   for (auto &C : FileName)
2299     String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2300                      DIEInteger(C));
2301   String->addValue(DIEAlloc, dwarf::Attribute(0), dwarf::DW_FORM_data1,
2302                    DIEInteger(0));
2303 
2304   CUDie->addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_string, String);
2305   for (const auto &Warning : File.Warnings) {
2306     DIE &ConstDie = CUDie->addChild(DIE::get(DIEAlloc, dwarf::DW_TAG_constant));
2307     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_name, dwarf::DW_FORM_strp,
2308                       DIEInteger(StringPool.getStringOffset(WarningHeader)));
2309     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag,
2310                       DIEInteger(1));
2311     ConstDie.addValue(DIEAlloc, dwarf::DW_AT_const_value, dwarf::DW_FORM_strp,
2312                       DIEInteger(StringPool.getStringOffset(Warning)));
2313   }
2314   unsigned Size = 4 /* FORM_strp */ + FileName.size() + 1 +
2315                   File.Warnings.size() * (4 + 1 + 4) + 1 /* End of children */;
2316   DIEAbbrev Abbrev = CUDie->generateAbbrev();
2317   assignAbbrev(Abbrev);
2318   CUDie->setAbbrevNumber(Abbrev.getNumber());
2319   Size += getULEB128Size(Abbrev.getNumber());
2320   // Abbreviation ordering needed for classic compatibility.
2321   for (auto &Child : CUDie->children()) {
2322     Abbrev = Child.generateAbbrev();
2323     assignAbbrev(Abbrev);
2324     Child.setAbbrevNumber(Abbrev.getNumber());
2325     Size += getULEB128Size(Abbrev.getNumber());
2326   }
2327   CUDie->setSize(Size);
2328   TheDwarfEmitter->emitPaperTrailWarningsDie(*CUDie);
2329 
2330   return true;
2331 }
2332 
2333 void DWARFLinker::copyInvariantDebugSection(DWARFContext &Dwarf) {
2334   if (!needToTranslateStrings())
2335     TheDwarfEmitter->emitSectionContents(
2336         Dwarf.getDWARFObj().getLineSection().Data, "debug_line");
2337   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getLocSection().Data,
2338                                        "debug_loc");
2339   TheDwarfEmitter->emitSectionContents(
2340       Dwarf.getDWARFObj().getRangesSection().Data, "debug_ranges");
2341   TheDwarfEmitter->emitSectionContents(
2342       Dwarf.getDWARFObj().getFrameSection().Data, "debug_frame");
2343   TheDwarfEmitter->emitSectionContents(Dwarf.getDWARFObj().getArangesSection(),
2344                                        "debug_aranges");
2345 }
2346 
2347 void DWARFLinker::addObjectFile(DWARFFile &File) {
2348   ObjectContexts.emplace_back(LinkContext(File));
2349 
2350   if (ObjectContexts.back().File.Dwarf)
2351     updateAccelKind(*ObjectContexts.back().File.Dwarf);
2352 }
2353 
2354 bool DWARFLinker::link() {
2355   assert(Options.NoOutput || TheDwarfEmitter);
2356 
2357   // A unique ID that identifies each compile unit.
2358   unsigned UnitID = 0;
2359 
2360   // First populate the data structure we need for each iteration of the
2361   // parallel loop.
2362   unsigned NumObjects = ObjectContexts.size();
2363 
2364   // This Dwarf string pool which is used for emission. It must be used
2365   // serially as the order of calling getStringOffset matters for
2366   // reproducibility.
2367   OffsetsStringPool OffsetsStringPool(StringsTranslator, true);
2368 
2369   // ODR Contexts for the optimize.
2370   DeclContextTree ODRContexts;
2371 
2372   // If we haven't decided on an accelerator table kind yet, we base ourselves
2373   // on the DWARF we have seen so far. At this point we haven't pulled in debug
2374   // information from modules yet, so it is technically possible that they
2375   // would affect the decision. However, as they're built with the same
2376   // compiler and flags, it is safe to assume that they will follow the
2377   // decision made here.
2378   if (Options.TheAccelTableKind == DwarfLinkerAccelTableKind::Default) {
2379     if (AtLeastOneDwarfAccelTable && !AtLeastOneAppleAccelTable)
2380       Options.TheAccelTableKind = DwarfLinkerAccelTableKind::Dwarf;
2381     else
2382       Options.TheAccelTableKind = DwarfLinkerAccelTableKind::Apple;
2383   }
2384 
2385   for (LinkContext &OptContext : ObjectContexts) {
2386     if (Options.Verbose) {
2387       if (DwarfLinkerClientID == DwarfLinkerClient::Dsymutil)
2388         outs() << "DEBUG MAP OBJECT: " << OptContext.File.FileName << "\n";
2389       else
2390         outs() << "OBJECT FILE: " << OptContext.File.FileName << "\n";
2391     }
2392 
2393     if (emitPaperTrailWarnings(OptContext.File, OffsetsStringPool))
2394       continue;
2395 
2396     if (!OptContext.File.Dwarf)
2397       continue;
2398 
2399     if (Options.VerifyInputDWARF)
2400       verify(OptContext.File);
2401 
2402     // Look for relocations that correspond to address map entries.
2403 
2404     // there was findvalidrelocations previously ... probably we need to gather
2405     // info here
2406     if (LLVM_LIKELY(!Options.Update) &&
2407         !OptContext.File.Addresses->hasValidRelocs()) {
2408       if (Options.Verbose)
2409         outs() << "No valid relocations found. Skipping.\n";
2410 
2411       // Set "Skip" flag as a signal to other loops that we should not
2412       // process this iteration.
2413       OptContext.Skip = true;
2414       continue;
2415     }
2416 
2417     // Setup access to the debug info.
2418     if (!OptContext.File.Dwarf)
2419       continue;
2420 
2421     // In a first phase, just read in the debug info and load all clang modules.
2422     OptContext.CompileUnits.reserve(
2423         OptContext.File.Dwarf->getNumCompileUnits());
2424 
2425     for (const auto &CU : OptContext.File.Dwarf->compile_units()) {
2426       updateDwarfVersion(CU->getVersion());
2427       auto CUDie = CU->getUnitDIE(false);
2428       if (Options.Verbose) {
2429         outs() << "Input compilation unit:";
2430         DIDumpOptions DumpOpts;
2431         DumpOpts.ChildRecurseDepth = 0;
2432         DumpOpts.Verbose = Options.Verbose;
2433         CUDie.dump(outs(), 0, DumpOpts);
2434       }
2435       if (CUDie && !LLVM_UNLIKELY(Options.Update))
2436         registerModuleReference(CUDie, *CU, OptContext.File, OffsetsStringPool,
2437                                 ODRContexts, 0, UnitID,
2438                                 OptContext.File.Dwarf->isLittleEndian());
2439     }
2440   }
2441 
2442   // If we haven't seen any CUs, pick an arbitrary valid Dwarf version anyway.
2443   if (MaxDwarfVersion == 0)
2444     MaxDwarfVersion = 3;
2445 
2446   // At this point we know how much data we have emitted. We use this value to
2447   // compare canonical DIE offsets in analyzeContextInfo to see if a definition
2448   // is already emitted, without being affected by canonical die offsets set
2449   // later. This prevents undeterminism when analyze and clone execute
2450   // concurrently, as clone set the canonical DIE offset and analyze reads it.
2451   const uint64_t ModulesEndOffset =
2452       Options.NoOutput ? 0 : TheDwarfEmitter->getDebugInfoSectionSize();
2453 
2454   // These variables manage the list of processed object files.
2455   // The mutex and condition variable are to ensure that this is thread safe.
2456   std::mutex ProcessedFilesMutex;
2457   std::condition_variable ProcessedFilesConditionVariable;
2458   BitVector ProcessedFiles(NumObjects, false);
2459 
2460   //  Analyzing the context info is particularly expensive so it is executed in
2461   //  parallel with emitting the previous compile unit.
2462   auto AnalyzeLambda = [&](size_t I) {
2463     auto &Context = ObjectContexts[I];
2464 
2465     if (Context.Skip || !Context.File.Dwarf)
2466       return;
2467 
2468     for (const auto &CU : Context.File.Dwarf->compile_units()) {
2469       updateDwarfVersion(CU->getVersion());
2470       // The !registerModuleReference() condition effectively skips
2471       // over fully resolved skeleton units. This second pass of
2472       // registerModuleReferences doesn't do any new work, but it
2473       // will collect top-level errors, which are suppressed. Module
2474       // warnings were already displayed in the first iteration.
2475       bool Quiet = true;
2476       auto CUDie = CU->getUnitDIE(false);
2477       if (!CUDie || LLVM_UNLIKELY(Options.Update) ||
2478           !registerModuleReference(CUDie, *CU, Context.File, OffsetsStringPool,
2479                                    ODRContexts, ModulesEndOffset, UnitID,
2480                                    Quiet)) {
2481         Context.CompileUnits.push_back(std::make_unique<CompileUnit>(
2482             *CU, UnitID++, !Options.NoODR && !Options.Update, ""));
2483       }
2484     }
2485 
2486     // Now build the DIE parent links that we will use during the next phase.
2487     for (auto &CurrentUnit : Context.CompileUnits) {
2488       auto CUDie = CurrentUnit->getOrigUnit().getUnitDIE();
2489       if (!CUDie)
2490         continue;
2491       analyzeContextInfo(CurrentUnit->getOrigUnit().getUnitDIE(), 0,
2492                          *CurrentUnit, &ODRContexts.getRoot(), ODRContexts,
2493                          ModulesEndOffset, Options.ParseableSwiftInterfaces,
2494                          [&](const Twine &Warning, const DWARFDie &DIE) {
2495                            reportWarning(Warning, Context.File, &DIE);
2496                          });
2497     }
2498   };
2499 
2500   // For each object file map how many bytes were emitted.
2501   StringMap<DebugInfoSize> SizeByObject;
2502 
2503   // And then the remaining work in serial again.
2504   // Note, although this loop runs in serial, it can run in parallel with
2505   // the analyzeContextInfo loop so long as we process files with indices >=
2506   // than those processed by analyzeContextInfo.
2507   auto CloneLambda = [&](size_t I) {
2508     auto &OptContext = ObjectContexts[I];
2509     if (OptContext.Skip || !OptContext.File.Dwarf)
2510       return;
2511 
2512     // Then mark all the DIEs that need to be present in the generated output
2513     // and collect some information about them.
2514     // Note that this loop can not be merged with the previous one because
2515     // cross-cu references require the ParentIdx to be setup for every CU in
2516     // the object file before calling this.
2517     if (LLVM_UNLIKELY(Options.Update)) {
2518       for (auto &CurrentUnit : OptContext.CompileUnits)
2519         CurrentUnit->markEverythingAsKept();
2520       copyInvariantDebugSection(*OptContext.File.Dwarf);
2521     } else {
2522       for (auto &CurrentUnit : OptContext.CompileUnits)
2523         lookForDIEsToKeep(*OptContext.File.Addresses,
2524                           OptContext.File.Addresses->getValidAddressRanges(),
2525                           OptContext.CompileUnits,
2526                           CurrentUnit->getOrigUnit().getUnitDIE(),
2527                           OptContext.File, *CurrentUnit, 0);
2528     }
2529 
2530     // The calls to applyValidRelocs inside cloneDIE will walk the reloc
2531     // array again (in the same way findValidRelocsInDebugInfo() did). We
2532     // need to reset the NextValidReloc index to the beginning.
2533     if (OptContext.File.Addresses->hasValidRelocs() ||
2534         LLVM_UNLIKELY(Options.Update)) {
2535       SizeByObject[OptContext.File.FileName].Input =
2536           getDebugInfoSize(*OptContext.File.Dwarf);
2537       SizeByObject[OptContext.File.FileName].Output =
2538           DIECloner(*this, TheDwarfEmitter, OptContext.File, DIEAlloc,
2539                     OptContext.CompileUnits, Options.Update)
2540               .cloneAllCompileUnits(*OptContext.File.Dwarf, OptContext.File,
2541                                     OffsetsStringPool,
2542                                     OptContext.File.Dwarf->isLittleEndian());
2543     }
2544     if (!Options.NoOutput && !OptContext.CompileUnits.empty() &&
2545         LLVM_LIKELY(!Options.Update))
2546       patchFrameInfoForObject(
2547           OptContext.File, OptContext.File.Addresses->getValidAddressRanges(),
2548           *OptContext.File.Dwarf,
2549           OptContext.CompileUnits[0]->getOrigUnit().getAddressByteSize());
2550 
2551     // Clean-up before starting working on the next object.
2552     cleanupAuxiliarryData(OptContext);
2553   };
2554 
2555   auto EmitLambda = [&]() {
2556     // Emit everything that's global.
2557     if (!Options.NoOutput) {
2558       TheDwarfEmitter->emitAbbrevs(Abbreviations, MaxDwarfVersion);
2559       TheDwarfEmitter->emitStrings(OffsetsStringPool);
2560       switch (Options.TheAccelTableKind) {
2561       case DwarfLinkerAccelTableKind::None:
2562         // Nothing to do.
2563         break;
2564       case DwarfLinkerAccelTableKind::Apple:
2565         TheDwarfEmitter->emitAppleNames(AppleNames);
2566         TheDwarfEmitter->emitAppleNamespaces(AppleNamespaces);
2567         TheDwarfEmitter->emitAppleTypes(AppleTypes);
2568         TheDwarfEmitter->emitAppleObjc(AppleObjc);
2569         break;
2570       case DwarfLinkerAccelTableKind::Dwarf:
2571         TheDwarfEmitter->emitDebugNames(DebugNames);
2572         break;
2573       case DwarfLinkerAccelTableKind::Pub:
2574         // Already emitted by emitPubAcceleratorEntriesForUnit.
2575         break;
2576       case DwarfLinkerAccelTableKind::Default:
2577         llvm_unreachable("Default should have already been resolved.");
2578         break;
2579       }
2580     }
2581   };
2582 
2583   auto AnalyzeAll = [&]() {
2584     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2585       AnalyzeLambda(I);
2586 
2587       std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2588       ProcessedFiles.set(I);
2589       ProcessedFilesConditionVariable.notify_one();
2590     }
2591   };
2592 
2593   auto CloneAll = [&]() {
2594     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2595       {
2596         std::unique_lock<std::mutex> LockGuard(ProcessedFilesMutex);
2597         if (!ProcessedFiles[I]) {
2598           ProcessedFilesConditionVariable.wait(
2599               LockGuard, [&]() { return ProcessedFiles[I]; });
2600         }
2601       }
2602 
2603       CloneLambda(I);
2604     }
2605     EmitLambda();
2606   };
2607 
2608   // To limit memory usage in the single threaded case, analyze and clone are
2609   // run sequentially so the OptContext is freed after processing each object
2610   // in endDebugObject.
2611   if (Options.Threads == 1) {
2612     for (unsigned I = 0, E = NumObjects; I != E; ++I) {
2613       AnalyzeLambda(I);
2614       CloneLambda(I);
2615     }
2616     EmitLambda();
2617   } else {
2618     ThreadPool Pool(hardware_concurrency(2));
2619     Pool.async(AnalyzeAll);
2620     Pool.async(CloneAll);
2621     Pool.wait();
2622   }
2623 
2624   if (Options.Statistics) {
2625     // Create a vector sorted in descending order by output size.
2626     std::vector<std::pair<StringRef, DebugInfoSize>> Sorted;
2627     for (auto &E : SizeByObject)
2628       Sorted.emplace_back(E.first(), E.second);
2629     llvm::sort(Sorted, [](auto &LHS, auto &RHS) {
2630       return LHS.second.Output > RHS.second.Output;
2631     });
2632 
2633     auto ComputePercentange = [](int64_t Input, int64_t Output) -> float {
2634       const float Difference = Output - Input;
2635       const float Sum = Input + Output;
2636       if (Sum == 0)
2637         return 0;
2638       return (Difference / (Sum / 2));
2639     };
2640 
2641     int64_t InputTotal = 0;
2642     int64_t OutputTotal = 0;
2643     const char *FormatStr = "{0,-45} {1,10}b  {2,10}b {3,8:P}\n";
2644 
2645     // Print header.
2646     outs() << ".debug_info section size (in bytes)\n";
2647     outs() << "----------------------------------------------------------------"
2648               "---------------\n";
2649     outs() << "Filename                                           Object       "
2650               "  dSYM   Change\n";
2651     outs() << "----------------------------------------------------------------"
2652               "---------------\n";
2653 
2654     // Print body.
2655     for (auto &E : Sorted) {
2656       InputTotal += E.second.Input;
2657       OutputTotal += E.second.Output;
2658       llvm::outs() << formatv(
2659           FormatStr, sys::path::filename(E.first).take_back(45), E.second.Input,
2660           E.second.Output, ComputePercentange(E.second.Input, E.second.Output));
2661     }
2662     // Print total and footer.
2663     outs() << "----------------------------------------------------------------"
2664               "---------------\n";
2665     llvm::outs() << formatv(FormatStr, "Total", InputTotal, OutputTotal,
2666                             ComputePercentange(InputTotal, OutputTotal));
2667     outs() << "----------------------------------------------------------------"
2668               "---------------\n\n";
2669   }
2670 
2671   return true;
2672 }
2673 
2674 bool DWARFLinker::verify(const DWARFFile &File) {
2675   assert(File.Dwarf);
2676 
2677   DIDumpOptions DumpOpts;
2678   if (!File.Dwarf->verify(llvm::outs(), DumpOpts.noImplicitRecursion())) {
2679     reportWarning("input verification failed", File);
2680     return false;
2681   }
2682   return true;
2683 }
2684 
2685 } // namespace llvm
2686