[dsymutil] Use the new MCDwarfLineTableParams customization to emit linetables
[oota-llvm.git] / tools / dsymutil / DwarfLinker.cpp
1 //===- tools/dsymutil/DwarfLinker.cpp - Dwarf debug info linker -----------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 #include "DebugMap.h"
10 #include "BinaryHolder.h"
11 #include "DebugMap.h"
12 #include "dsymutil.h"
13 #include "llvm/ADT/IntervalMap.h"
14 #include "llvm/ADT/StringMap.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/CodeGen/AsmPrinter.h"
17 #include "llvm/CodeGen/DIE.h"
18 #include "llvm/Config/config.h"
19 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
21 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
22 #include "llvm/MC/MCAsmBackend.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCCodeEmitter.h"
26 #include "llvm/MC/MCDwarf.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCObjectFileInfo.h"
29 #include "llvm/MC/MCRegisterInfo.h"
30 #include "llvm/MC/MCStreamer.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/MachO.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/LEB128.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include <string>
39 #include <tuple>
40
41 namespace llvm {
42 namespace dsymutil {
43
44 namespace {
45
46 void warn(const Twine &Warning, const Twine &Context) {
47   errs() << Twine("while processing ") + Context + ":\n";
48   errs() << Twine("warning: ") + Warning + "\n";
49 }
50
51 bool error(const Twine &Error, const Twine &Context) {
52   errs() << Twine("while processing ") + Context + ":\n";
53   errs() << Twine("error: ") + Error + "\n";
54   return false;
55 }
56
57 template <typename KeyT, typename ValT>
58 using HalfOpenIntervalMap =
59     IntervalMap<KeyT, ValT, IntervalMapImpl::NodeSizer<KeyT, ValT>::LeafSize,
60                 IntervalMapHalfOpenInfo<KeyT>>;
61
62 typedef HalfOpenIntervalMap<uint64_t, int64_t> FunctionIntervals;
63
64 // FIXME: Delete this structure.
65 struct PatchLocation {
66   DIE::value_iterator I;
67
68   PatchLocation() = default;
69   PatchLocation(DIE::value_iterator I) : I(I) {}
70
71   void set(uint64_t New) const {
72     assert(I);
73     const auto &Old = *I;
74     assert(Old.getType() == DIEValue::isInteger);
75     *I = DIEValue(Old.getAttribute(), Old.getForm(), DIEInteger(New));
76   }
77
78   uint64_t get() const {
79     assert(I);
80     return I->getDIEInteger().getValue();
81   }
82 };
83
84 class CompileUnit;
85 struct DeclMapInfo;
86 class NonRelocatableStringpool;
87
88 /// A DeclContext is a named program scope that is used for ODR
89 /// uniquing of types.
90 /// The set of DeclContext for the ODR-subject parts of a Dwarf link
91 /// is expanded (and uniqued) with each new object file processed. We
92 /// need to determine the context of each DIE in an linked object file
93 /// to see if the corresponding type has already been emitted.
94 ///
95 /// The contexts are conceptually organised as a tree (eg. a function
96 /// scope is contained in a namespace scope that contains other
97 /// scopes), but storing/accessing them in an actual tree is too
98 /// inefficient: we need to be able to very quickly query a context
99 /// for a given child context by name. Storing a StringMap in each
100 /// DeclContext would be too space inefficient.
101 /// The solution here is to give each DeclContext a link to its parent
102 /// (this allows to walk up the tree), but to query the existance of a
103 /// specific DeclContext using a separate DenseMap keyed on the hash
104 /// of the fully qualified name of the context.
105 class DeclContext {
106   unsigned QualifiedNameHash;
107   uint32_t Line;
108   uint32_t ByteSize;
109   uint16_t Tag;
110   StringRef Name;
111   StringRef File;
112   const DeclContext &Parent;
113   const DWARFDebugInfoEntryMinimal *LastSeenDIE;
114   uint32_t LastSeenCompileUnitID;
115   uint32_t CanonicalDIEOffset;
116
117   friend DeclMapInfo;
118
119 public:
120   typedef DenseSet<DeclContext *, DeclMapInfo> Map;
121
122   DeclContext()
123       : QualifiedNameHash(0), Line(0), ByteSize(0),
124         Tag(dwarf::DW_TAG_compile_unit), Name(), File(), Parent(*this),
125         LastSeenDIE(nullptr), LastSeenCompileUnitID(0), CanonicalDIEOffset(0) {}
126
127   DeclContext(unsigned Hash, uint32_t Line, uint32_t ByteSize, uint16_t Tag,
128               StringRef Name, StringRef File, const DeclContext &Parent,
129               const DWARFDebugInfoEntryMinimal *LastSeenDIE = nullptr,
130               unsigned CUId = 0)
131       : QualifiedNameHash(Hash), Line(Line), ByteSize(ByteSize), Tag(Tag),
132         Name(Name), File(File), Parent(Parent), LastSeenDIE(LastSeenDIE),
133         LastSeenCompileUnitID(CUId), CanonicalDIEOffset(0) {}
134
135   uint32_t getQualifiedNameHash() const { return QualifiedNameHash; }
136
137   bool setLastSeenDIE(CompileUnit &U, const DWARFDebugInfoEntryMinimal *Die);
138
139   uint32_t getCanonicalDIEOffset() const { return CanonicalDIEOffset; }
140   void setCanonicalDIEOffset(uint32_t Offset) { CanonicalDIEOffset = Offset; }
141
142   uint16_t getTag() const { return Tag; }
143   StringRef getName() const { return Name; }
144 };
145
146 /// Info type for the DenseMap storing the DeclContext pointers.
147 struct DeclMapInfo : private DenseMapInfo<DeclContext *> {
148   using DenseMapInfo<DeclContext *>::getEmptyKey;
149   using DenseMapInfo<DeclContext *>::getTombstoneKey;
150
151   static unsigned getHashValue(const DeclContext *Ctxt) {
152     return Ctxt->QualifiedNameHash;
153   }
154
155   static bool isEqual(const DeclContext *LHS, const DeclContext *RHS) {
156     if (RHS == getEmptyKey() || RHS == getTombstoneKey())
157       return RHS == LHS;
158     return LHS->QualifiedNameHash == RHS->QualifiedNameHash &&
159            LHS->Line == RHS->Line && LHS->ByteSize == RHS->ByteSize &&
160            LHS->Name.data() == RHS->Name.data() &&
161            LHS->File.data() == RHS->File.data() &&
162            LHS->Parent.QualifiedNameHash == RHS->Parent.QualifiedNameHash;
163   }
164 };
165
166 /// This class gives a tree-like API to the DenseMap that stores the
167 /// DeclContext objects. It also holds the BumpPtrAllocator where
168 /// these objects will be allocated.
169 class DeclContextTree {
170   BumpPtrAllocator Allocator;
171   DeclContext Root;
172   DeclContext::Map Contexts;
173
174 public:
175   /// Get the child of \a Context described by \a DIE in \a Unit. The
176   /// required strings will be interned in \a StringPool.
177   /// \returns The child DeclContext along with one bit that is set if
178   /// this context is invalid.
179   /// FIXME: the invalid bit along the return value is to emulate some
180   /// dsymutil-classic functionality. See the fucntion definition for
181   /// a more thorough discussion of its use.
182   PointerIntPair<DeclContext *, 1>
183   getChildDeclContext(DeclContext &Context,
184                       const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &Unit,
185                       NonRelocatableStringpool &StringPool);
186
187   DeclContext &getRoot() { return Root; }
188 };
189
190 /// \brief Stores all information relating to a compile unit, be it in
191 /// its original instance in the object file to its brand new cloned
192 /// and linked DIE tree.
193 class CompileUnit {
194 public:
195   /// \brief Information gathered about a DIE in the object file.
196   struct DIEInfo {
197     int64_t AddrAdjust; ///< Address offset to apply to the described entity.
198     DeclContext *Ctxt;  ///< ODR Declaration context.
199     DIE *Clone;         ///< Cloned version of that DIE.
200     uint32_t ParentIdx; ///< The index of this DIE's parent.
201     bool Keep;          ///< Is the DIE part of the linked output?
202     bool InDebugMap;    ///< Was this DIE's entity found in the map?
203   };
204
205   CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR)
206       : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
207         Ranges(RangeAlloc) {
208     Info.resize(OrigUnit.getNumDIEs());
209
210     const auto *CUDie = OrigUnit.getUnitDIE(false);
211     unsigned Lang = CUDie->getAttributeValueAsUnsignedConstant(
212         &OrigUnit, dwarf::DW_AT_language, 0);
213     HasODR = CanUseODR && (Lang == dwarf::DW_LANG_C_plus_plus ||
214                            Lang == dwarf::DW_LANG_C_plus_plus_03 ||
215                            Lang == dwarf::DW_LANG_C_plus_plus_11 ||
216                            Lang == dwarf::DW_LANG_C_plus_plus_14 ||
217                            Lang == dwarf::DW_LANG_ObjC_plus_plus);
218   }
219
220   CompileUnit(CompileUnit &&RHS)
221       : OrigUnit(RHS.OrigUnit), Info(std::move(RHS.Info)),
222         CUDie(std::move(RHS.CUDie)), StartOffset(RHS.StartOffset),
223         NextUnitOffset(RHS.NextUnitOffset), RangeAlloc(), Ranges(RangeAlloc) {
224     // The CompileUnit container has been 'reserve()'d with the right
225     // size. We cannot move the IntervalMap anyway.
226     llvm_unreachable("CompileUnits should not be moved.");
227   }
228
229   DWARFUnit &getOrigUnit() const { return OrigUnit; }
230
231   unsigned getUniqueID() const { return ID; }
232
233   DIE *getOutputUnitDIE() const { return CUDie; }
234   void setOutputUnitDIE(DIE *Die) { CUDie = Die; }
235
236   bool hasODR() const { return HasODR; }
237
238   DIEInfo &getInfo(unsigned Idx) { return Info[Idx]; }
239   const DIEInfo &getInfo(unsigned Idx) const { return Info[Idx]; }
240
241   uint64_t getStartOffset() const { return StartOffset; }
242   uint64_t getNextUnitOffset() const { return NextUnitOffset; }
243   void setStartOffset(uint64_t DebugInfoSize) { StartOffset = DebugInfoSize; }
244
245   uint64_t getLowPc() const { return LowPc; }
246   uint64_t getHighPc() const { return HighPc; }
247
248   Optional<PatchLocation> getUnitRangesAttribute() const {
249     return UnitRangeAttribute;
250   }
251   const FunctionIntervals &getFunctionRanges() const { return Ranges; }
252   const std::vector<PatchLocation> &getRangesAttributes() const {
253     return RangeAttributes;
254   }
255
256   const std::vector<std::pair<PatchLocation, int64_t>> &
257   getLocationAttributes() const {
258     return LocationAttributes;
259   }
260
261   /// \brief Compute the end offset for this unit. Must be
262   /// called after the CU's DIEs have been cloned.
263   /// \returns the next unit offset (which is also the current
264   /// debug_info section size).
265   uint64_t computeNextUnitOffset();
266
267   /// \brief Keep track of a forward reference to DIE \p Die in \p
268   /// RefUnit by \p Attr. The attribute should be fixed up later to
269   /// point to the absolute offset of \p Die in the debug_info section
270   /// or to the canonical offset of \p Ctxt if it is non-null.
271   void noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
272                             DeclContext *Ctxt, PatchLocation Attr);
273
274   /// \brief Apply all fixups recored by noteForwardReference().
275   void fixupForwardReferences();
276
277   /// \brief Add a function range [\p LowPC, \p HighPC) that is
278   /// relocatad by applying offset \p PCOffset.
279   void addFunctionRange(uint64_t LowPC, uint64_t HighPC, int64_t PCOffset);
280
281   /// \brief Keep track of a DW_AT_range attribute that we will need to
282   /// patch up later.
283   void noteRangeAttribute(const DIE &Die, PatchLocation Attr);
284
285   /// \brief Keep track of a location attribute pointing to a location
286   /// list in the debug_loc section.
287   void noteLocationAttribute(PatchLocation Attr, int64_t PcOffset);
288
289   /// \brief Add a name accelerator entry for \p Die with \p Name
290   /// which is stored in the string table at \p Offset.
291   void addNameAccelerator(const DIE *Die, const char *Name, uint32_t Offset,
292                           bool SkipPubnamesSection = false);
293
294   /// \brief Add a type accelerator entry for \p Die with \p Name
295   /// which is stored in the string table at \p Offset.
296   void addTypeAccelerator(const DIE *Die, const char *Name, uint32_t Offset);
297
298   struct AccelInfo {
299     StringRef Name;      ///< Name of the entry.
300     const DIE *Die;      ///< DIE this entry describes.
301     uint32_t NameOffset; ///< Offset of Name in the string pool.
302     bool SkipPubSection; ///< Emit this entry only in the apple_* sections.
303
304     AccelInfo(StringRef Name, const DIE *Die, uint32_t NameOffset,
305               bool SkipPubSection = false)
306         : Name(Name), Die(Die), NameOffset(NameOffset),
307           SkipPubSection(SkipPubSection) {}
308   };
309
310   const std::vector<AccelInfo> &getPubnames() const { return Pubnames; }
311   const std::vector<AccelInfo> &getPubtypes() const { return Pubtypes; }
312
313   /// Get the full path for file \a FileNum in the line table
314   const char *getResolvedPath(unsigned FileNum) {
315     if (FileNum >= ResolvedPaths.size())
316       return nullptr;
317     return ResolvedPaths[FileNum].size() ? ResolvedPaths[FileNum].c_str()
318                                          : nullptr;
319   }
320
321   /// Set the fully resolved path for the line-table's file \a FileNum
322   /// to \a Path.
323   void setResolvedPath(unsigned FileNum, const std::string &Path) {
324     if (ResolvedPaths.size() <= FileNum)
325       ResolvedPaths.resize(FileNum + 1);
326     ResolvedPaths[FileNum] = Path;
327   }
328
329 private:
330   DWARFUnit &OrigUnit;
331   unsigned ID;
332   std::vector<DIEInfo> Info; ///< DIE info indexed by DIE index.
333   DIE *CUDie;                ///< Root of the linked DIE tree.
334
335   uint64_t StartOffset;
336   uint64_t NextUnitOffset;
337
338   uint64_t LowPc;
339   uint64_t HighPc;
340
341   /// \brief A list of attributes to fixup with the absolute offset of
342   /// a DIE in the debug_info section.
343   ///
344   /// The offsets for the attributes in this array couldn't be set while
345   /// cloning because for cross-cu forward refences the target DIE's
346   /// offset isn't known you emit the reference attribute.
347   std::vector<std::tuple<DIE *, const CompileUnit *, DeclContext *,
348                          PatchLocation>> ForwardDIEReferences;
349
350   FunctionIntervals::Allocator RangeAlloc;
351   /// \brief The ranges in that interval map are the PC ranges for
352   /// functions in this unit, associated with the PC offset to apply
353   /// to the addresses to get the linked address.
354   FunctionIntervals Ranges;
355
356   /// \brief DW_AT_ranges attributes to patch after we have gathered
357   /// all the unit's function addresses.
358   /// @{
359   std::vector<PatchLocation> RangeAttributes;
360   Optional<PatchLocation> UnitRangeAttribute;
361   /// @}
362
363   /// \brief Location attributes that need to be transfered from th
364   /// original debug_loc section to the liked one. They are stored
365   /// along with the PC offset that is to be applied to their
366   /// function's address.
367   std::vector<std::pair<PatchLocation, int64_t>> LocationAttributes;
368
369   /// \brief Accelerator entries for the unit, both for the pub*
370   /// sections and the apple* ones.
371   /// @{
372   std::vector<AccelInfo> Pubnames;
373   std::vector<AccelInfo> Pubtypes;
374   /// @}
375
376   /// Cached resolved paths from the line table.
377   std::vector<std::string> ResolvedPaths;
378
379   /// Is this unit subject to the ODR rule?
380   bool HasODR;
381 };
382
383 uint64_t CompileUnit::computeNextUnitOffset() {
384   NextUnitOffset = StartOffset + 11 /* Header size */;
385   // The root DIE might be null, meaning that the Unit had nothing to
386   // contribute to the linked output. In that case, we will emit the
387   // unit header without any actual DIE.
388   if (CUDie)
389     NextUnitOffset += CUDie->getSize();
390   return NextUnitOffset;
391 }
392
393 /// \brief Keep track of a forward cross-cu reference from this unit
394 /// to \p Die that lives in \p RefUnit.
395 void CompileUnit::noteForwardReference(DIE *Die, const CompileUnit *RefUnit,
396                                        DeclContext *Ctxt, PatchLocation Attr) {
397   ForwardDIEReferences.emplace_back(Die, RefUnit, Ctxt, Attr);
398 }
399
400 /// \brief Apply all fixups recorded by noteForwardReference().
401 void CompileUnit::fixupForwardReferences() {
402   for (const auto &Ref : ForwardDIEReferences) {
403     DIE *RefDie;
404     const CompileUnit *RefUnit;
405     PatchLocation Attr;
406     DeclContext *Ctxt;
407     std::tie(RefDie, RefUnit, Ctxt, Attr) = Ref;
408     if (Ctxt && Ctxt->getCanonicalDIEOffset())
409       Attr.set(Ctxt->getCanonicalDIEOffset());
410     else
411       Attr.set(RefDie->getOffset() + RefUnit->getStartOffset());
412   }
413 }
414
415 void CompileUnit::addFunctionRange(uint64_t FuncLowPc, uint64_t FuncHighPc,
416                                    int64_t PcOffset) {
417   Ranges.insert(FuncLowPc, FuncHighPc, PcOffset);
418   this->LowPc = std::min(LowPc, FuncLowPc + PcOffset);
419   this->HighPc = std::max(HighPc, FuncHighPc + PcOffset);
420 }
421
422 void CompileUnit::noteRangeAttribute(const DIE &Die, PatchLocation Attr) {
423   if (Die.getTag() != dwarf::DW_TAG_compile_unit)
424     RangeAttributes.push_back(Attr);
425   else
426     UnitRangeAttribute = Attr;
427 }
428
429 void CompileUnit::noteLocationAttribute(PatchLocation Attr, int64_t PcOffset) {
430   LocationAttributes.emplace_back(Attr, PcOffset);
431 }
432
433 /// \brief Add a name accelerator entry for \p Die with \p Name
434 /// which is stored in the string table at \p Offset.
435 void CompileUnit::addNameAccelerator(const DIE *Die, const char *Name,
436                                      uint32_t Offset, bool SkipPubSection) {
437   Pubnames.emplace_back(Name, Die, Offset, SkipPubSection);
438 }
439
440 /// \brief Add a type accelerator entry for \p Die with \p Name
441 /// which is stored in the string table at \p Offset.
442 void CompileUnit::addTypeAccelerator(const DIE *Die, const char *Name,
443                                      uint32_t Offset) {
444   Pubtypes.emplace_back(Name, Die, Offset, false);
445 }
446
447 /// \brief A string table that doesn't need relocations.
448 ///
449 /// We are doing a final link, no need for a string table that
450 /// has relocation entries for every reference to it. This class
451 /// provides this ablitity by just associating offsets with
452 /// strings.
453 class NonRelocatableStringpool {
454 public:
455   /// \brief Entries are stored into the StringMap and simply linked
456   /// together through the second element of this pair in order to
457   /// keep track of insertion order.
458   typedef StringMap<std::pair<uint32_t, StringMapEntryBase *>, BumpPtrAllocator>
459       MapTy;
460
461   NonRelocatableStringpool()
462       : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
463     // Legacy dsymutil puts an empty string at the start of the line
464     // table.
465     getStringOffset("");
466   }
467
468   /// \brief Get the offset of string \p S in the string table. This
469   /// can insert a new element or return the offset of a preexisitng
470   /// one.
471   uint32_t getStringOffset(StringRef S);
472
473   /// \brief Get permanent storage for \p S (but do not necessarily
474   /// emit \p S in the output section).
475   /// \returns The StringRef that points to permanent storage to use
476   /// in place of \p S.
477   StringRef internString(StringRef S);
478
479   // \brief Return the first entry of the string table.
480   const MapTy::MapEntryTy *getFirstEntry() const {
481     return getNextEntry(&Sentinel);
482   }
483
484   // \brief Get the entry following \p E in the string table or null
485   // if \p E was the last entry.
486   const MapTy::MapEntryTy *getNextEntry(const MapTy::MapEntryTy *E) const {
487     return static_cast<const MapTy::MapEntryTy *>(E->getValue().second);
488   }
489
490   uint64_t getSize() { return CurrentEndOffset; }
491
492 private:
493   MapTy Strings;
494   uint32_t CurrentEndOffset;
495   MapTy::MapEntryTy Sentinel, *Last;
496 };
497
498 /// \brief Get the offset of string \p S in the string table. This
499 /// can insert a new element or return the offset of a preexisitng
500 /// one.
501 uint32_t NonRelocatableStringpool::getStringOffset(StringRef S) {
502   if (S.empty() && !Strings.empty())
503     return 0;
504
505   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
506   MapTy::iterator It;
507   bool Inserted;
508
509   // A non-empty string can't be at offset 0, so if we have an entry
510   // with a 0 offset, it must be a previously interned string.
511   std::tie(It, Inserted) = Strings.insert(std::make_pair(S, Entry));
512   if (Inserted || It->getValue().first == 0) {
513     // Set offset and chain at the end of the entries list.
514     It->getValue().first = CurrentEndOffset;
515     CurrentEndOffset += S.size() + 1; // +1 for the '\0'.
516     Last->getValue().second = &*It;
517     Last = &*It;
518   }
519   return It->getValue().first;
520 }
521
522 /// \brief Put \p S into the StringMap so that it gets permanent
523 /// storage, but do not actually link it in the chain of elements
524 /// that go into the output section. A latter call to
525 /// getStringOffset() with the same string will chain it though.
526 StringRef NonRelocatableStringpool::internString(StringRef S) {
527   std::pair<uint32_t, StringMapEntryBase *> Entry(0, nullptr);
528   auto InsertResult = Strings.insert(std::make_pair(S, Entry));
529   return InsertResult.first->getKey();
530 }
531
532 /// \brief The Dwarf streaming logic
533 ///
534 /// All interactions with the MC layer that is used to build the debug
535 /// information binary representation are handled in this class.
536 class DwarfStreamer {
537   /// \defgroup MCObjects MC layer objects constructed by the streamer
538   /// @{
539   std::unique_ptr<MCRegisterInfo> MRI;
540   std::unique_ptr<MCAsmInfo> MAI;
541   std::unique_ptr<MCObjectFileInfo> MOFI;
542   std::unique_ptr<MCContext> MC;
543   MCAsmBackend *MAB; // Owned by MCStreamer
544   std::unique_ptr<MCInstrInfo> MII;
545   std::unique_ptr<MCSubtargetInfo> MSTI;
546   MCCodeEmitter *MCE; // Owned by MCStreamer
547   MCStreamer *MS;     // Owned by AsmPrinter
548   std::unique_ptr<TargetMachine> TM;
549   std::unique_ptr<AsmPrinter> Asm;
550   /// @}
551
552   /// \brief the file we stream the linked Dwarf to.
553   std::unique_ptr<raw_fd_ostream> OutFile;
554
555   uint32_t RangesSectionSize;
556   uint32_t LocSectionSize;
557   uint32_t LineSectionSize;
558   uint32_t FrameSectionSize;
559
560   /// \brief Emit the pubnames or pubtypes section contribution for \p
561   /// Unit into \p Sec. The data is provided in \p Names.
562   void emitPubSectionForUnit(MCSection *Sec, StringRef Name,
563                              const CompileUnit &Unit,
564                              const std::vector<CompileUnit::AccelInfo> &Names);
565
566 public:
567   /// \brief Actually create the streamer and the ouptut file.
568   ///
569   /// This could be done directly in the constructor, but it feels
570   /// more natural to handle errors through return value.
571   bool init(Triple TheTriple, StringRef OutputFilename);
572
573   /// \brief Dump the file to the disk.
574   bool finish();
575
576   AsmPrinter &getAsmPrinter() const { return *Asm; }
577
578   /// \brief Set the current output section to debug_info and change
579   /// the MC Dwarf version to \p DwarfVersion.
580   void switchToDebugInfoSection(unsigned DwarfVersion);
581
582   /// \brief Emit the compilation unit header for \p Unit in the
583   /// debug_info section.
584   ///
585   /// As a side effect, this also switches the current Dwarf version
586   /// of the MC layer to the one of U.getOrigUnit().
587   void emitCompileUnitHeader(CompileUnit &Unit);
588
589   /// \brief Recursively emit the DIE tree rooted at \p Die.
590   void emitDIE(DIE &Die);
591
592   /// \brief Emit the abbreviation table \p Abbrevs to the
593   /// debug_abbrev section.
594   void emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs);
595
596   /// \brief Emit the string table described by \p Pool.
597   void emitStrings(const NonRelocatableStringpool &Pool);
598
599   /// \brief Emit debug_ranges for \p FuncRange by translating the
600   /// original \p Entries.
601   void emitRangesEntries(
602       int64_t UnitPcOffset, uint64_t OrigLowPc,
603       FunctionIntervals::const_iterator FuncRange,
604       const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
605       unsigned AddressSize);
606
607   /// \brief Emit debug_aranges entries for \p Unit and if \p
608   /// DoRangesSection is true, also emit the debug_ranges entries for
609   /// the DW_TAG_compile_unit's DW_AT_ranges attribute.
610   void emitUnitRangesEntries(CompileUnit &Unit, bool DoRangesSection);
611
612   uint32_t getRangesSectionSize() const { return RangesSectionSize; }
613
614   /// \brief Emit the debug_loc contribution for \p Unit by copying
615   /// the entries from \p Dwarf and offseting them. Update the
616   /// location attributes to point to the new entries.
617   void emitLocationsForUnit(const CompileUnit &Unit, DWARFContext &Dwarf);
618
619   /// \brief Emit the line table described in \p Rows into the
620   /// debug_line section.
621   void emitLineTableForUnit(MCDwarfLineTableParams Params,
622                             StringRef PrologueBytes, unsigned MinInstLength,
623                             std::vector<DWARFDebugLine::Row> &Rows,
624                             unsigned AdddressSize);
625
626   uint32_t getLineSectionSize() const { return LineSectionSize; }
627
628   /// \brief Emit the .debug_pubnames contribution for \p Unit.
629   void emitPubNamesForUnit(const CompileUnit &Unit);
630
631   /// \brief Emit the .debug_pubtypes contribution for \p Unit.
632   void emitPubTypesForUnit(const CompileUnit &Unit);
633
634   /// \brief Emit a CIE.
635   void emitCIE(StringRef CIEBytes);
636
637   /// \brief Emit an FDE with data \p Bytes.
638   void emitFDE(uint32_t CIEOffset, uint32_t AddreSize, uint32_t Address,
639                StringRef Bytes);
640
641   uint32_t getFrameSectionSize() const { return FrameSectionSize; }
642 };
643
644 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
645   std::string ErrorStr;
646   std::string TripleName;
647   StringRef Context = "dwarf streamer init";
648
649   // Get the target.
650   const Target *TheTarget =
651       TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
652   if (!TheTarget)
653     return error(ErrorStr, Context);
654   TripleName = TheTriple.getTriple();
655
656   // Create all the MC Objects.
657   MRI.reset(TheTarget->createMCRegInfo(TripleName));
658   if (!MRI)
659     return error(Twine("no register info for target ") + TripleName, Context);
660
661   MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
662   if (!MAI)
663     return error("no asm info for target " + TripleName, Context);
664
665   MOFI.reset(new MCObjectFileInfo);
666   MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
667   MOFI->InitMCObjectFileInfo(TheTriple, Reloc::Default, CodeModel::Default,
668                              *MC);
669
670   MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, "");
671   if (!MAB)
672     return error("no asm backend for target " + TripleName, Context);
673
674   MII.reset(TheTarget->createMCInstrInfo());
675   if (!MII)
676     return error("no instr info info for target " + TripleName, Context);
677
678   MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
679   if (!MSTI)
680     return error("no subtarget info for target " + TripleName, Context);
681
682   MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
683   if (!MCE)
684     return error("no code emitter for target " + TripleName, Context);
685
686   // Create the output file.
687   std::error_code EC;
688   OutFile =
689       llvm::make_unique<raw_fd_ostream>(OutputFilename, EC, sys::fs::F_None);
690   if (EC)
691     return error(Twine(OutputFilename) + ": " + EC.message(), Context);
692
693   MS = TheTarget->createMCObjectStreamer(TheTriple, *MC, *MAB, *OutFile, MCE,
694                                          *MSTI, false,
695                                          /*DWARFMustBeAtTheEnd*/ false);
696   if (!MS)
697     return error("no object streamer for target " + TripleName, Context);
698
699   // Finally create the AsmPrinter we'll use to emit the DIEs.
700   TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions()));
701   if (!TM)
702     return error("no target machine for target " + TripleName, Context);
703
704   Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
705   if (!Asm)
706     return error("no asm printer for target " + TripleName, Context);
707
708   RangesSectionSize = 0;
709   LocSectionSize = 0;
710   LineSectionSize = 0;
711   FrameSectionSize = 0;
712
713   return true;
714 }
715
716 bool DwarfStreamer::finish() {
717   MS->Finish();
718   return true;
719 }
720
721 /// \brief Set the current output section to debug_info and change
722 /// the MC Dwarf version to \p DwarfVersion.
723 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
724   MS->SwitchSection(MOFI->getDwarfInfoSection());
725   MC->setDwarfVersion(DwarfVersion);
726 }
727
728 /// \brief Emit the compilation unit header for \p Unit in the
729 /// debug_info section.
730 ///
731 /// A Dwarf scetion header is encoded as:
732 ///  uint32_t   Unit length (omiting this field)
733 ///  uint16_t   Version
734 ///  uint32_t   Abbreviation table offset
735 ///  uint8_t    Address size
736 ///
737 /// Leading to a total of 11 bytes.
738 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
739   unsigned Version = Unit.getOrigUnit().getVersion();
740   switchToDebugInfoSection(Version);
741
742   // Emit size of content not including length itself. The size has
743   // already been computed in CompileUnit::computeOffsets(). Substract
744   // 4 to that size to account for the length field.
745   Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
746   Asm->EmitInt16(Version);
747   // We share one abbreviations table across all units so it's always at the
748   // start of the section.
749   Asm->EmitInt32(0);
750   Asm->EmitInt8(Unit.getOrigUnit().getAddressByteSize());
751 }
752
753 /// \brief Emit the \p Abbrevs array as the shared abbreviation table
754 /// for the linked Dwarf file.
755 void DwarfStreamer::emitAbbrevs(const std::vector<DIEAbbrev *> &Abbrevs) {
756   MS->SwitchSection(MOFI->getDwarfAbbrevSection());
757   Asm->emitDwarfAbbrevs(Abbrevs);
758 }
759
760 /// \brief Recursively emit the DIE tree rooted at \p Die.
761 void DwarfStreamer::emitDIE(DIE &Die) {
762   MS->SwitchSection(MOFI->getDwarfInfoSection());
763   Asm->emitDwarfDIE(Die);
764 }
765
766 /// \brief Emit the debug_str section stored in \p Pool.
767 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
768   Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
769   for (auto *Entry = Pool.getFirstEntry(); Entry;
770        Entry = Pool.getNextEntry(Entry))
771     Asm->OutStreamer->EmitBytes(
772         StringRef(Entry->getKey().data(), Entry->getKey().size() + 1));
773 }
774
775 /// \brief Emit the debug_range section contents for \p FuncRange by
776 /// translating the original \p Entries. The debug_range section
777 /// format is totally trivial, consisting just of pairs of address
778 /// sized addresses describing the ranges.
779 void DwarfStreamer::emitRangesEntries(
780     int64_t UnitPcOffset, uint64_t OrigLowPc,
781     FunctionIntervals::const_iterator FuncRange,
782     const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
783     unsigned AddressSize) {
784   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
785
786   // Offset each range by the right amount.
787   int64_t PcOffset = FuncRange.value() + UnitPcOffset;
788   for (const auto &Range : Entries) {
789     if (Range.isBaseAddressSelectionEntry(AddressSize)) {
790       warn("unsupported base address selection operation",
791            "emitting debug_ranges");
792       break;
793     }
794     // Do not emit empty ranges.
795     if (Range.StartAddress == Range.EndAddress)
796       continue;
797
798     // All range entries should lie in the function range.
799     if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
800           Range.EndAddress + OrigLowPc <= FuncRange.stop()))
801       warn("inconsistent range data.", "emitting debug_ranges");
802     MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
803     MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
804     RangesSectionSize += 2 * AddressSize;
805   }
806
807   // Add the terminator entry.
808   MS->EmitIntValue(0, AddressSize);
809   MS->EmitIntValue(0, AddressSize);
810   RangesSectionSize += 2 * AddressSize;
811 }
812
813 /// \brief Emit the debug_aranges contribution of a unit and
814 /// if \p DoDebugRanges is true the debug_range contents for a
815 /// compile_unit level DW_AT_ranges attribute (Which are basically the
816 /// same thing with a different base address).
817 /// Just aggregate all the ranges gathered inside that unit.
818 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
819                                           bool DoDebugRanges) {
820   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
821   // Gather the ranges in a vector, so that we can simplify them. The
822   // IntervalMap will have coalesced the non-linked ranges, but here
823   // we want to coalesce the linked addresses.
824   std::vector<std::pair<uint64_t, uint64_t>> Ranges;
825   const auto &FunctionRanges = Unit.getFunctionRanges();
826   for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
827        Range != End; ++Range)
828     Ranges.push_back(std::make_pair(Range.start() + Range.value(),
829                                     Range.stop() + Range.value()));
830
831   // The object addresses where sorted, but again, the linked
832   // addresses might end up in a different order.
833   std::sort(Ranges.begin(), Ranges.end());
834
835   if (!Ranges.empty()) {
836     MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
837
838     MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
839     MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
840
841     unsigned HeaderSize =
842         sizeof(int32_t) + // Size of contents (w/o this field
843         sizeof(int16_t) + // DWARF ARange version number
844         sizeof(int32_t) + // Offset of CU in the .debug_info section
845         sizeof(int8_t) +  // Pointer Size (in bytes)
846         sizeof(int8_t);   // Segment Size (in bytes)
847
848     unsigned TupleSize = AddressSize * 2;
849     unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
850
851     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
852     Asm->OutStreamer->EmitLabel(BeginLabel);
853     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION); // Version number
854     Asm->EmitInt32(Unit.getStartOffset());     // Corresponding unit's offset
855     Asm->EmitInt8(AddressSize);                // Address size
856     Asm->EmitInt8(0);                          // Segment size
857
858     Asm->OutStreamer->EmitFill(Padding, 0x0);
859
860     for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
861          ++Range) {
862       uint64_t RangeStart = Range->first;
863       MS->EmitIntValue(RangeStart, AddressSize);
864       while ((Range + 1) != End && Range->second == (Range + 1)->first)
865         ++Range;
866       MS->EmitIntValue(Range->second - RangeStart, AddressSize);
867     }
868
869     // Emit terminator
870     Asm->OutStreamer->EmitIntValue(0, AddressSize);
871     Asm->OutStreamer->EmitIntValue(0, AddressSize);
872     Asm->OutStreamer->EmitLabel(EndLabel);
873   }
874
875   if (!DoDebugRanges)
876     return;
877
878   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
879   // Offset each range by the right amount.
880   int64_t PcOffset = -Unit.getLowPc();
881   // Emit coalesced ranges.
882   for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
883     MS->EmitIntValue(Range->first + PcOffset, AddressSize);
884     while (Range + 1 != End && Range->second == (Range + 1)->first)
885       ++Range;
886     MS->EmitIntValue(Range->second + PcOffset, AddressSize);
887     RangesSectionSize += 2 * AddressSize;
888   }
889
890   // Add the terminator entry.
891   MS->EmitIntValue(0, AddressSize);
892   MS->EmitIntValue(0, AddressSize);
893   RangesSectionSize += 2 * AddressSize;
894 }
895
896 /// \brief Emit location lists for \p Unit and update attribtues to
897 /// point to the new entries.
898 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
899                                          DWARFContext &Dwarf) {
900   const auto &Attributes = Unit.getLocationAttributes();
901
902   if (Attributes.empty())
903     return;
904
905   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
906
907   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
908   const DWARFSection &InputSec = Dwarf.getLocSection();
909   DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
910   DWARFUnit &OrigUnit = Unit.getOrigUnit();
911   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
912   int64_t UnitPcOffset = 0;
913   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
914       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
915   if (OrigLowPc != -1ULL)
916     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
917
918   for (const auto &Attr : Attributes) {
919     uint32_t Offset = Attr.first.get();
920     Attr.first.set(LocSectionSize);
921     // This is the quantity to add to the old location address to get
922     // the correct address for the new one.
923     int64_t LocPcOffset = Attr.second + UnitPcOffset;
924     while (Data.isValidOffset(Offset)) {
925       uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
926       uint64_t High = Data.getUnsigned(&Offset, AddressSize);
927       LocSectionSize += 2 * AddressSize;
928       if (Low == 0 && High == 0) {
929         Asm->OutStreamer->EmitIntValue(0, AddressSize);
930         Asm->OutStreamer->EmitIntValue(0, AddressSize);
931         break;
932       }
933       Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
934       Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
935       uint64_t Length = Data.getU16(&Offset);
936       Asm->OutStreamer->EmitIntValue(Length, 2);
937       // Just copy the bytes over.
938       Asm->OutStreamer->EmitBytes(
939           StringRef(InputSec.Data.substr(Offset, Length)));
940       Offset += Length;
941       LocSectionSize += Length + 2;
942     }
943   }
944 }
945
946 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
947                                          StringRef PrologueBytes,
948                                          unsigned MinInstLength,
949                                          std::vector<DWARFDebugLine::Row> &Rows,
950                                          unsigned PointerSize) {
951   // Switch to the section where the table will be emitted into.
952   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
953   MCSymbol *LineStartSym = MC->createTempSymbol();
954   MCSymbol *LineEndSym = MC->createTempSymbol();
955
956   // The first 4 bytes is the total length of the information for this
957   // compilation unit (not including these 4 bytes for the length).
958   Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
959   Asm->OutStreamer->EmitLabel(LineStartSym);
960   // Copy Prologue.
961   MS->EmitBytes(PrologueBytes);
962   LineSectionSize += PrologueBytes.size() + 4;
963
964   SmallString<128> EncodingBuffer;
965   raw_svector_ostream EncodingOS(EncodingBuffer);
966
967   if (Rows.empty()) {
968     // We only have the dummy entry, dsymutil emits an entry with a 0
969     // address in that case.
970     MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
971     MS->EmitBytes(EncodingOS.str());
972     LineSectionSize += EncodingBuffer.size();
973     MS->EmitLabel(LineEndSym);
974     return;
975   }
976
977   // Line table state machine fields
978   unsigned FileNum = 1;
979   unsigned LastLine = 1;
980   unsigned Column = 0;
981   unsigned IsStatement = 1;
982   unsigned Isa = 0;
983   uint64_t Address = -1ULL;
984
985   unsigned RowsSinceLastSequence = 0;
986
987   for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
988     auto &Row = Rows[Idx];
989
990     int64_t AddressDelta;
991     if (Address == -1ULL) {
992       MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
993       MS->EmitULEB128IntValue(PointerSize + 1);
994       MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
995       MS->EmitIntValue(Row.Address, PointerSize);
996       LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
997       AddressDelta = 0;
998     } else {
999       AddressDelta = (Row.Address - Address) / MinInstLength;
1000     }
1001
1002     // FIXME: code copied and transfromed from
1003     // MCDwarf.cpp::EmitDwarfLineTable. We should find a way to share
1004     // this code, but the current compatibility requirement with
1005     // classic dsymutil makes it hard. Revisit that once this
1006     // requirement is dropped.
1007
1008     if (FileNum != Row.File) {
1009       FileNum = Row.File;
1010       MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
1011       MS->EmitULEB128IntValue(FileNum);
1012       LineSectionSize += 1 + getULEB128Size(FileNum);
1013     }
1014     if (Column != Row.Column) {
1015       Column = Row.Column;
1016       MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
1017       MS->EmitULEB128IntValue(Column);
1018       LineSectionSize += 1 + getULEB128Size(Column);
1019     }
1020
1021     // FIXME: We should handle the discriminator here, but dsymutil
1022     // doesn' consider it, thus ignore it for now.
1023
1024     if (Isa != Row.Isa) {
1025       Isa = Row.Isa;
1026       MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
1027       MS->EmitULEB128IntValue(Isa);
1028       LineSectionSize += 1 + getULEB128Size(Isa);
1029     }
1030     if (IsStatement != Row.IsStmt) {
1031       IsStatement = Row.IsStmt;
1032       MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
1033       LineSectionSize += 1;
1034     }
1035     if (Row.BasicBlock) {
1036       MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
1037       LineSectionSize += 1;
1038     }
1039
1040     if (Row.PrologueEnd) {
1041       MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
1042       LineSectionSize += 1;
1043     }
1044
1045     if (Row.EpilogueBegin) {
1046       MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
1047       LineSectionSize += 1;
1048     }
1049
1050     int64_t LineDelta = int64_t(Row.Line) - LastLine;
1051     if (!Row.EndSequence) {
1052       MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
1053       MS->EmitBytes(EncodingOS.str());
1054       LineSectionSize += EncodingBuffer.size();
1055       EncodingBuffer.resize(0);
1056       EncodingOS.resync();
1057       Address = Row.Address;
1058       LastLine = Row.Line;
1059       RowsSinceLastSequence++;
1060     } else {
1061       if (LineDelta) {
1062         MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
1063         MS->EmitSLEB128IntValue(LineDelta);
1064         LineSectionSize += 1 + getSLEB128Size(LineDelta);
1065       }
1066       if (AddressDelta) {
1067         MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
1068         MS->EmitULEB128IntValue(AddressDelta);
1069         LineSectionSize += 1 + getULEB128Size(AddressDelta);
1070       }
1071       MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1072       MS->EmitBytes(EncodingOS.str());
1073       LineSectionSize += EncodingBuffer.size();
1074       EncodingBuffer.resize(0);
1075       EncodingOS.resync();
1076       Address = -1ULL;
1077       LastLine = FileNum = IsStatement = 1;
1078       RowsSinceLastSequence = Column = Isa = 0;
1079     }
1080   }
1081
1082   if (RowsSinceLastSequence) {
1083     MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1084     MS->EmitBytes(EncodingOS.str());
1085     LineSectionSize += EncodingBuffer.size();
1086     EncodingBuffer.resize(0);
1087     EncodingOS.resync();
1088   }
1089
1090   MS->EmitLabel(LineEndSym);
1091 }
1092
1093 /// \brief Emit the pubnames or pubtypes section contribution for \p
1094 /// Unit into \p Sec. The data is provided in \p Names.
1095 void DwarfStreamer::emitPubSectionForUnit(
1096     MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
1097     const std::vector<CompileUnit::AccelInfo> &Names) {
1098   if (Names.empty())
1099     return;
1100
1101   // Start the dwarf pubnames section.
1102   Asm->OutStreamer->SwitchSection(Sec);
1103   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
1104   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
1105
1106   bool HeaderEmitted = false;
1107   // Emit the pubnames for this compilation unit.
1108   for (const auto &Name : Names) {
1109     if (Name.SkipPubSection)
1110       continue;
1111
1112     if (!HeaderEmitted) {
1113       // Emit the header.
1114       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
1115       Asm->OutStreamer->EmitLabel(BeginLabel);
1116       Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
1117       Asm->EmitInt32(Unit.getStartOffset());      // Unit offset
1118       Asm->EmitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
1119       HeaderEmitted = true;
1120     }
1121     Asm->EmitInt32(Name.Die->getOffset());
1122     Asm->OutStreamer->EmitBytes(
1123         StringRef(Name.Name.data(), Name.Name.size() + 1));
1124   }
1125
1126   if (!HeaderEmitted)
1127     return;
1128   Asm->EmitInt32(0); // End marker.
1129   Asm->OutStreamer->EmitLabel(EndLabel);
1130 }
1131
1132 /// \brief Emit .debug_pubnames for \p Unit.
1133 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
1134   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
1135                         "names", Unit, Unit.getPubnames());
1136 }
1137
1138 /// \brief Emit .debug_pubtypes for \p Unit.
1139 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
1140   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
1141                         "types", Unit, Unit.getPubtypes());
1142 }
1143
1144 /// \brief Emit a CIE into the debug_frame section.
1145 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
1146   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1147
1148   MS->EmitBytes(CIEBytes);
1149   FrameSectionSize += CIEBytes.size();
1150 }
1151
1152 /// \brief Emit a FDE into the debug_frame section. \p FDEBytes
1153 /// contains the FDE data without the length, CIE offset and address
1154 /// which will be replaced with the paramter values.
1155 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
1156                             uint32_t Address, StringRef FDEBytes) {
1157   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
1158
1159   MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
1160   MS->EmitIntValue(CIEOffset, 4);
1161   MS->EmitIntValue(Address, AddrSize);
1162   MS->EmitBytes(FDEBytes);
1163   FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
1164 }
1165
1166 /// \brief The core of the Dwarf linking logic.
1167 ///
1168 /// The link of the dwarf information from the object files will be
1169 /// driven by the selection of 'root DIEs', which are DIEs that
1170 /// describe variables or functions that are present in the linked
1171 /// binary (and thus have entries in the debug map). All the debug
1172 /// information that will be linked (the DIEs, but also the line
1173 /// tables, ranges, ...) is derived from that set of root DIEs.
1174 ///
1175 /// The root DIEs are identified because they contain relocations that
1176 /// correspond to a debug map entry at specific places (the low_pc for
1177 /// a function, the location for a variable). These relocations are
1178 /// called ValidRelocs in the DwarfLinker and are gathered as a very
1179 /// first step when we start processing a DebugMapObject.
1180 class DwarfLinker {
1181 public:
1182   DwarfLinker(StringRef OutputFilename, const LinkOptions &Options)
1183       : OutputFilename(OutputFilename), Options(Options),
1184         BinHolder(Options.Verbose), LastCIEOffset(0) {}
1185
1186   ~DwarfLinker() {
1187     for (auto *Abbrev : Abbreviations)
1188       delete Abbrev;
1189   }
1190
1191   /// \brief Link the contents of the DebugMap.
1192   bool link(const DebugMap &);
1193
1194 private:
1195   /// \brief Called at the start of a debug object link.
1196   void startDebugObject(DWARFContext &, DebugMapObject &);
1197
1198   /// \brief Called at the end of a debug object link.
1199   void endDebugObject();
1200
1201   /// \defgroup FindValidRelocations Translate debug map into a list
1202   /// of relevant relocations
1203   ///
1204   /// @{
1205   struct ValidReloc {
1206     uint32_t Offset;
1207     uint32_t Size;
1208     uint64_t Addend;
1209     const DebugMapObject::DebugMapEntry *Mapping;
1210
1211     ValidReloc(uint32_t Offset, uint32_t Size, uint64_t Addend,
1212                const DebugMapObject::DebugMapEntry *Mapping)
1213         : Offset(Offset), Size(Size), Addend(Addend), Mapping(Mapping) {}
1214
1215     bool operator<(const ValidReloc &RHS) const { return Offset < RHS.Offset; }
1216   };
1217
1218   /// \brief The valid relocations for the current DebugMapObject.
1219   /// This vector is sorted by relocation offset.
1220   std::vector<ValidReloc> ValidRelocs;
1221
1222   /// \brief Index into ValidRelocs of the next relocation to
1223   /// consider. As we walk the DIEs in acsending file offset and as
1224   /// ValidRelocs is sorted by file offset, keeping this index
1225   /// uptodate is all we have to do to have a cheap lookup during the
1226   /// root DIE selection and during DIE cloning.
1227   unsigned NextValidReloc;
1228
1229   bool findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1230                                   const DebugMapObject &DMO);
1231
1232   bool findValidRelocs(const object::SectionRef &Section,
1233                        const object::ObjectFile &Obj,
1234                        const DebugMapObject &DMO);
1235
1236   void findValidRelocsMachO(const object::SectionRef &Section,
1237                             const object::MachOObjectFile &Obj,
1238                             const DebugMapObject &DMO);
1239   /// @}
1240
1241   /// \defgroup FindRootDIEs Find DIEs corresponding to debug map entries.
1242   ///
1243   /// @{
1244   /// \brief Recursively walk the \p DIE tree and look for DIEs to
1245   /// keep. Store that information in \p CU's DIEInfo.
1246   void lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
1247                          const DebugMapObject &DMO, CompileUnit &CU,
1248                          unsigned Flags);
1249
1250   /// \brief Flags passed to DwarfLinker::lookForDIEsToKeep
1251   enum TravesalFlags {
1252     TF_Keep = 1 << 0,            ///< Mark the traversed DIEs as kept.
1253     TF_InFunctionScope = 1 << 1, ///< Current scope is a fucntion scope.
1254     TF_DependencyWalk = 1 << 2,  ///< Walking the dependencies of a kept DIE.
1255     TF_ParentWalk = 1 << 3,      ///< Walking up the parents of a kept DIE.
1256     TF_ODR = 1 << 4,             ///< Use the ODR whhile keeping dependants.
1257   };
1258
1259   /// \brief Mark the passed DIE as well as all the ones it depends on
1260   /// as kept.
1261   void keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
1262                                CompileUnit::DIEInfo &MyInfo,
1263                                const DebugMapObject &DMO, CompileUnit &CU,
1264                                bool UseODR);
1265
1266   unsigned shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
1267                          CompileUnit &Unit, CompileUnit::DIEInfo &MyInfo,
1268                          unsigned Flags);
1269
1270   unsigned shouldKeepVariableDIE(const DWARFDebugInfoEntryMinimal &DIE,
1271                                  CompileUnit &Unit,
1272                                  CompileUnit::DIEInfo &MyInfo, unsigned Flags);
1273
1274   unsigned shouldKeepSubprogramDIE(const DWARFDebugInfoEntryMinimal &DIE,
1275                                    CompileUnit &Unit,
1276                                    CompileUnit::DIEInfo &MyInfo,
1277                                    unsigned Flags);
1278
1279   bool hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1280                           CompileUnit::DIEInfo &Info);
1281   /// @}
1282
1283   /// \defgroup Linking Methods used to link the debug information
1284   ///
1285   /// @{
1286   /// \brief Recursively clone \p InputDIE into an tree of DIE objects
1287   /// where useless (as decided by lookForDIEsToKeep()) bits have been
1288   /// stripped out and addresses have been rewritten according to the
1289   /// debug map.
1290   ///
1291   /// \param OutOffset is the offset the cloned DIE in the output
1292   /// compile unit.
1293   /// \param PCOffset (while cloning a function scope) is the offset
1294   /// applied to the entry point of the function to get the linked address.
1295   ///
1296   /// \returns the root of the cloned tree.
1297   DIE *cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &U,
1298                 int64_t PCOffset, uint32_t OutOffset);
1299
1300   typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1301
1302   /// \brief Information gathered and exchanged between the various
1303   /// clone*Attributes helpers about the attributes of a particular DIE.
1304   struct AttributesInfo {
1305     const char *Name, *MangledName;         ///< Names.
1306     uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1307
1308     uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1309     int64_t PCOffset;    ///< Offset to apply to PC addresses inside a function.
1310
1311     bool HasLowPc;      ///< Does the DIE have a low_pc attribute?
1312     bool IsDeclaration; ///< Is this DIE only a declaration?
1313
1314     AttributesInfo()
1315         : Name(nullptr), MangledName(nullptr), NameOffset(0),
1316           MangledNameOffset(0), OrigHighPc(0), PCOffset(0), HasLowPc(false),
1317           IsDeclaration(false) {}
1318   };
1319
1320   /// \brief Helper for cloneDIE.
1321   unsigned cloneAttribute(DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
1322                           CompileUnit &U, const DWARFFormValue &Val,
1323                           const AttributeSpec AttrSpec, unsigned AttrSize,
1324                           AttributesInfo &AttrInfo);
1325
1326   /// \brief Helper for cloneDIE.
1327   unsigned cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
1328                                 const DWARFFormValue &Val, const DWARFUnit &U);
1329
1330   /// \brief Helper for cloneDIE.
1331   unsigned
1332   cloneDieReferenceAttribute(DIE &Die,
1333                              const DWARFDebugInfoEntryMinimal &InputDIE,
1334                              AttributeSpec AttrSpec, unsigned AttrSize,
1335                              const DWARFFormValue &Val, CompileUnit &Unit);
1336
1337   /// \brief Helper for cloneDIE.
1338   unsigned cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
1339                                const DWARFFormValue &Val, unsigned AttrSize);
1340
1341   /// \brief Helper for cloneDIE.
1342   unsigned cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
1343                                  const DWARFFormValue &Val,
1344                                  const CompileUnit &Unit, AttributesInfo &Info);
1345
1346   /// \brief Helper for cloneDIE.
1347   unsigned cloneScalarAttribute(DIE &Die,
1348                                 const DWARFDebugInfoEntryMinimal &InputDIE,
1349                                 CompileUnit &U, AttributeSpec AttrSpec,
1350                                 const DWARFFormValue &Val, unsigned AttrSize,
1351                                 AttributesInfo &Info);
1352
1353   /// \brief Helper for cloneDIE.
1354   bool applyValidRelocs(MutableArrayRef<char> Data, uint32_t BaseOffset,
1355                         bool isLittleEndian);
1356
1357   /// \brief Assign an abbreviation number to \p Abbrev
1358   void AssignAbbrev(DIEAbbrev &Abbrev);
1359
1360   /// \brief FoldingSet that uniques the abbreviations.
1361   FoldingSet<DIEAbbrev> AbbreviationsSet;
1362   /// \brief Storage for the unique Abbreviations.
1363   /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
1364   /// be changed to a vecot of unique_ptrs.
1365   std::vector<DIEAbbrev *> Abbreviations;
1366
1367   /// \brief Compute and emit debug_ranges section for \p Unit, and
1368   /// patch the attributes referencing it.
1369   void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1370
1371   /// \brief Generate and emit the DW_AT_ranges attribute for a
1372   /// compile_unit if it had one.
1373   void generateUnitRanges(CompileUnit &Unit) const;
1374
1375   /// \brief Extract the line tables fromt he original dwarf, extract
1376   /// the relevant parts according to the linked function ranges and
1377   /// emit the result in the debug_line section.
1378   void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1379
1380   /// \brief Emit the accelerator entries for \p Unit.
1381   void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1382
1383   /// \brief Patch the frame info for an object file and emit it.
1384   void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1385                                unsigned AddressSize);
1386
1387   /// \brief DIELoc objects that need to be destructed (but not freed!).
1388   std::vector<DIELoc *> DIELocs;
1389   /// \brief DIEBlock objects that need to be destructed (but not freed!).
1390   std::vector<DIEBlock *> DIEBlocks;
1391   /// \brief Allocator used for all the DIEValue objects.
1392   BumpPtrAllocator DIEAlloc;
1393   /// @}
1394
1395   /// ODR Contexts for that link.
1396   DeclContextTree ODRContexts;
1397
1398   /// \defgroup Helpers Various helper methods.
1399   ///
1400   /// @{
1401   const DWARFDebugInfoEntryMinimal *
1402   resolveDIEReference(const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1403                       const DWARFDebugInfoEntryMinimal &DIE,
1404                       CompileUnit *&ReferencedCU);
1405
1406   CompileUnit *getUnitForOffset(unsigned Offset);
1407
1408   bool getDIENames(const DWARFDebugInfoEntryMinimal &Die, DWARFUnit &U,
1409                    AttributesInfo &Info);
1410
1411   void reportWarning(const Twine &Warning, const DWARFUnit *Unit = nullptr,
1412                      const DWARFDebugInfoEntryMinimal *DIE = nullptr) const;
1413
1414   bool createStreamer(Triple TheTriple, StringRef OutputFilename);
1415
1416   /// \brief Attempt to load a debug object from disk.
1417   ErrorOr<const object::ObjectFile &> loadObject(BinaryHolder &BinaryHolder,
1418                                                  DebugMapObject &Obj,
1419                                                  const DebugMap &Map);
1420   /// @}
1421
1422 private:
1423   std::string OutputFilename;
1424   LinkOptions Options;
1425   BinaryHolder BinHolder;
1426   std::unique_ptr<DwarfStreamer> Streamer;
1427
1428   /// The units of the current debug map object.
1429   std::vector<CompileUnit> Units;
1430
1431   /// The debug map object curently under consideration.
1432   DebugMapObject *CurrentDebugObject;
1433
1434   /// \brief The Dwarf string pool
1435   NonRelocatableStringpool StringPool;
1436
1437   /// \brief This map is keyed by the entry PC of functions in that
1438   /// debug object and the associated value is a pair storing the
1439   /// corresponding end PC and the offset to apply to get the linked
1440   /// address.
1441   ///
1442   /// See startDebugObject() for a more complete description of its use.
1443   std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1444
1445   /// \brief The CIEs that have been emitted in the output
1446   /// section. The actual CIE data serves a the key to this StringMap,
1447   /// this takes care of comparing the semantics of CIEs defined in
1448   /// different object files.
1449   StringMap<uint32_t> EmittedCIEs;
1450
1451   /// Offset of the last CIE that has been emitted in the output
1452   /// debug_frame section.
1453   uint32_t LastCIEOffset;
1454 };
1455
1456 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1457 /// returning our CompileUnit object instead.
1458 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1459   auto CU =
1460       std::upper_bound(Units.begin(), Units.end(), Offset,
1461                        [](uint32_t LHS, const CompileUnit &RHS) {
1462                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
1463                        });
1464   return CU != Units.end() ? &*CU : nullptr;
1465 }
1466
1467 /// \brief Resolve the DIE attribute reference that has been
1468 /// extracted in \p RefValue. The resulting DIE migh be in another
1469 /// CompileUnit which is stored into \p ReferencedCU.
1470 /// \returns null if resolving fails for any reason.
1471 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1472     const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1473     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1474   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1475   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1476
1477   if ((RefCU = getUnitForOffset(RefOffset)))
1478     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1479       return RefDie;
1480
1481   reportWarning("could not find referenced DIE", &Unit, &DIE);
1482   return nullptr;
1483 }
1484
1485 /// \returns whether the passed \a Attr type might contain a DIE
1486 /// reference suitable for ODR uniquing.
1487 static bool isODRAttribute(uint16_t Attr) {
1488   switch (Attr) {
1489   default:
1490     return false;
1491   case dwarf::DW_AT_type:
1492   case dwarf::DW_AT_containing_type:
1493   case dwarf::DW_AT_specification:
1494   case dwarf::DW_AT_abstract_origin:
1495   case dwarf::DW_AT_import:
1496     return true;
1497   }
1498   llvm_unreachable("Improper attribute.");
1499 }
1500
1501 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1502 /// the context if it is ambiguous.
1503 ///
1504 /// In the current implementation, we don't handle overloaded
1505 /// functions well, because the argument types are not taken into
1506 /// account when computing the DeclContext tree.
1507 ///
1508 /// Some of this is mitigated byt using mangled names that do contain
1509 /// the arguments types, but sometimes (eg. with function templates)
1510 /// we don't have that. In that case, just do not unique anything that
1511 /// refers to the contexts we are not able to distinguish.
1512 ///
1513 /// If a context that is not a namespace appears twice in the same CU,
1514 /// we know it is ambiguous. Make it invalid.
1515 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1516                                  const DWARFDebugInfoEntryMinimal *Die) {
1517   if (LastSeenCompileUnitID == U.getUniqueID()) {
1518     DWARFUnit &OrigUnit = U.getOrigUnit();
1519     uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1520     U.getInfo(FirstIdx).Ctxt = nullptr;
1521     return false;
1522   }
1523
1524   LastSeenCompileUnitID = U.getUniqueID();
1525   LastSeenDIE = Die;
1526   return true;
1527 }
1528
1529 /// Get the child context of \a Context corresponding to \a DIE.
1530 ///
1531 /// \returns the child context or null if we shouldn't track children
1532 /// contexts. It also returns an additional bit meaning 'invalid'. An
1533 /// invalid context means it shouldn't be considered for uniquing, but
1534 /// its not returning null, because some children of that context
1535 /// might be uniquing candidates.
1536 /// FIXME: this is for dsymutil-classic compatibility, I don't think
1537 /// it buys us much.
1538 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1539     DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1540     NonRelocatableStringpool &StringPool) {
1541   unsigned Tag = DIE->getTag();
1542
1543   // FIXME: dsymutil-classic compat: We should bail out here if we
1544   // have a specification or an abstract_origin. We will get the
1545   // parent context wrong here.
1546
1547   switch (Tag) {
1548   default:
1549     // By default stop gathering child contexts.
1550     return PointerIntPair<DeclContext *, 1>(nullptr);
1551   case dwarf::DW_TAG_compile_unit:
1552     // FIXME: Add support for DW_TAG_module.
1553     return PointerIntPair<DeclContext *, 1>(&Context);
1554   case dwarf::DW_TAG_subprogram:
1555     // Do not unique anything inside CU local functions.
1556     if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1557          Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1558         !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1559                                                   dwarf::DW_AT_external, 0))
1560       return PointerIntPair<DeclContext *, 1>(nullptr);
1561   // Fallthrough
1562   case dwarf::DW_TAG_member:
1563   case dwarf::DW_TAG_namespace:
1564   case dwarf::DW_TAG_structure_type:
1565   case dwarf::DW_TAG_class_type:
1566   case dwarf::DW_TAG_union_type:
1567   case dwarf::DW_TAG_enumeration_type:
1568   case dwarf::DW_TAG_typedef:
1569     // Artificial things might be ambiguous, because they might be
1570     // created on demand. For example implicitely defined constructors
1571     // are ambiguous because of the way we identify contexts, and they
1572     // won't be generated everytime everywhere.
1573     if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1574                                                  dwarf::DW_AT_artificial, 0))
1575       return PointerIntPair<DeclContext *, 1>(nullptr);
1576     break;
1577   }
1578
1579   const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1580   const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1581   StringRef NameRef;
1582   StringRef ShortNameRef;
1583   StringRef FileRef;
1584
1585   if (Name)
1586     NameRef = StringPool.internString(Name);
1587   else if (Tag == dwarf::DW_TAG_namespace)
1588     // FIXME: For dsymutil-classic compatibility. I think uniquing
1589     // within anonymous namespaces is wrong. There is no ODR guarantee
1590     // there.
1591     NameRef = StringPool.internString("(anonymous namespace)");
1592
1593   if (ShortName && ShortName != Name)
1594     ShortNameRef = StringPool.internString(ShortName);
1595   else
1596     ShortNameRef = NameRef;
1597
1598   if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1599       Tag != dwarf::DW_TAG_union_type &&
1600       Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1601     return PointerIntPair<DeclContext *, 1>(nullptr);
1602
1603   std::string File;
1604   unsigned Line = 0;
1605   unsigned ByteSize = 0;
1606
1607   // Gather some discriminating data about the DeclContext we will be
1608   // creating: File, line number and byte size. This shouldn't be
1609   // necessary, because the ODR is just about names, but given that we
1610   // do some approximations with overloaded functions and anonymous
1611   // namespaces, use these additional data points to make the process safer.
1612   ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1613       &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1614   if (Tag != dwarf::DW_TAG_namespace || !Name) {
1615     if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1616             &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1617       if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1618               &U.getOrigUnit())) {
1619         // FIXME: dsymutil-classic compatibility. I'd rather not
1620         // unique anything in anonymous namespaces, but if we do, then
1621         // verify that the file and line correspond.
1622         if (!Name && Tag == dwarf::DW_TAG_namespace)
1623           FileNum = 1;
1624
1625         // FIXME: Passing U.getOrigUnit().getCompilationDir()
1626         // instead of "" would allow more uniquing, but for now, do
1627         // it this way to match dsymutil-classic.
1628         if (LT->getFileNameByIndex(
1629                 FileNum, "",
1630                 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1631                 File)) {
1632           Line = DIE->getAttributeValueAsUnsignedConstant(
1633               &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1634 #ifdef HAVE_REALPATH
1635           // Cache the resolved paths, because calling realpath is expansive.
1636           if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1637             File = ResolvedPath;
1638           } else {
1639             char RealPath[PATH_MAX + 1];
1640             RealPath[PATH_MAX] = 0;
1641             if (::realpath(File.c_str(), RealPath))
1642               File = RealPath;
1643             U.setResolvedPath(FileNum, File);
1644           }
1645 #endif
1646           FileRef = StringPool.internString(File);
1647         }
1648       }
1649     }
1650   }
1651
1652   if (!Line && NameRef.empty())
1653     return PointerIntPair<DeclContext *, 1>(nullptr);
1654
1655   // FIXME: dsymutil-classic compat won't unique the same type
1656   // presented once as a struct and once as a class. Use the Tag in
1657   // the fully qualified name hash to get the same effect.
1658   // We hash NameRef, which is the mangled name, in order to get most
1659   // overloaded functions resolvec correctly.
1660   unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1661
1662   // FIXME: dsymutil-classic compatibility: when we don't have a name,
1663   // use the filename.
1664   if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1665     Hash = hash_combine(Hash, FileRef);
1666
1667   // Now look if this context already exists.
1668   DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1669   auto ContextIter = Contexts.find(&Key);
1670
1671   if (ContextIter == Contexts.end()) {
1672     // The context wasn't found.
1673     bool Inserted;
1674     DeclContext *NewContext =
1675         new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1676                                     Context, DIE, U.getUniqueID());
1677     std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1678     assert(Inserted && "Failed to insert DeclContext");
1679     (void)Inserted;
1680   } else if (Tag != dwarf::DW_TAG_namespace &&
1681              !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1682     // The context was found, but it is ambiguous with another context
1683     // in the same file. Mark it invalid.
1684     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1685   }
1686
1687   assert(ContextIter != Contexts.end());
1688   // FIXME: dsymutil-classic compatibility. Union types aren't
1689   // uniques, but their children might be.
1690   if ((Tag == dwarf::DW_TAG_subprogram &&
1691        Context.getTag() != dwarf::DW_TAG_structure_type &&
1692        Context.getTag() != dwarf::DW_TAG_class_type) ||
1693       (Tag == dwarf::DW_TAG_union_type))
1694     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1695
1696   return PointerIntPair<DeclContext *, 1>(*ContextIter);
1697 }
1698
1699 /// \brief Get the potential name and mangled name for the entity
1700 /// described by \p Die and store them in \Info if they are not
1701 /// already there.
1702 /// \returns is a name was found.
1703 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1704                               DWARFUnit &U, AttributesInfo &Info) {
1705   // FIXME: a bit wastefull as the first getName might return the
1706   // short name.
1707   if (!Info.MangledName &&
1708       (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1709     Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1710
1711   if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1712     Info.NameOffset = StringPool.getStringOffset(Info.Name);
1713
1714   return Info.Name || Info.MangledName;
1715 }
1716
1717 /// \brief Report a warning to the user, optionaly including
1718 /// information about a specific \p DIE related to the warning.
1719 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1720                                 const DWARFDebugInfoEntryMinimal *DIE) const {
1721   StringRef Context = "<debug map>";
1722   if (CurrentDebugObject)
1723     Context = CurrentDebugObject->getObjectFilename();
1724   warn(Warning, Context);
1725
1726   if (!Options.Verbose || !DIE)
1727     return;
1728
1729   errs() << "    in DIE:\n";
1730   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1731             6 /* Indent */);
1732 }
1733
1734 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1735   if (Options.NoOutput)
1736     return true;
1737
1738   Streamer = llvm::make_unique<DwarfStreamer>();
1739   return Streamer->init(TheTriple, OutputFilename);
1740 }
1741
1742 /// \brief Recursive helper to gather the child->parent relationships in the
1743 /// original compile unit.
1744 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1745                              unsigned ParentIdx, CompileUnit &CU,
1746                              DeclContext *CurrentDeclContext,
1747                              NonRelocatableStringpool &StringPool,
1748                              DeclContextTree &Contexts) {
1749   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1750   CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1751
1752   Info.ParentIdx = ParentIdx;
1753   if (CU.hasODR()) {
1754     if (CurrentDeclContext) {
1755       auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1756                                                          DIE, CU, StringPool);
1757       CurrentDeclContext = PtrInvalidPair.getPointer();
1758       Info.Ctxt =
1759           PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1760     } else
1761       Info.Ctxt = CurrentDeclContext = nullptr;
1762   }
1763
1764   if (DIE->hasChildren())
1765     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1766          Child = Child->getSibling())
1767       gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1768                        Contexts);
1769 }
1770
1771 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1772   switch (Tag) {
1773   default:
1774     return false;
1775   case dwarf::DW_TAG_subprogram:
1776   case dwarf::DW_TAG_lexical_block:
1777   case dwarf::DW_TAG_subroutine_type:
1778   case dwarf::DW_TAG_structure_type:
1779   case dwarf::DW_TAG_class_type:
1780   case dwarf::DW_TAG_union_type:
1781     return true;
1782   }
1783   llvm_unreachable("Invalid Tag");
1784 }
1785
1786 static unsigned getRefAddrSize(const DWARFUnit &U) {
1787   if (U.getVersion() == 2)
1788     return U.getAddressByteSize();
1789   return 4;
1790 }
1791
1792 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1793   Units.reserve(Dwarf.getNumCompileUnits());
1794   NextValidReloc = 0;
1795   // Iterate over the debug map entries and put all the ones that are
1796   // functions (because they have a size) into the Ranges map. This
1797   // map is very similar to the FunctionRanges that are stored in each
1798   // unit, with 2 notable differences:
1799   //  - obviously this one is global, while the other ones are per-unit.
1800   //  - this one contains not only the functions described in the DIE
1801   // tree, but also the ones that are only in the debug map.
1802   // The latter information is required to reproduce dsymutil's logic
1803   // while linking line tables. The cases where this information
1804   // matters look like bugs that need to be investigated, but for now
1805   // we need to reproduce dsymutil's behavior.
1806   // FIXME: Once we understood exactly if that information is needed,
1807   // maybe totally remove this (or try to use it to do a real
1808   // -gline-tables-only on Darwin.
1809   for (const auto &Entry : Obj.symbols()) {
1810     const auto &Mapping = Entry.getValue();
1811     if (Mapping.Size)
1812       Ranges[Mapping.ObjectAddress] = std::make_pair(
1813           Mapping.ObjectAddress + Mapping.Size,
1814           int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1815   }
1816 }
1817
1818 void DwarfLinker::endDebugObject() {
1819   Units.clear();
1820   ValidRelocs.clear();
1821   Ranges.clear();
1822
1823   for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1824     (*I)->~DIEBlock();
1825   for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1826     (*I)->~DIELoc();
1827
1828   DIEBlocks.clear();
1829   DIELocs.clear();
1830   DIEAlloc.Reset();
1831 }
1832
1833 /// \brief Iterate over the relocations of the given \p Section and
1834 /// store the ones that correspond to debug map entries into the
1835 /// ValidRelocs array.
1836 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1837                                        const object::MachOObjectFile &Obj,
1838                                        const DebugMapObject &DMO) {
1839   StringRef Contents;
1840   Section.getContents(Contents);
1841   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1842
1843   for (const object::RelocationRef &Reloc : Section.relocations()) {
1844     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1845     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1846     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1847     uint64_t Offset64 = Reloc.getOffset();
1848     if ((RelocSize != 4 && RelocSize != 8)) {
1849       reportWarning(" unsupported relocation in debug_info section.");
1850       continue;
1851     }
1852     uint32_t Offset = Offset64;
1853     // Mach-o uses REL relocations, the addend is at the relocation offset.
1854     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1855
1856     auto Sym = Reloc.getSymbol();
1857     if (Sym != Obj.symbol_end()) {
1858       ErrorOr<StringRef> SymbolName = Sym->getName();
1859       if (!SymbolName) {
1860         reportWarning("error getting relocation symbol name.");
1861         continue;
1862       }
1863       if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1864         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1865     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1866       // Do not store the addend. The addend was the address of the
1867       // symbol in the object file, the address in the binary that is
1868       // stored in the debug map doesn't need to be offseted.
1869       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1870     }
1871   }
1872 }
1873
1874 /// \brief Dispatch the valid relocation finding logic to the
1875 /// appropriate handler depending on the object file format.
1876 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1877                                   const object::ObjectFile &Obj,
1878                                   const DebugMapObject &DMO) {
1879   // Dispatch to the right handler depending on the file type.
1880   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1881     findValidRelocsMachO(Section, *MachOObj, DMO);
1882   else
1883     reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1884
1885   if (ValidRelocs.empty())
1886     return false;
1887
1888   // Sort the relocations by offset. We will walk the DIEs linearly in
1889   // the file, this allows us to just keep an index in the relocation
1890   // array that we advance during our walk, rather than resorting to
1891   // some associative container. See DwarfLinker::NextValidReloc.
1892   std::sort(ValidRelocs.begin(), ValidRelocs.end());
1893   return true;
1894 }
1895
1896 /// \brief Look for relocations in the debug_info section that match
1897 /// entries in the debug map. These relocations will drive the Dwarf
1898 /// link by indicating which DIEs refer to symbols present in the
1899 /// linked binary.
1900 /// \returns wether there are any valid relocations in the debug info.
1901 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1902                                              const DebugMapObject &DMO) {
1903   // Find the debug_info section.
1904   for (const object::SectionRef &Section : Obj.sections()) {
1905     StringRef SectionName;
1906     Section.getName(SectionName);
1907     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1908     if (SectionName != "debug_info")
1909       continue;
1910     return findValidRelocs(Section, Obj, DMO);
1911   }
1912   return false;
1913 }
1914
1915 /// \brief Checks that there is a relocation against an actual debug
1916 /// map entry between \p StartOffset and \p NextOffset.
1917 ///
1918 /// This function must be called with offsets in strictly ascending
1919 /// order because it never looks back at relocations it already 'went past'.
1920 /// \returns true and sets Info.InDebugMap if it is the case.
1921 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1922                                      CompileUnit::DIEInfo &Info) {
1923   assert(NextValidReloc == 0 ||
1924          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1925   if (NextValidReloc >= ValidRelocs.size())
1926     return false;
1927
1928   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1929
1930   // We might need to skip some relocs that we didn't consider. For
1931   // example the high_pc of a discarded DIE might contain a reloc that
1932   // is in the list because it actually corresponds to the start of a
1933   // function that is in the debug map.
1934   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1935     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1936
1937   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1938     return false;
1939
1940   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1941   const auto &Mapping = ValidReloc.Mapping->getValue();
1942   if (Options.Verbose)
1943     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1944            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1945                             uint64_t(Mapping.ObjectAddress),
1946                             uint64_t(Mapping.BinaryAddress));
1947
1948   Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1949                     Mapping.ObjectAddress;
1950   Info.InDebugMap = true;
1951   return true;
1952 }
1953
1954 /// \brief Get the starting and ending (exclusive) offset for the
1955 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1956 /// supposed to point to the position of the first attribute described
1957 /// by \p Abbrev.
1958 /// \return [StartOffset, EndOffset) as a pair.
1959 static std::pair<uint32_t, uint32_t>
1960 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1961                     unsigned Offset, const DWARFUnit &Unit) {
1962   DataExtractor Data = Unit.getDebugInfoExtractor();
1963
1964   for (unsigned i = 0; i < Idx; ++i)
1965     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1966
1967   uint32_t End = Offset;
1968   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1969
1970   return std::make_pair(Offset, End);
1971 }
1972
1973 /// \brief Check if a variable describing DIE should be kept.
1974 /// \returns updated TraversalFlags.
1975 unsigned DwarfLinker::shouldKeepVariableDIE(
1976     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1977     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1978   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1979
1980   // Global variables with constant value can always be kept.
1981   if (!(Flags & TF_InFunctionScope) &&
1982       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1983     MyInfo.InDebugMap = true;
1984     return Flags | TF_Keep;
1985   }
1986
1987   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1988   if (LocationIdx == -1U)
1989     return Flags;
1990
1991   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1992   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1993   uint32_t LocationOffset, LocationEndOffset;
1994   std::tie(LocationOffset, LocationEndOffset) =
1995       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1996
1997   // See if there is a relocation to a valid debug map entry inside
1998   // this variable's location. The order is important here. We want to
1999   // always check in the variable has a valid relocation, so that the
2000   // DIEInfo is filled. However, we don't want a static variable in a
2001   // function to force us to keep the enclosing function.
2002   if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
2003       (Flags & TF_InFunctionScope))
2004     return Flags;
2005
2006   if (Options.Verbose)
2007     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2008
2009   return Flags | TF_Keep;
2010 }
2011
2012 /// \brief Check if a function describing DIE should be kept.
2013 /// \returns updated TraversalFlags.
2014 unsigned DwarfLinker::shouldKeepSubprogramDIE(
2015     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2016     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2017   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2018
2019   Flags |= TF_InFunctionScope;
2020
2021   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2022   if (LowPcIdx == -1U)
2023     return Flags;
2024
2025   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2026   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2027   uint32_t LowPcOffset, LowPcEndOffset;
2028   std::tie(LowPcOffset, LowPcEndOffset) =
2029       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2030
2031   uint64_t LowPc =
2032       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2033   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2034   if (LowPc == -1ULL ||
2035       !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2036     return Flags;
2037
2038   if (Options.Verbose)
2039     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2040
2041   Flags |= TF_Keep;
2042
2043   DWARFFormValue HighPcValue;
2044   if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2045     reportWarning("Function without high_pc. Range will be discarded.\n",
2046                   &OrigUnit, &DIE);
2047     return Flags;
2048   }
2049
2050   uint64_t HighPc;
2051   if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2052     HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2053   } else {
2054     assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2055     HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2056   }
2057
2058   // Replace the debug map range with a more accurate one.
2059   Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
2060   Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2061   return Flags;
2062 }
2063
2064 /// \brief Check if a DIE should be kept.
2065 /// \returns updated TraversalFlags.
2066 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
2067                                     CompileUnit &Unit,
2068                                     CompileUnit::DIEInfo &MyInfo,
2069                                     unsigned Flags) {
2070   switch (DIE.getTag()) {
2071   case dwarf::DW_TAG_constant:
2072   case dwarf::DW_TAG_variable:
2073     return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
2074   case dwarf::DW_TAG_subprogram:
2075     return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
2076   case dwarf::DW_TAG_module:
2077   case dwarf::DW_TAG_imported_module:
2078   case dwarf::DW_TAG_imported_declaration:
2079   case dwarf::DW_TAG_imported_unit:
2080     // We always want to keep these.
2081     return Flags | TF_Keep;
2082   }
2083
2084   return Flags;
2085 }
2086
2087 /// \brief Mark the passed DIE as well as all the ones it depends on
2088 /// as kept.
2089 ///
2090 /// This function is called by lookForDIEsToKeep on DIEs that are
2091 /// newly discovered to be needed in the link. It recursively calls
2092 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2093 /// TraversalFlags to inform it that it's not doing the primary DIE
2094 /// tree walk.
2095 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
2096                                           CompileUnit::DIEInfo &MyInfo,
2097                                           const DebugMapObject &DMO,
2098                                           CompileUnit &CU, bool UseODR) {
2099   const DWARFUnit &Unit = CU.getOrigUnit();
2100   MyInfo.Keep = true;
2101
2102   // First mark all the parent chain as kept.
2103   unsigned AncestorIdx = MyInfo.ParentIdx;
2104   while (!CU.getInfo(AncestorIdx).Keep) {
2105     unsigned ODRFlag = UseODR ? TF_ODR : 0;
2106     lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2107                       TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2108     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2109   }
2110
2111   // Then we need to mark all the DIEs referenced by this DIE's
2112   // attributes as kept.
2113   DataExtractor Data = Unit.getDebugInfoExtractor();
2114   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2115   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2116
2117   // Mark all DIEs referenced through atttributes as kept.
2118   for (const auto &AttrSpec : Abbrev->attributes()) {
2119     DWARFFormValue Val(AttrSpec.Form);
2120
2121     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2122       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2123       continue;
2124     }
2125
2126     Val.extractValue(Data, &Offset, &Unit);
2127     CompileUnit *ReferencedCU;
2128     if (const auto *RefDIE =
2129             resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2130       uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2131       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2132       // If the referenced DIE has a DeclContext that has already been
2133       // emitted, then do not keep the one in this CU. We'll link to
2134       // the canonical DIE in cloneDieReferenceAttribute.
2135       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2136       // be necessary and could be advantageously replaced by
2137       // ReferencedCU->hasODR() && CU.hasODR().
2138       // FIXME: compatibility with dsymutil-classic. There is no
2139       // reason not to unique ref_addr references.
2140       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2141           Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2142           Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2143         continue;
2144
2145       unsigned ODRFlag = UseODR ? TF_ODR : 0;
2146       lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
2147                         TF_Keep | TF_DependencyWalk | ODRFlag);
2148     }
2149   }
2150 }
2151
2152 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2153 /// keep. Store that information in \p CU's DIEInfo.
2154 ///
2155 /// This function is the entry point of the DIE selection
2156 /// algorithm. It is expected to walk the DIE tree in file order and
2157 /// (though the mediation of its helper) call hasValidRelocation() on
2158 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2159 /// comment).
2160 /// While walking the dependencies of root DIEs, this function is
2161 /// also called, but during these dependency walks the file order is
2162 /// not respected. The TF_DependencyWalk flag tells us which kind of
2163 /// traversal we are currently doing.
2164 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2165                                     const DebugMapObject &DMO, CompileUnit &CU,
2166                                     unsigned Flags) {
2167   unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2168   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2169   bool AlreadyKept = MyInfo.Keep;
2170
2171   // If the Keep flag is set, we are marking a required DIE's
2172   // dependencies. If our target is already marked as kept, we're all
2173   // set.
2174   if ((Flags & TF_DependencyWalk) && AlreadyKept)
2175     return;
2176
2177   // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2178   // because it would screw up the relocation finding logic.
2179   if (!(Flags & TF_DependencyWalk))
2180     Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2181
2182   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2183   if (!AlreadyKept && (Flags & TF_Keep)) {
2184     bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2185     keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2186   }
2187   // The TF_ParentWalk flag tells us that we are currently walking up
2188   // the parent chain of a required DIE, and we don't want to mark all
2189   // the children of the parents as kept (consider for example a
2190   // DW_TAG_namespace node in the parent chain). There are however a
2191   // set of DIE types for which we want to ignore that directive and still
2192   // walk their children.
2193   if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2194     Flags &= ~TF_ParentWalk;
2195
2196   if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2197     return;
2198
2199   for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2200        Child = Child->getSibling())
2201     lookForDIEsToKeep(*Child, DMO, CU, Flags);
2202 }
2203
2204 /// \brief Assign an abbreviation numer to \p Abbrev.
2205 ///
2206 /// Our DIEs get freed after every DebugMapObject has been processed,
2207 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2208 /// the instances hold by the DIEs. When we encounter an abbreviation
2209 /// that we don't know, we create a permanent copy of it.
2210 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2211   // Check the set for priors.
2212   FoldingSetNodeID ID;
2213   Abbrev.Profile(ID);
2214   void *InsertToken;
2215   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2216
2217   // If it's newly added.
2218   if (InSet) {
2219     // Assign existing abbreviation number.
2220     Abbrev.setNumber(InSet->getNumber());
2221   } else {
2222     // Add to abbreviation list.
2223     Abbreviations.push_back(
2224         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2225     for (const auto &Attr : Abbrev.getData())
2226       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2227     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2228     // Assign the unique abbreviation number.
2229     Abbrev.setNumber(Abbreviations.size());
2230     Abbreviations.back()->setNumber(Abbreviations.size());
2231   }
2232 }
2233
2234 /// \brief Clone a string attribute described by \p AttrSpec and add
2235 /// it to \p Die.
2236 /// \returns the size of the new attribute.
2237 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2238                                            const DWARFFormValue &Val,
2239                                            const DWARFUnit &U) {
2240   // Switch everything to out of line strings.
2241   const char *String = *Val.getAsCString(&U);
2242   unsigned Offset = StringPool.getStringOffset(String);
2243   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2244                DIEInteger(Offset));
2245   return 4;
2246 }
2247
2248 /// \brief Clone an attribute referencing another DIE and add
2249 /// it to \p Die.
2250 /// \returns the size of the new attribute.
2251 unsigned DwarfLinker::cloneDieReferenceAttribute(
2252     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2253     AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2254     CompileUnit &Unit) {
2255   const DWARFUnit &U = Unit.getOrigUnit();
2256   uint32_t Ref = *Val.getAsReference(&U);
2257   DIE *NewRefDie = nullptr;
2258   CompileUnit *RefUnit = nullptr;
2259   DeclContext *Ctxt = nullptr;
2260
2261   const DWARFDebugInfoEntryMinimal *RefDie =
2262       resolveDIEReference(Val, U, InputDIE, RefUnit);
2263
2264   // If the referenced DIE is not found,  drop the attribute.
2265   if (!RefDie)
2266     return 0;
2267
2268   unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2269   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2270
2271   // If we already have emitted an equivalent DeclContext, just point
2272   // at it.
2273   if (isODRAttribute(AttrSpec.Attr)) {
2274     Ctxt = RefInfo.Ctxt;
2275     if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2276       DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2277       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2278                    dwarf::DW_FORM_ref_addr, Attr);
2279       return getRefAddrSize(U);
2280     }
2281   }
2282
2283   if (!RefInfo.Clone) {
2284     assert(Ref > InputDIE.getOffset());
2285     // We haven't cloned this DIE yet. Just create an empty one and
2286     // store it. It'll get really cloned when we process it.
2287     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
2288   }
2289   NewRefDie = RefInfo.Clone;
2290
2291   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2292       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2293     // We cannot currently rely on a DIEEntry to emit ref_addr
2294     // references, because the implementation calls back to DwarfDebug
2295     // to find the unit offset. (We don't have a DwarfDebug)
2296     // FIXME: we should be able to design DIEEntry reliance on
2297     // DwarfDebug away.
2298     uint64_t Attr;
2299     if (Ref < InputDIE.getOffset()) {
2300       // We must have already cloned that DIE.
2301       uint32_t NewRefOffset =
2302           RefUnit->getStartOffset() + NewRefDie->getOffset();
2303       Attr = NewRefOffset;
2304       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2305                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2306     } else {
2307       // A forward reference. Note and fixup later.
2308       Attr = 0xBADDEF;
2309       Unit.noteForwardReference(
2310           NewRefDie, RefUnit, Ctxt,
2311           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2312                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2313     }
2314     return getRefAddrSize(U);
2315   }
2316
2317   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2318                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2319   return AttrSize;
2320 }
2321
2322 /// \brief Clone an attribute of block form (locations, constants) and add
2323 /// it to \p Die.
2324 /// \returns the size of the new attribute.
2325 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2326                                           const DWARFFormValue &Val,
2327                                           unsigned AttrSize) {
2328   DIEValueList *Attr;
2329   DIEValue Value;
2330   DIELoc *Loc = nullptr;
2331   DIEBlock *Block = nullptr;
2332   // Just copy the block data over.
2333   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2334     Loc = new (DIEAlloc) DIELoc;
2335     DIELocs.push_back(Loc);
2336   } else {
2337     Block = new (DIEAlloc) DIEBlock;
2338     DIEBlocks.push_back(Block);
2339   }
2340   Attr = Loc ? static_cast<DIEValueList *>(Loc)
2341              : static_cast<DIEValueList *>(Block);
2342
2343   if (Loc)
2344     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2345                      dwarf::Form(AttrSpec.Form), Loc);
2346   else
2347     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2348                      dwarf::Form(AttrSpec.Form), Block);
2349   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2350   for (auto Byte : Bytes)
2351     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2352                    dwarf::DW_FORM_data1, DIEInteger(Byte));
2353   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2354   // the DIE class, this if could be replaced by
2355   // Attr->setSize(Bytes.size()).
2356   if (Streamer) {
2357     if (Loc)
2358       Loc->ComputeSize(&Streamer->getAsmPrinter());
2359     else
2360       Block->ComputeSize(&Streamer->getAsmPrinter());
2361   }
2362   Die.addValue(DIEAlloc, Value);
2363   return AttrSize;
2364 }
2365
2366 /// \brief Clone an address attribute and add it to \p Die.
2367 /// \returns the size of the new attribute.
2368 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2369                                             const DWARFFormValue &Val,
2370                                             const CompileUnit &Unit,
2371                                             AttributesInfo &Info) {
2372   uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
2373   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2374     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2375         Die.getTag() == dwarf::DW_TAG_lexical_block)
2376       Addr += Info.PCOffset;
2377     else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2378       Addr = Unit.getLowPc();
2379       if (Addr == UINT64_MAX)
2380         return 0;
2381     }
2382     Info.HasLowPc = true;
2383   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2384     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2385       if (uint64_t HighPc = Unit.getHighPc())
2386         Addr = HighPc;
2387       else
2388         return 0;
2389     } else
2390       // If we have a high_pc recorded for the input DIE, use
2391       // it. Otherwise (when no relocations where applied) just use the
2392       // one we just decoded.
2393       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2394   }
2395
2396   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2397                static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2398   return Unit.getOrigUnit().getAddressByteSize();
2399 }
2400
2401 /// \brief Clone a scalar attribute  and add it to \p Die.
2402 /// \returns the size of the new attribute.
2403 unsigned DwarfLinker::cloneScalarAttribute(
2404     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2405     AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2406     AttributesInfo &Info) {
2407   uint64_t Value;
2408   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2409       Die.getTag() == dwarf::DW_TAG_compile_unit) {
2410     if (Unit.getLowPc() == -1ULL)
2411       return 0;
2412     // Dwarf >= 4 high_pc is an size, not an address.
2413     Value = Unit.getHighPc() - Unit.getLowPc();
2414   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2415     Value = *Val.getAsSectionOffset();
2416   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2417     Value = *Val.getAsSignedConstant();
2418   else if (auto OptionalValue = Val.getAsUnsignedConstant())
2419     Value = *OptionalValue;
2420   else {
2421     reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2422                   &Unit.getOrigUnit(), &InputDIE);
2423     return 0;
2424   }
2425   PatchLocation Patch =
2426       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2427                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2428   if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2429     Unit.noteRangeAttribute(Die, Patch);
2430   // A more generic way to check for location attributes would be
2431   // nice, but it's very unlikely that any other attribute needs a
2432   // location list.
2433   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2434            AttrSpec.Attr == dwarf::DW_AT_frame_base)
2435     Unit.noteLocationAttribute(Patch, Info.PCOffset);
2436   else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2437     Info.IsDeclaration = true;
2438
2439   return AttrSize;
2440 }
2441
2442 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2443 /// value \p Val, and add it to \p Die.
2444 /// \returns the size of the cloned attribute.
2445 unsigned DwarfLinker::cloneAttribute(DIE &Die,
2446                                      const DWARFDebugInfoEntryMinimal &InputDIE,
2447                                      CompileUnit &Unit,
2448                                      const DWARFFormValue &Val,
2449                                      const AttributeSpec AttrSpec,
2450                                      unsigned AttrSize, AttributesInfo &Info) {
2451   const DWARFUnit &U = Unit.getOrigUnit();
2452
2453   switch (AttrSpec.Form) {
2454   case dwarf::DW_FORM_strp:
2455   case dwarf::DW_FORM_string:
2456     return cloneStringAttribute(Die, AttrSpec, Val, U);
2457   case dwarf::DW_FORM_ref_addr:
2458   case dwarf::DW_FORM_ref1:
2459   case dwarf::DW_FORM_ref2:
2460   case dwarf::DW_FORM_ref4:
2461   case dwarf::DW_FORM_ref8:
2462     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2463                                       Unit);
2464   case dwarf::DW_FORM_block:
2465   case dwarf::DW_FORM_block1:
2466   case dwarf::DW_FORM_block2:
2467   case dwarf::DW_FORM_block4:
2468   case dwarf::DW_FORM_exprloc:
2469     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2470   case dwarf::DW_FORM_addr:
2471     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2472   case dwarf::DW_FORM_data1:
2473   case dwarf::DW_FORM_data2:
2474   case dwarf::DW_FORM_data4:
2475   case dwarf::DW_FORM_data8:
2476   case dwarf::DW_FORM_udata:
2477   case dwarf::DW_FORM_sdata:
2478   case dwarf::DW_FORM_sec_offset:
2479   case dwarf::DW_FORM_flag:
2480   case dwarf::DW_FORM_flag_present:
2481     return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2482                                 Info);
2483   default:
2484     reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2485                   &InputDIE);
2486   }
2487
2488   return 0;
2489 }
2490
2491 /// \brief Apply the valid relocations found by findValidRelocs() to
2492 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2493 /// in the debug_info section.
2494 ///
2495 /// Like for findValidRelocs(), this function must be called with
2496 /// monotonic \p BaseOffset values.
2497 ///
2498 /// \returns wether any reloc has been applied.
2499 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2500                                    uint32_t BaseOffset, bool isLittleEndian) {
2501   assert((NextValidReloc == 0 ||
2502           BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2503          "BaseOffset should only be increasing.");
2504   if (NextValidReloc >= ValidRelocs.size())
2505     return false;
2506
2507   // Skip relocs that haven't been applied.
2508   while (NextValidReloc < ValidRelocs.size() &&
2509          ValidRelocs[NextValidReloc].Offset < BaseOffset)
2510     ++NextValidReloc;
2511
2512   bool Applied = false;
2513   uint64_t EndOffset = BaseOffset + Data.size();
2514   while (NextValidReloc < ValidRelocs.size() &&
2515          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2516          ValidRelocs[NextValidReloc].Offset < EndOffset) {
2517     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2518     assert(ValidReloc.Offset - BaseOffset < Data.size());
2519     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2520     char Buf[8];
2521     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2522     Value += ValidReloc.Addend;
2523     for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2524       unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2525       Buf[i] = uint8_t(Value >> (Index * 8));
2526     }
2527     assert(ValidReloc.Size <= sizeof(Buf));
2528     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2529     Applied = true;
2530   }
2531
2532   return Applied;
2533 }
2534
2535 static bool isTypeTag(uint16_t Tag) {
2536   switch (Tag) {
2537   case dwarf::DW_TAG_array_type:
2538   case dwarf::DW_TAG_class_type:
2539   case dwarf::DW_TAG_enumeration_type:
2540   case dwarf::DW_TAG_pointer_type:
2541   case dwarf::DW_TAG_reference_type:
2542   case dwarf::DW_TAG_string_type:
2543   case dwarf::DW_TAG_structure_type:
2544   case dwarf::DW_TAG_subroutine_type:
2545   case dwarf::DW_TAG_typedef:
2546   case dwarf::DW_TAG_union_type:
2547   case dwarf::DW_TAG_ptr_to_member_type:
2548   case dwarf::DW_TAG_set_type:
2549   case dwarf::DW_TAG_subrange_type:
2550   case dwarf::DW_TAG_base_type:
2551   case dwarf::DW_TAG_const_type:
2552   case dwarf::DW_TAG_constant:
2553   case dwarf::DW_TAG_file_type:
2554   case dwarf::DW_TAG_namelist:
2555   case dwarf::DW_TAG_packed_type:
2556   case dwarf::DW_TAG_volatile_type:
2557   case dwarf::DW_TAG_restrict_type:
2558   case dwarf::DW_TAG_interface_type:
2559   case dwarf::DW_TAG_unspecified_type:
2560   case dwarf::DW_TAG_shared_type:
2561     return true;
2562   default:
2563     break;
2564   }
2565   return false;
2566 }
2567
2568 /// \brief Recursively clone \p InputDIE's subtrees that have been
2569 /// selected to appear in the linked output.
2570 ///
2571 /// \param OutOffset is the Offset where the newly created DIE will
2572 /// lie in the linked compile unit.
2573 ///
2574 /// \returns the cloned DIE object or null if nothing was selected.
2575 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2576                            CompileUnit &Unit, int64_t PCOffset,
2577                            uint32_t OutOffset) {
2578   DWARFUnit &U = Unit.getOrigUnit();
2579   unsigned Idx = U.getDIEIndex(&InputDIE);
2580   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2581
2582   // Should the DIE appear in the output?
2583   if (!Unit.getInfo(Idx).Keep)
2584     return nullptr;
2585
2586   uint32_t Offset = InputDIE.getOffset();
2587   // The DIE might have been already created by a forward reference
2588   // (see cloneDieReferenceAttribute()).
2589   DIE *Die = Info.Clone;
2590   if (!Die)
2591     Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2592   assert(Die->getTag() == InputDIE.getTag());
2593   Die->setOffset(OutOffset);
2594   if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2595       Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2596       !Info.Ctxt->getCanonicalDIEOffset()) {
2597     // We are about to emit a DIE that is the root of its own valid
2598     // DeclContext tree. Make the current offset the canonical offset
2599     // for this context.
2600     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2601   }
2602
2603   // Extract and clone every attribute.
2604   DataExtractor Data = U.getDebugInfoExtractor();
2605   uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2606   AttributesInfo AttrInfo;
2607
2608   // We could copy the data only if we need to aply a relocation to
2609   // it. After testing, it seems there is no performance downside to
2610   // doing the copy unconditionally, and it makes the code simpler.
2611   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2612   Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2613   // Modify the copy with relocated addresses.
2614   if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2615     // If we applied relocations, we store the value of high_pc that was
2616     // potentially stored in the input DIE. If high_pc is an address
2617     // (Dwarf version == 2), then it might have been relocated to a
2618     // totally unrelated value (because the end address in the object
2619     // file might be start address of another function which got moved
2620     // independantly by the linker). The computation of the actual
2621     // high_pc value is done in cloneAddressAttribute().
2622     AttrInfo.OrigHighPc =
2623         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2624   }
2625
2626   // Reset the Offset to 0 as we will be working on the local copy of
2627   // the data.
2628   Offset = 0;
2629
2630   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2631   Offset += getULEB128Size(Abbrev->getCode());
2632
2633   // We are entering a subprogram. Get and propagate the PCOffset.
2634   if (Die->getTag() == dwarf::DW_TAG_subprogram)
2635     PCOffset = Info.AddrAdjust;
2636   AttrInfo.PCOffset = PCOffset;
2637
2638   for (const auto &AttrSpec : Abbrev->attributes()) {
2639     DWARFFormValue Val(AttrSpec.Form);
2640     uint32_t AttrSize = Offset;
2641     Val.extractValue(Data, &Offset, &U);
2642     AttrSize = Offset - AttrSize;
2643
2644     OutOffset +=
2645         cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2646   }
2647
2648   // Look for accelerator entries.
2649   uint16_t Tag = InputDIE.getTag();
2650   // FIXME: This is slightly wrong. An inline_subroutine without a
2651   // low_pc, but with AT_ranges might be interesting to get into the
2652   // accelerator tables too. For now stick with dsymutil's behavior.
2653   if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2654       Tag != dwarf::DW_TAG_compile_unit &&
2655       getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2656     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2657       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2658                               AttrInfo.MangledNameOffset,
2659                               Tag == dwarf::DW_TAG_inlined_subroutine);
2660     if (AttrInfo.Name)
2661       Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2662                               Tag == dwarf::DW_TAG_inlined_subroutine);
2663   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2664              getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2665     Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2666   }
2667
2668   DIEAbbrev NewAbbrev = Die->generateAbbrev();
2669   // If a scope DIE is kept, we must have kept at least one child. If
2670   // it's not the case, we'll just be emitting one wasteful end of
2671   // children marker, but things won't break.
2672   if (InputDIE.hasChildren())
2673     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2674   // Assign a permanent abbrev number
2675   AssignAbbrev(NewAbbrev);
2676   Die->setAbbrevNumber(NewAbbrev.getNumber());
2677
2678   // Add the size of the abbreviation number to the output offset.
2679   OutOffset += getULEB128Size(Die->getAbbrevNumber());
2680
2681   if (!Abbrev->hasChildren()) {
2682     // Update our size.
2683     Die->setSize(OutOffset - Die->getOffset());
2684     return Die;
2685   }
2686
2687   // Recursively clone children.
2688   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2689        Child = Child->getSibling()) {
2690     if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2691       Die->addChild(Clone);
2692       OutOffset = Clone->getOffset() + Clone->getSize();
2693     }
2694   }
2695
2696   // Account for the end of children marker.
2697   OutOffset += sizeof(int8_t);
2698   // Update our size.
2699   Die->setSize(OutOffset - Die->getOffset());
2700   return Die;
2701 }
2702
2703 /// \brief Patch the input object file relevant debug_ranges entries
2704 /// and emit them in the output file. Update the relevant attributes
2705 /// to point at the new entries.
2706 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2707                                      DWARFContext &OrigDwarf) const {
2708   DWARFDebugRangeList RangeList;
2709   const auto &FunctionRanges = Unit.getFunctionRanges();
2710   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2711   DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2712                                OrigDwarf.isLittleEndian(), AddressSize);
2713   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2714   DWARFUnit &OrigUnit = Unit.getOrigUnit();
2715   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2716   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2717       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2718   // Ranges addresses are based on the unit's low_pc. Compute the
2719   // offset we need to apply to adapt to the the new unit's low_pc.
2720   int64_t UnitPcOffset = 0;
2721   if (OrigLowPc != -1ULL)
2722     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2723
2724   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2725     uint32_t Offset = RangeAttribute.get();
2726     RangeAttribute.set(Streamer->getRangesSectionSize());
2727     RangeList.extract(RangeExtractor, &Offset);
2728     const auto &Entries = RangeList.getEntries();
2729     const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2730
2731     if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2732         First.StartAddress >= CurrRange.stop()) {
2733       CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2734       if (CurrRange == InvalidRange ||
2735           CurrRange.start() > First.StartAddress + OrigLowPc) {
2736         reportWarning("no mapping for range.");
2737         continue;
2738       }
2739     }
2740
2741     Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2742                                 AddressSize);
2743   }
2744 }
2745
2746 /// \brief Generate the debug_aranges entries for \p Unit and if the
2747 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2748 /// contribution for this attribute.
2749 /// FIXME: this could actually be done right in patchRangesForUnit,
2750 /// but for the sake of initial bit-for-bit compatibility with legacy
2751 /// dsymutil, we have to do it in a delayed pass.
2752 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2753   auto Attr = Unit.getUnitRangesAttribute();
2754   if (Attr)
2755     Attr->set(Streamer->getRangesSectionSize());
2756   Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2757 }
2758
2759 /// \brief Insert the new line info sequence \p Seq into the current
2760 /// set of already linked line info \p Rows.
2761 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2762                                std::vector<DWARFDebugLine::Row> &Rows) {
2763   if (Seq.empty())
2764     return;
2765
2766   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2767     Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2768     Seq.clear();
2769     return;
2770   }
2771
2772   auto InsertPoint = std::lower_bound(
2773       Rows.begin(), Rows.end(), Seq.front(),
2774       [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2775         return LHS.Address < RHS.Address;
2776       });
2777
2778   // FIXME: this only removes the unneeded end_sequence if the
2779   // sequences have been inserted in order. using a global sort like
2780   // described in patchLineTableForUnit() and delaying the end_sequene
2781   // elimination to emitLineTableForUnit() we can get rid of all of them.
2782   if (InsertPoint != Rows.end() &&
2783       InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2784     *InsertPoint = Seq.front();
2785     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2786   } else {
2787     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2788   }
2789
2790   Seq.clear();
2791 }
2792
2793 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2794   for (auto &V : Die.values())
2795     if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2796       V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2797       return;
2798     }
2799
2800   llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2801 }
2802
2803 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2804 /// recreate a relocated version of these for the address ranges that
2805 /// are present in the binary.
2806 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2807                                         DWARFContext &OrigDwarf) {
2808   const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2809   uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2810       &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2811   if (StmtList == -1ULL)
2812     return;
2813
2814   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2815   if (auto *OutputDIE = Unit.getOutputUnitDIE())
2816     patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2817
2818   // Parse the original line info for the unit.
2819   DWARFDebugLine::LineTable LineTable;
2820   uint32_t StmtOffset = StmtList;
2821   StringRef LineData = OrigDwarf.getLineSection().Data;
2822   DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2823                               Unit.getOrigUnit().getAddressByteSize());
2824   LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2825                   &StmtOffset);
2826
2827   // This vector is the output line table.
2828   std::vector<DWARFDebugLine::Row> NewRows;
2829   NewRows.reserve(LineTable.Rows.size());
2830
2831   // Current sequence of rows being extracted, before being inserted
2832   // in NewRows.
2833   std::vector<DWARFDebugLine::Row> Seq;
2834   const auto &FunctionRanges = Unit.getFunctionRanges();
2835   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2836
2837   // FIXME: This logic is meant to generate exactly the same output as
2838   // Darwin's classic dsynutil. There is a nicer way to implement this
2839   // by simply putting all the relocated line info in NewRows and simply
2840   // sorting NewRows before passing it to emitLineTableForUnit. This
2841   // should be correct as sequences for a function should stay
2842   // together in the sorted output. There are a few corner cases that
2843   // look suspicious though, and that required to implement the logic
2844   // this way. Revisit that once initial validation is finished.
2845
2846   // Iterate over the object file line info and extract the sequences
2847   // that correspond to linked functions.
2848   for (auto &Row : LineTable.Rows) {
2849     // Check wether we stepped out of the range. The range is
2850     // half-open, but consider accept the end address of the range if
2851     // it is marked as end_sequence in the input (because in that
2852     // case, the relocation offset is accurate and that entry won't
2853     // serve as the start of another function).
2854     if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2855         Row.Address > CurrRange.stop() ||
2856         (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2857       // We just stepped out of a known range. Insert a end_sequence
2858       // corresponding to the end of the range.
2859       uint64_t StopAddress = CurrRange != InvalidRange
2860                                  ? CurrRange.stop() + CurrRange.value()
2861                                  : -1ULL;
2862       CurrRange = FunctionRanges.find(Row.Address);
2863       bool CurrRangeValid =
2864           CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2865       if (!CurrRangeValid) {
2866         CurrRange = InvalidRange;
2867         if (StopAddress != -1ULL) {
2868           // Try harder by looking in the DebugMapObject function
2869           // ranges map. There are corner cases where this finds a
2870           // valid entry. It's unclear if this is right or wrong, but
2871           // for now do as dsymutil.
2872           // FIXME: Understand exactly what cases this addresses and
2873           // potentially remove it along with the Ranges map.
2874           auto Range = Ranges.lower_bound(Row.Address);
2875           if (Range != Ranges.begin() && Range != Ranges.end())
2876             --Range;
2877
2878           if (Range != Ranges.end() && Range->first <= Row.Address &&
2879               Range->second.first >= Row.Address) {
2880             StopAddress = Row.Address + Range->second.second;
2881           }
2882         }
2883       }
2884       if (StopAddress != -1ULL && !Seq.empty()) {
2885         // Insert end sequence row with the computed end address, but
2886         // the same line as the previous one.
2887         Seq.emplace_back(Seq.back());
2888         Seq.back().Address = StopAddress;
2889         Seq.back().EndSequence = 1;
2890         Seq.back().PrologueEnd = 0;
2891         Seq.back().BasicBlock = 0;
2892         Seq.back().EpilogueBegin = 0;
2893         insertLineSequence(Seq, NewRows);
2894       }
2895
2896       if (!CurrRangeValid)
2897         continue;
2898     }
2899
2900     // Ignore empty sequences.
2901     if (Row.EndSequence && Seq.empty())
2902       continue;
2903
2904     // Relocate row address and add it to the current sequence.
2905     Row.Address += CurrRange.value();
2906     Seq.emplace_back(Row);
2907
2908     if (Row.EndSequence)
2909       insertLineSequence(Seq, NewRows);
2910   }
2911
2912   // Finished extracting, now emit the line tables.
2913   uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2914   // FIXME: LLVM hardcodes it's prologue values. We just copy the
2915   // prologue over and that works because we act as both producer and
2916   // consumer. It would be nicer to have a real configurable line
2917   // table emitter.
2918   if (LineTable.Prologue.Version != 2 ||
2919       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2920       LineTable.Prologue.OpcodeBase > 13)
2921     reportWarning("line table paramters mismatch. Cannot emit.");
2922   else {
2923     MCDwarfLineTableParams Params;
2924     Params.DWARF2LineOpcodeBase = LineTable.Prologue.OpcodeBase;
2925     Params.DWARF2LineBase = LineTable.Prologue.LineBase;
2926     Params.DWARF2LineRange = LineTable.Prologue.LineRange;
2927     Streamer->emitLineTableForUnit(Params,
2928                                    LineData.slice(StmtList + 4, PrologueEnd),
2929                                    LineTable.Prologue.MinInstLength, NewRows,
2930                                    Unit.getOrigUnit().getAddressByteSize());
2931   }
2932 }
2933
2934 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2935   Streamer->emitPubNamesForUnit(Unit);
2936   Streamer->emitPubTypesForUnit(Unit);
2937 }
2938
2939 /// \brief Read the frame info stored in the object, and emit the
2940 /// patched frame descriptions for the linked binary.
2941 ///
2942 /// This is actually pretty easy as the data of the CIEs and FDEs can
2943 /// be considered as black boxes and moved as is. The only thing to do
2944 /// is to patch the addresses in the headers.
2945 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2946                                           DWARFContext &OrigDwarf,
2947                                           unsigned AddrSize) {
2948   StringRef FrameData = OrigDwarf.getDebugFrameSection();
2949   if (FrameData.empty())
2950     return;
2951
2952   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2953   uint32_t InputOffset = 0;
2954
2955   // Store the data of the CIEs defined in this object, keyed by their
2956   // offsets.
2957   DenseMap<uint32_t, StringRef> LocalCIES;
2958
2959   while (Data.isValidOffset(InputOffset)) {
2960     uint32_t EntryOffset = InputOffset;
2961     uint32_t InitialLength = Data.getU32(&InputOffset);
2962     if (InitialLength == 0xFFFFFFFF)
2963       return reportWarning("Dwarf64 bits no supported");
2964
2965     uint32_t CIEId = Data.getU32(&InputOffset);
2966     if (CIEId == 0xFFFFFFFF) {
2967       // This is a CIE, store it.
2968       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2969       LocalCIES[EntryOffset] = CIEData;
2970       // The -4 is to account for the CIEId we just read.
2971       InputOffset += InitialLength - 4;
2972       continue;
2973     }
2974
2975     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2976
2977     // Some compilers seem to emit frame info that doesn't start at
2978     // the function entry point, thus we can't just lookup the address
2979     // in the debug map. Use the linker's range map to see if the FDE
2980     // describes something that we can relocate.
2981     auto Range = Ranges.upper_bound(Loc);
2982     if (Range != Ranges.begin())
2983       --Range;
2984     if (Range == Ranges.end() || Range->first > Loc ||
2985         Range->second.first <= Loc) {
2986       // The +4 is to account for the size of the InitialLength field itself.
2987       InputOffset = EntryOffset + InitialLength + 4;
2988       continue;
2989     }
2990
2991     // This is an FDE, and we have a mapping.
2992     // Have we already emitted a corresponding CIE?
2993     StringRef CIEData = LocalCIES[CIEId];
2994     if (CIEData.empty())
2995       return reportWarning("Inconsistent debug_frame content. Dropping.");
2996
2997     // Look if we already emitted a CIE that corresponds to the
2998     // referenced one (the CIE data is the key of that lookup).
2999     auto IteratorInserted = EmittedCIEs.insert(
3000         std::make_pair(CIEData, Streamer->getFrameSectionSize()));
3001     // If there is no CIE yet for this ID, emit it.
3002     if (IteratorInserted.second ||
3003         // FIXME: dsymutil-classic only caches the last used CIE for
3004         // reuse. Mimic that behavior for now. Just removing that
3005         // second half of the condition and the LastCIEOffset variable
3006         // makes the code DTRT.
3007         LastCIEOffset != IteratorInserted.first->getValue()) {
3008       LastCIEOffset = Streamer->getFrameSectionSize();
3009       IteratorInserted.first->getValue() = LastCIEOffset;
3010       Streamer->emitCIE(CIEData);
3011     }
3012
3013     // Emit the FDE with updated address and CIE pointer.
3014     // (4 + AddrSize) is the size of the CIEId + initial_location
3015     // fields that will get reconstructed by emitFDE().
3016     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3017     Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3018                       Loc + Range->second.second,
3019                       FrameData.substr(InputOffset, FDERemainingBytes));
3020     InputOffset += FDERemainingBytes;
3021   }
3022 }
3023
3024 ErrorOr<const object::ObjectFile &>
3025 DwarfLinker::loadObject(BinaryHolder &BinaryHolder, DebugMapObject &Obj,
3026                         const DebugMap &Map) {
3027   auto ErrOrObjs =
3028       BinaryHolder.GetObjectFiles(Obj.getObjectFilename(), Obj.getTimestamp());
3029   if (std::error_code EC = ErrOrObjs.getError())
3030     reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3031   auto ErrOrObj = BinaryHolder.Get(Map.getTriple());
3032   if (std::error_code EC = ErrOrObj.getError())
3033     reportWarning(Twine(Obj.getObjectFilename()) + ": " + EC.message());
3034   return ErrOrObj;
3035 }
3036
3037 bool DwarfLinker::link(const DebugMap &Map) {
3038
3039   if (Map.begin() == Map.end()) {
3040     errs() << "Empty debug map.\n";
3041     return false;
3042   }
3043
3044   if (!createStreamer(Map.getTriple(), OutputFilename))
3045     return false;
3046
3047   // Size of the DIEs (and headers) generated for the linked output.
3048   uint64_t OutputDebugInfoSize = 0;
3049   // A unique ID that identifies each compile unit.
3050   unsigned UnitID = 0;
3051   for (const auto &Obj : Map.objects()) {
3052     CurrentDebugObject = Obj.get();
3053
3054     if (Options.Verbose)
3055       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3056     auto ErrOrObj = loadObject(BinHolder, *Obj, Map);
3057     if (!ErrOrObj)
3058       continue;
3059
3060     // Look for relocations that correspond to debug map entries.
3061     if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3062       if (Options.Verbose)
3063         outs() << "No valid relocations found. Skipping.\n";
3064       continue;
3065     }
3066
3067     // Setup access to the debug info.
3068     DWARFContextInMemory DwarfContext(*ErrOrObj);
3069     startDebugObject(DwarfContext, *Obj);
3070
3071     // In a first phase, just read in the debug info and store the DIE
3072     // parent links that we will use during the next phase.
3073     for (const auto &CU : DwarfContext.compile_units()) {
3074       auto *CUDie = CU->getUnitDIE(false);
3075       if (Options.Verbose) {
3076         outs() << "Input compilation unit:";
3077         CUDie->dump(outs(), CU.get(), 0);
3078       }
3079       Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3080       gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3081                        StringPool, ODRContexts);
3082     }
3083
3084     // Then mark all the DIEs that need to be present in the linked
3085     // output and collect some information about them. Note that this
3086     // loop can not be merged with the previous one becaue cross-cu
3087     // references require the ParentIdx to be setup for every CU in
3088     // the object file before calling this.
3089     for (auto &CurrentUnit : Units)
3090       lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
3091                         CurrentUnit, 0);
3092
3093     // The calls to applyValidRelocs inside cloneDIE will walk the
3094     // reloc array again (in the same way findValidRelocsInDebugInfo()
3095     // did). We need to reset the NextValidReloc index to the beginning.
3096     NextValidReloc = 0;
3097
3098     // Construct the output DIE tree by cloning the DIEs we chose to
3099     // keep above. If there are no valid relocs, then there's nothing
3100     // to clone/emit.
3101     if (!ValidRelocs.empty())
3102       for (auto &CurrentUnit : Units) {
3103         const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
3104         CurrentUnit.setStartOffset(OutputDebugInfoSize);
3105         DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3106                                   11 /* Unit Header size */);
3107         CurrentUnit.setOutputUnitDIE(OutputDIE);
3108         OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3109         if (Options.NoOutput)
3110           continue;
3111         // FIXME: for compatibility with the classic dsymutil, we emit
3112         // an empty line table for the unit, even if the unit doesn't
3113         // actually exist in the DIE tree.
3114         patchLineTableForUnit(CurrentUnit, DwarfContext);
3115         if (!OutputDIE)
3116           continue;
3117         patchRangesForUnit(CurrentUnit, DwarfContext);
3118         Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3119         emitAcceleratorEntriesForUnit(CurrentUnit);
3120       }
3121
3122     // Emit all the compile unit's debug information.
3123     if (!ValidRelocs.empty() && !Options.NoOutput)
3124       for (auto &CurrentUnit : Units) {
3125         generateUnitRanges(CurrentUnit);
3126         CurrentUnit.fixupForwardReferences();
3127         Streamer->emitCompileUnitHeader(CurrentUnit);
3128         if (!CurrentUnit.getOutputUnitDIE())
3129           continue;
3130         Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3131       }
3132
3133     if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3134       patchFrameInfoForObject(*Obj, DwarfContext,
3135                               Units[0].getOrigUnit().getAddressByteSize());
3136
3137     // Clean-up before starting working on the next object.
3138     endDebugObject();
3139   }
3140
3141   // Emit everything that's global.
3142   if (!Options.NoOutput) {
3143     Streamer->emitAbbrevs(Abbreviations);
3144     Streamer->emitStrings(StringPool);
3145   }
3146
3147   return Options.NoOutput ? true : Streamer->finish();
3148 }
3149 }
3150
3151 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3152                const LinkOptions &Options) {
3153   DwarfLinker Linker(OutputFilename, Options);
3154   return Linker.link(DM);
3155 }
3156 }
3157 }