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