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