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