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