[dsymutil] Remove extra semicolon. 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
1415 private:
1416   std::string OutputFilename;
1417   LinkOptions Options;
1418   BinaryHolder BinHolder;
1419   std::unique_ptr<DwarfStreamer> Streamer;
1420
1421   /// The units of the current debug map object.
1422   std::vector<CompileUnit> Units;
1423
1424   /// The debug map object curently under consideration.
1425   DebugMapObject *CurrentDebugObject;
1426
1427   /// \brief The Dwarf string pool
1428   NonRelocatableStringpool StringPool;
1429
1430   /// \brief This map is keyed by the entry PC of functions in that
1431   /// debug object and the associated value is a pair storing the
1432   /// corresponding end PC and the offset to apply to get the linked
1433   /// address.
1434   ///
1435   /// See startDebugObject() for a more complete description of its use.
1436   std::map<uint64_t, std::pair<uint64_t, int64_t>> Ranges;
1437
1438   /// \brief The CIEs that have been emitted in the output
1439   /// section. The actual CIE data serves a the key to this StringMap,
1440   /// this takes care of comparing the semantics of CIEs defined in
1441   /// different object files.
1442   StringMap<uint32_t> EmittedCIEs;
1443
1444   /// Offset of the last CIE that has been emitted in the output
1445   /// debug_frame section.
1446   uint32_t LastCIEOffset;
1447 };
1448
1449 /// \brief Similar to DWARFUnitSection::getUnitForOffset(), but
1450 /// returning our CompileUnit object instead.
1451 CompileUnit *DwarfLinker::getUnitForOffset(unsigned Offset) {
1452   auto CU =
1453       std::upper_bound(Units.begin(), Units.end(), Offset,
1454                        [](uint32_t LHS, const CompileUnit &RHS) {
1455                          return LHS < RHS.getOrigUnit().getNextUnitOffset();
1456                        });
1457   return CU != Units.end() ? &*CU : nullptr;
1458 }
1459
1460 /// \brief Resolve the DIE attribute reference that has been
1461 /// extracted in \p RefValue. The resulting DIE migh be in another
1462 /// CompileUnit which is stored into \p ReferencedCU.
1463 /// \returns null if resolving fails for any reason.
1464 const DWARFDebugInfoEntryMinimal *DwarfLinker::resolveDIEReference(
1465     const DWARFFormValue &RefValue, const DWARFUnit &Unit,
1466     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit *&RefCU) {
1467   assert(RefValue.isFormClass(DWARFFormValue::FC_Reference));
1468   uint64_t RefOffset = *RefValue.getAsReference(&Unit);
1469
1470   if ((RefCU = getUnitForOffset(RefOffset)))
1471     if (const auto *RefDie = RefCU->getOrigUnit().getDIEForOffset(RefOffset))
1472       return RefDie;
1473
1474   reportWarning("could not find referenced DIE", &Unit, &DIE);
1475   return nullptr;
1476 }
1477
1478 /// \returns whether the passed \a Attr type might contain a DIE
1479 /// reference suitable for ODR uniquing.
1480 static bool isODRAttribute(uint16_t Attr) {
1481   switch (Attr) {
1482   default:
1483     return false;
1484   case dwarf::DW_AT_type:
1485   case dwarf::DW_AT_containing_type:
1486   case dwarf::DW_AT_specification:
1487   case dwarf::DW_AT_abstract_origin:
1488   case dwarf::DW_AT_import:
1489     return true;
1490   }
1491   llvm_unreachable("Improper attribute.");
1492 }
1493
1494 /// Set the last DIE/CU a context was seen in and, possibly invalidate
1495 /// the context if it is ambiguous.
1496 ///
1497 /// In the current implementation, we don't handle overloaded
1498 /// functions well, because the argument types are not taken into
1499 /// account when computing the DeclContext tree.
1500 ///
1501 /// Some of this is mitigated byt using mangled names that do contain
1502 /// the arguments types, but sometimes (eg. with function templates)
1503 /// we don't have that. In that case, just do not unique anything that
1504 /// refers to the contexts we are not able to distinguish.
1505 ///
1506 /// If a context that is not a namespace appears twice in the same CU,
1507 /// we know it is ambiguous. Make it invalid.
1508 bool DeclContext::setLastSeenDIE(CompileUnit &U,
1509                                  const DWARFDebugInfoEntryMinimal *Die) {
1510   if (LastSeenCompileUnitID == U.getUniqueID()) {
1511     DWARFUnit &OrigUnit = U.getOrigUnit();
1512     uint32_t FirstIdx = OrigUnit.getDIEIndex(LastSeenDIE);
1513     U.getInfo(FirstIdx).Ctxt = nullptr;
1514     return false;
1515   }
1516
1517   LastSeenCompileUnitID = U.getUniqueID();
1518   LastSeenDIE = Die;
1519   return true;
1520 }
1521
1522 /// Get the child context of \a Context corresponding to \a DIE.
1523 ///
1524 /// \returns the child context or null if we shouldn't track children
1525 /// contexts. It also returns an additional bit meaning 'invalid'. An
1526 /// invalid context means it shouldn't be considered for uniquing, but
1527 /// its not returning null, because some children of that context
1528 /// might be uniquing candidates.
1529 /// FIXME: this is for dsymutil-classic compatibility, I don't think
1530 /// it buys us much.
1531 PointerIntPair<DeclContext *, 1> DeclContextTree::getChildDeclContext(
1532     DeclContext &Context, const DWARFDebugInfoEntryMinimal *DIE, CompileUnit &U,
1533     NonRelocatableStringpool &StringPool) {
1534   unsigned Tag = DIE->getTag();
1535
1536   // FIXME: dsymutil-classic compat: We should bail out here if we
1537   // have a specification or an abstract_origin. We will get the
1538   // parent context wrong here.
1539
1540   switch (Tag) {
1541   default:
1542     // By default stop gathering child contexts.
1543     return PointerIntPair<DeclContext *, 1>(nullptr);
1544   case dwarf::DW_TAG_compile_unit:
1545     // FIXME: Add support for DW_TAG_module.
1546     return PointerIntPair<DeclContext *, 1>(&Context);
1547   case dwarf::DW_TAG_subprogram:
1548     // Do not unique anything inside CU local functions.
1549     if ((Context.getTag() == dwarf::DW_TAG_namespace ||
1550          Context.getTag() == dwarf::DW_TAG_compile_unit) &&
1551         !DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1552                                                   dwarf::DW_AT_external, 0))
1553       return PointerIntPair<DeclContext *, 1>(nullptr);
1554   // Fallthrough
1555   case dwarf::DW_TAG_member:
1556   case dwarf::DW_TAG_namespace:
1557   case dwarf::DW_TAG_structure_type:
1558   case dwarf::DW_TAG_class_type:
1559   case dwarf::DW_TAG_union_type:
1560   case dwarf::DW_TAG_enumeration_type:
1561   case dwarf::DW_TAG_typedef:
1562     // Artificial things might be ambiguous, because they might be
1563     // created on demand. For example implicitely defined constructors
1564     // are ambiguous because of the way we identify contexts, and they
1565     // won't be generated everytime everywhere.
1566     if (DIE->getAttributeValueAsUnsignedConstant(&U.getOrigUnit(),
1567                                                  dwarf::DW_AT_artificial, 0))
1568       return PointerIntPair<DeclContext *, 1>(nullptr);
1569     break;
1570   }
1571
1572   const char *Name = DIE->getName(&U.getOrigUnit(), DINameKind::LinkageName);
1573   const char *ShortName = DIE->getName(&U.getOrigUnit(), DINameKind::ShortName);
1574   StringRef NameRef;
1575   StringRef ShortNameRef;
1576   StringRef FileRef;
1577
1578   if (Name)
1579     NameRef = StringPool.internString(Name);
1580   else if (Tag == dwarf::DW_TAG_namespace)
1581     // FIXME: For dsymutil-classic compatibility. I think uniquing
1582     // within anonymous namespaces is wrong. There is no ODR guarantee
1583     // there.
1584     NameRef = StringPool.internString("(anonymous namespace)");
1585
1586   if (ShortName && ShortName != Name)
1587     ShortNameRef = StringPool.internString(ShortName);
1588   else
1589     ShortNameRef = NameRef;
1590
1591   if (Tag != dwarf::DW_TAG_class_type && Tag != dwarf::DW_TAG_structure_type &&
1592       Tag != dwarf::DW_TAG_union_type &&
1593       Tag != dwarf::DW_TAG_enumeration_type && NameRef.empty())
1594     return PointerIntPair<DeclContext *, 1>(nullptr);
1595
1596   std::string File;
1597   unsigned Line = 0;
1598   unsigned ByteSize = 0;
1599
1600   // Gather some discriminating data about the DeclContext we will be
1601   // creating: File, line number and byte size. This shouldn't be
1602   // necessary, because the ODR is just about names, but given that we
1603   // do some approximations with overloaded functions and anonymous
1604   // namespaces, use these additional data points to make the process safer.
1605   ByteSize = DIE->getAttributeValueAsUnsignedConstant(
1606       &U.getOrigUnit(), dwarf::DW_AT_byte_size, UINT64_MAX);
1607   if (Tag != dwarf::DW_TAG_namespace || !Name) {
1608     if (unsigned FileNum = DIE->getAttributeValueAsUnsignedConstant(
1609             &U.getOrigUnit(), dwarf::DW_AT_decl_file, 0)) {
1610       if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
1611               &U.getOrigUnit())) {
1612         // FIXME: dsymutil-classic compatibility. I'd rather not
1613         // unique anything in anonymous namespaces, but if we do, then
1614         // verify that the file and line correspond.
1615         if (!Name && Tag == dwarf::DW_TAG_namespace)
1616           FileNum = 1;
1617
1618         // FIXME: Passing U.getOrigUnit().getCompilationDir()
1619         // instead of "" would allow more uniquing, but for now, do
1620         // it this way to match dsymutil-classic.
1621         if (LT->getFileNameByIndex(
1622                 FileNum, "",
1623                 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
1624                 File)) {
1625           Line = DIE->getAttributeValueAsUnsignedConstant(
1626               &U.getOrigUnit(), dwarf::DW_AT_decl_line, 0);
1627 #ifdef HAVE_REALPATH
1628           // Cache the resolved paths, because calling realpath is expansive.
1629           if (const char *ResolvedPath = U.getResolvedPath(FileNum)) {
1630             File = ResolvedPath;
1631           } else {
1632             char RealPath[PATH_MAX + 1];
1633             RealPath[PATH_MAX] = 0;
1634             if (::realpath(File.c_str(), RealPath))
1635               File = RealPath;
1636             U.setResolvedPath(FileNum, File);
1637           }
1638 #endif
1639           FileRef = StringPool.internString(File);
1640         }
1641       }
1642     }
1643   }
1644
1645   if (!Line && NameRef.empty())
1646     return PointerIntPair<DeclContext *, 1>(nullptr);
1647
1648   // FIXME: dsymutil-classic compat won't unique the same type
1649   // presented once as a struct and once as a class. Use the Tag in
1650   // the fully qualified name hash to get the same effect.
1651   // We hash NameRef, which is the mangled name, in order to get most
1652   // overloaded functions resolvec correctly.
1653   unsigned Hash = hash_combine(Context.getQualifiedNameHash(), Tag, NameRef);
1654
1655   // FIXME: dsymutil-classic compatibility: when we don't have a name,
1656   // use the filename.
1657   if (Tag == dwarf::DW_TAG_namespace && NameRef == "(anonymous namespace)")
1658     Hash = hash_combine(Hash, FileRef);
1659
1660   // Now look if this context already exists.
1661   DeclContext Key(Hash, Line, ByteSize, Tag, NameRef, FileRef, Context);
1662   auto ContextIter = Contexts.find(&Key);
1663
1664   if (ContextIter == Contexts.end()) {
1665     // The context wasn't found.
1666     bool Inserted;
1667     DeclContext *NewContext =
1668         new (Allocator) DeclContext(Hash, Line, ByteSize, Tag, NameRef, FileRef,
1669                                     Context, DIE, U.getUniqueID());
1670     std::tie(ContextIter, Inserted) = Contexts.insert(NewContext);
1671     assert(Inserted && "Failed to insert DeclContext");
1672     (void)Inserted;
1673   } else if (Tag != dwarf::DW_TAG_namespace &&
1674              !(*ContextIter)->setLastSeenDIE(U, DIE)) {
1675     // The context was found, but it is ambiguous with another context
1676     // in the same file. Mark it invalid.
1677     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1678   }
1679
1680   assert(ContextIter != Contexts.end());
1681   // FIXME: dsymutil-classic compatibility. Union types aren't
1682   // uniques, but their children might be.
1683   if ((Tag == dwarf::DW_TAG_subprogram &&
1684        Context.getTag() != dwarf::DW_TAG_structure_type &&
1685        Context.getTag() != dwarf::DW_TAG_class_type) ||
1686       (Tag == dwarf::DW_TAG_union_type))
1687     return PointerIntPair<DeclContext *, 1>(*ContextIter, /* Invalid= */ 1);
1688
1689   return PointerIntPair<DeclContext *, 1>(*ContextIter);
1690 }
1691
1692 /// \brief Get the potential name and mangled name for the entity
1693 /// described by \p Die and store them in \Info if they are not
1694 /// already there.
1695 /// \returns is a name was found.
1696 bool DwarfLinker::getDIENames(const DWARFDebugInfoEntryMinimal &Die,
1697                               DWARFUnit &U, AttributesInfo &Info) {
1698   // FIXME: a bit wastefull as the first getName might return the
1699   // short name.
1700   if (!Info.MangledName &&
1701       (Info.MangledName = Die.getName(&U, DINameKind::LinkageName)))
1702     Info.MangledNameOffset = StringPool.getStringOffset(Info.MangledName);
1703
1704   if (!Info.Name && (Info.Name = Die.getName(&U, DINameKind::ShortName)))
1705     Info.NameOffset = StringPool.getStringOffset(Info.Name);
1706
1707   return Info.Name || Info.MangledName;
1708 }
1709
1710 /// \brief Report a warning to the user, optionaly including
1711 /// information about a specific \p DIE related to the warning.
1712 void DwarfLinker::reportWarning(const Twine &Warning, const DWARFUnit *Unit,
1713                                 const DWARFDebugInfoEntryMinimal *DIE) const {
1714   StringRef Context = "<debug map>";
1715   if (CurrentDebugObject)
1716     Context = CurrentDebugObject->getObjectFilename();
1717   warn(Warning, Context);
1718
1719   if (!Options.Verbose || !DIE)
1720     return;
1721
1722   errs() << "    in DIE:\n";
1723   DIE->dump(errs(), const_cast<DWARFUnit *>(Unit), 0 /* RecurseDepth */,
1724             6 /* Indent */);
1725 }
1726
1727 bool DwarfLinker::createStreamer(Triple TheTriple, StringRef OutputFilename) {
1728   if (Options.NoOutput)
1729     return true;
1730
1731   Streamer = llvm::make_unique<DwarfStreamer>();
1732   return Streamer->init(TheTriple, OutputFilename);
1733 }
1734
1735 /// \brief Recursive helper to gather the child->parent relationships in the
1736 /// original compile unit.
1737 static void gatherDIEParents(const DWARFDebugInfoEntryMinimal *DIE,
1738                              unsigned ParentIdx, CompileUnit &CU,
1739                              DeclContext *CurrentDeclContext,
1740                              NonRelocatableStringpool &StringPool,
1741                              DeclContextTree &Contexts) {
1742   unsigned MyIdx = CU.getOrigUnit().getDIEIndex(DIE);
1743   CompileUnit::DIEInfo &Info = CU.getInfo(MyIdx);
1744
1745   Info.ParentIdx = ParentIdx;
1746   if (CU.hasODR()) {
1747     if (CurrentDeclContext) {
1748       auto PtrInvalidPair = Contexts.getChildDeclContext(*CurrentDeclContext,
1749                                                          DIE, CU, StringPool);
1750       CurrentDeclContext = PtrInvalidPair.getPointer();
1751       Info.Ctxt =
1752           PtrInvalidPair.getInt() ? nullptr : PtrInvalidPair.getPointer();
1753     } else
1754       Info.Ctxt = CurrentDeclContext = nullptr;
1755   }
1756
1757   if (DIE->hasChildren())
1758     for (auto *Child = DIE->getFirstChild(); Child && !Child->isNULL();
1759          Child = Child->getSibling())
1760       gatherDIEParents(Child, MyIdx, CU, CurrentDeclContext, StringPool,
1761                        Contexts);
1762 }
1763
1764 static bool dieNeedsChildrenToBeMeaningful(uint32_t Tag) {
1765   switch (Tag) {
1766   default:
1767     return false;
1768   case dwarf::DW_TAG_subprogram:
1769   case dwarf::DW_TAG_lexical_block:
1770   case dwarf::DW_TAG_subroutine_type:
1771   case dwarf::DW_TAG_structure_type:
1772   case dwarf::DW_TAG_class_type:
1773   case dwarf::DW_TAG_union_type:
1774     return true;
1775   }
1776   llvm_unreachable("Invalid Tag");
1777 }
1778
1779 static unsigned getRefAddrSize(const DWARFUnit &U) {
1780   if (U.getVersion() == 2)
1781     return U.getAddressByteSize();
1782   return 4;
1783 }
1784
1785 void DwarfLinker::startDebugObject(DWARFContext &Dwarf, DebugMapObject &Obj) {
1786   Units.reserve(Dwarf.getNumCompileUnits());
1787   NextValidReloc = 0;
1788   // Iterate over the debug map entries and put all the ones that are
1789   // functions (because they have a size) into the Ranges map. This
1790   // map is very similar to the FunctionRanges that are stored in each
1791   // unit, with 2 notable differences:
1792   //  - obviously this one is global, while the other ones are per-unit.
1793   //  - this one contains not only the functions described in the DIE
1794   // tree, but also the ones that are only in the debug map.
1795   // The latter information is required to reproduce dsymutil's logic
1796   // while linking line tables. The cases where this information
1797   // matters look like bugs that need to be investigated, but for now
1798   // we need to reproduce dsymutil's behavior.
1799   // FIXME: Once we understood exactly if that information is needed,
1800   // maybe totally remove this (or try to use it to do a real
1801   // -gline-tables-only on Darwin.
1802   for (const auto &Entry : Obj.symbols()) {
1803     const auto &Mapping = Entry.getValue();
1804     if (Mapping.Size)
1805       Ranges[Mapping.ObjectAddress] = std::make_pair(
1806           Mapping.ObjectAddress + Mapping.Size,
1807           int64_t(Mapping.BinaryAddress) - Mapping.ObjectAddress);
1808   }
1809 }
1810
1811 void DwarfLinker::endDebugObject() {
1812   Units.clear();
1813   ValidRelocs.clear();
1814   Ranges.clear();
1815
1816   for (auto I = DIEBlocks.begin(), E = DIEBlocks.end(); I != E; ++I)
1817     (*I)->~DIEBlock();
1818   for (auto I = DIELocs.begin(), E = DIELocs.end(); I != E; ++I)
1819     (*I)->~DIELoc();
1820
1821   DIEBlocks.clear();
1822   DIELocs.clear();
1823   DIEAlloc.Reset();
1824 }
1825
1826 /// \brief Iterate over the relocations of the given \p Section and
1827 /// store the ones that correspond to debug map entries into the
1828 /// ValidRelocs array.
1829 void DwarfLinker::findValidRelocsMachO(const object::SectionRef &Section,
1830                                        const object::MachOObjectFile &Obj,
1831                                        const DebugMapObject &DMO) {
1832   StringRef Contents;
1833   Section.getContents(Contents);
1834   DataExtractor Data(Contents, Obj.isLittleEndian(), 0);
1835
1836   for (const object::RelocationRef &Reloc : Section.relocations()) {
1837     object::DataRefImpl RelocDataRef = Reloc.getRawDataRefImpl();
1838     MachO::any_relocation_info MachOReloc = Obj.getRelocation(RelocDataRef);
1839     unsigned RelocSize = 1 << Obj.getAnyRelocationLength(MachOReloc);
1840     uint64_t Offset64 = Reloc.getOffset();
1841     if ((RelocSize != 4 && RelocSize != 8)) {
1842       reportWarning(" unsupported relocation in debug_info section.");
1843       continue;
1844     }
1845     uint32_t Offset = Offset64;
1846     // Mach-o uses REL relocations, the addend is at the relocation offset.
1847     uint64_t Addend = Data.getUnsigned(&Offset, RelocSize);
1848
1849     auto Sym = Reloc.getSymbol();
1850     if (Sym != Obj.symbol_end()) {
1851       ErrorOr<StringRef> SymbolName = Sym->getName();
1852       if (!SymbolName) {
1853         reportWarning("error getting relocation symbol name.");
1854         continue;
1855       }
1856       if (const auto *Mapping = DMO.lookupSymbol(*SymbolName))
1857         ValidRelocs.emplace_back(Offset64, RelocSize, Addend, Mapping);
1858     } else if (const auto *Mapping = DMO.lookupObjectAddress(Addend)) {
1859       // Do not store the addend. The addend was the address of the
1860       // symbol in the object file, the address in the binary that is
1861       // stored in the debug map doesn't need to be offseted.
1862       ValidRelocs.emplace_back(Offset64, RelocSize, 0, Mapping);
1863     }
1864   }
1865 }
1866
1867 /// \brief Dispatch the valid relocation finding logic to the
1868 /// appropriate handler depending on the object file format.
1869 bool DwarfLinker::findValidRelocs(const object::SectionRef &Section,
1870                                   const object::ObjectFile &Obj,
1871                                   const DebugMapObject &DMO) {
1872   // Dispatch to the right handler depending on the file type.
1873   if (auto *MachOObj = dyn_cast<object::MachOObjectFile>(&Obj))
1874     findValidRelocsMachO(Section, *MachOObj, DMO);
1875   else
1876     reportWarning(Twine("unsupported object file type: ") + Obj.getFileName());
1877
1878   if (ValidRelocs.empty())
1879     return false;
1880
1881   // Sort the relocations by offset. We will walk the DIEs linearly in
1882   // the file, this allows us to just keep an index in the relocation
1883   // array that we advance during our walk, rather than resorting to
1884   // some associative container. See DwarfLinker::NextValidReloc.
1885   std::sort(ValidRelocs.begin(), ValidRelocs.end());
1886   return true;
1887 }
1888
1889 /// \brief Look for relocations in the debug_info section that match
1890 /// entries in the debug map. These relocations will drive the Dwarf
1891 /// link by indicating which DIEs refer to symbols present in the
1892 /// linked binary.
1893 /// \returns wether there are any valid relocations in the debug info.
1894 bool DwarfLinker::findValidRelocsInDebugInfo(const object::ObjectFile &Obj,
1895                                              const DebugMapObject &DMO) {
1896   // Find the debug_info section.
1897   for (const object::SectionRef &Section : Obj.sections()) {
1898     StringRef SectionName;
1899     Section.getName(SectionName);
1900     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
1901     if (SectionName != "debug_info")
1902       continue;
1903     return findValidRelocs(Section, Obj, DMO);
1904   }
1905   return false;
1906 }
1907
1908 /// \brief Checks that there is a relocation against an actual debug
1909 /// map entry between \p StartOffset and \p NextOffset.
1910 ///
1911 /// This function must be called with offsets in strictly ascending
1912 /// order because it never looks back at relocations it already 'went past'.
1913 /// \returns true and sets Info.InDebugMap if it is the case.
1914 bool DwarfLinker::hasValidRelocation(uint32_t StartOffset, uint32_t EndOffset,
1915                                      CompileUnit::DIEInfo &Info) {
1916   assert(NextValidReloc == 0 ||
1917          StartOffset > ValidRelocs[NextValidReloc - 1].Offset);
1918   if (NextValidReloc >= ValidRelocs.size())
1919     return false;
1920
1921   uint64_t RelocOffset = ValidRelocs[NextValidReloc].Offset;
1922
1923   // We might need to skip some relocs that we didn't consider. For
1924   // example the high_pc of a discarded DIE might contain a reloc that
1925   // is in the list because it actually corresponds to the start of a
1926   // function that is in the debug map.
1927   while (RelocOffset < StartOffset && NextValidReloc < ValidRelocs.size() - 1)
1928     RelocOffset = ValidRelocs[++NextValidReloc].Offset;
1929
1930   if (RelocOffset < StartOffset || RelocOffset >= EndOffset)
1931     return false;
1932
1933   const auto &ValidReloc = ValidRelocs[NextValidReloc++];
1934   const auto &Mapping = ValidReloc.Mapping->getValue();
1935   if (Options.Verbose)
1936     outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
1937            << " " << format("\t%016" PRIx64 " => %016" PRIx64,
1938                             uint64_t(Mapping.ObjectAddress),
1939                             uint64_t(Mapping.BinaryAddress));
1940
1941   Info.AddrAdjust = int64_t(Mapping.BinaryAddress) + ValidReloc.Addend -
1942                     Mapping.ObjectAddress;
1943   Info.InDebugMap = true;
1944   return true;
1945 }
1946
1947 /// \brief Get the starting and ending (exclusive) offset for the
1948 /// attribute with index \p Idx descibed by \p Abbrev. \p Offset is
1949 /// supposed to point to the position of the first attribute described
1950 /// by \p Abbrev.
1951 /// \return [StartOffset, EndOffset) as a pair.
1952 static std::pair<uint32_t, uint32_t>
1953 getAttributeOffsets(const DWARFAbbreviationDeclaration *Abbrev, unsigned Idx,
1954                     unsigned Offset, const DWARFUnit &Unit) {
1955   DataExtractor Data = Unit.getDebugInfoExtractor();
1956
1957   for (unsigned i = 0; i < Idx; ++i)
1958     DWARFFormValue::skipValue(Abbrev->getFormByIndex(i), Data, &Offset, &Unit);
1959
1960   uint32_t End = Offset;
1961   DWARFFormValue::skipValue(Abbrev->getFormByIndex(Idx), Data, &End, &Unit);
1962
1963   return std::make_pair(Offset, End);
1964 }
1965
1966 /// \brief Check if a variable describing DIE should be kept.
1967 /// \returns updated TraversalFlags.
1968 unsigned DwarfLinker::shouldKeepVariableDIE(
1969     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
1970     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
1971   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
1972
1973   // Global variables with constant value can always be kept.
1974   if (!(Flags & TF_InFunctionScope) &&
1975       Abbrev->findAttributeIndex(dwarf::DW_AT_const_value) != -1U) {
1976     MyInfo.InDebugMap = true;
1977     return Flags | TF_Keep;
1978   }
1979
1980   uint32_t LocationIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_location);
1981   if (LocationIdx == -1U)
1982     return Flags;
1983
1984   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
1985   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
1986   uint32_t LocationOffset, LocationEndOffset;
1987   std::tie(LocationOffset, LocationEndOffset) =
1988       getAttributeOffsets(Abbrev, LocationIdx, Offset, OrigUnit);
1989
1990   // See if there is a relocation to a valid debug map entry inside
1991   // this variable's location. The order is important here. We want to
1992   // always check in the variable has a valid relocation, so that the
1993   // DIEInfo is filled. However, we don't want a static variable in a
1994   // function to force us to keep the enclosing function.
1995   if (!hasValidRelocation(LocationOffset, LocationEndOffset, MyInfo) ||
1996       (Flags & TF_InFunctionScope))
1997     return Flags;
1998
1999   if (Options.Verbose)
2000     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2001
2002   return Flags | TF_Keep;
2003 }
2004
2005 /// \brief Check if a function describing DIE should be kept.
2006 /// \returns updated TraversalFlags.
2007 unsigned DwarfLinker::shouldKeepSubprogramDIE(
2008     const DWARFDebugInfoEntryMinimal &DIE, CompileUnit &Unit,
2009     CompileUnit::DIEInfo &MyInfo, unsigned Flags) {
2010   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2011
2012   Flags |= TF_InFunctionScope;
2013
2014   uint32_t LowPcIdx = Abbrev->findAttributeIndex(dwarf::DW_AT_low_pc);
2015   if (LowPcIdx == -1U)
2016     return Flags;
2017
2018   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2019   const DWARFUnit &OrigUnit = Unit.getOrigUnit();
2020   uint32_t LowPcOffset, LowPcEndOffset;
2021   std::tie(LowPcOffset, LowPcEndOffset) =
2022       getAttributeOffsets(Abbrev, LowPcIdx, Offset, OrigUnit);
2023
2024   uint64_t LowPc =
2025       DIE.getAttributeValueAsAddress(&OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2026   assert(LowPc != -1ULL && "low_pc attribute is not an address.");
2027   if (LowPc == -1ULL ||
2028       !hasValidRelocation(LowPcOffset, LowPcEndOffset, MyInfo))
2029     return Flags;
2030
2031   if (Options.Verbose)
2032     DIE.dump(outs(), const_cast<DWARFUnit *>(&OrigUnit), 0, 8 /* Indent */);
2033
2034   Flags |= TF_Keep;
2035
2036   DWARFFormValue HighPcValue;
2037   if (!DIE.getAttributeValue(&OrigUnit, dwarf::DW_AT_high_pc, HighPcValue)) {
2038     reportWarning("Function without high_pc. Range will be discarded.\n",
2039                   &OrigUnit, &DIE);
2040     return Flags;
2041   }
2042
2043   uint64_t HighPc;
2044   if (HighPcValue.isFormClass(DWARFFormValue::FC_Address)) {
2045     HighPc = *HighPcValue.getAsAddress(&OrigUnit);
2046   } else {
2047     assert(HighPcValue.isFormClass(DWARFFormValue::FC_Constant));
2048     HighPc = LowPc + *HighPcValue.getAsUnsignedConstant();
2049   }
2050
2051   // Replace the debug map range with a more accurate one.
2052   Ranges[LowPc] = std::make_pair(HighPc, MyInfo.AddrAdjust);
2053   Unit.addFunctionRange(LowPc, HighPc, MyInfo.AddrAdjust);
2054   return Flags;
2055 }
2056
2057 /// \brief Check if a DIE should be kept.
2058 /// \returns updated TraversalFlags.
2059 unsigned DwarfLinker::shouldKeepDIE(const DWARFDebugInfoEntryMinimal &DIE,
2060                                     CompileUnit &Unit,
2061                                     CompileUnit::DIEInfo &MyInfo,
2062                                     unsigned Flags) {
2063   switch (DIE.getTag()) {
2064   case dwarf::DW_TAG_constant:
2065   case dwarf::DW_TAG_variable:
2066     return shouldKeepVariableDIE(DIE, Unit, MyInfo, Flags);
2067   case dwarf::DW_TAG_subprogram:
2068     return shouldKeepSubprogramDIE(DIE, Unit, MyInfo, Flags);
2069   case dwarf::DW_TAG_module:
2070   case dwarf::DW_TAG_imported_module:
2071   case dwarf::DW_TAG_imported_declaration:
2072   case dwarf::DW_TAG_imported_unit:
2073     // We always want to keep these.
2074     return Flags | TF_Keep;
2075   }
2076
2077   return Flags;
2078 }
2079
2080 /// \brief Mark the passed DIE as well as all the ones it depends on
2081 /// as kept.
2082 ///
2083 /// This function is called by lookForDIEsToKeep on DIEs that are
2084 /// newly discovered to be needed in the link. It recursively calls
2085 /// back to lookForDIEsToKeep while adding TF_DependencyWalk to the
2086 /// TraversalFlags to inform it that it's not doing the primary DIE
2087 /// tree walk.
2088 void DwarfLinker::keepDIEAndDenpendencies(const DWARFDebugInfoEntryMinimal &DIE,
2089                                           CompileUnit::DIEInfo &MyInfo,
2090                                           const DebugMapObject &DMO,
2091                                           CompileUnit &CU, bool UseODR) {
2092   const DWARFUnit &Unit = CU.getOrigUnit();
2093   MyInfo.Keep = true;
2094
2095   // First mark all the parent chain as kept.
2096   unsigned AncestorIdx = MyInfo.ParentIdx;
2097   while (!CU.getInfo(AncestorIdx).Keep) {
2098     unsigned ODRFlag = UseODR ? TF_ODR : 0;
2099     lookForDIEsToKeep(*Unit.getDIEAtIndex(AncestorIdx), DMO, CU,
2100                       TF_ParentWalk | TF_Keep | TF_DependencyWalk | ODRFlag);
2101     AncestorIdx = CU.getInfo(AncestorIdx).ParentIdx;
2102   }
2103
2104   // Then we need to mark all the DIEs referenced by this DIE's
2105   // attributes as kept.
2106   DataExtractor Data = Unit.getDebugInfoExtractor();
2107   const auto *Abbrev = DIE.getAbbreviationDeclarationPtr();
2108   uint32_t Offset = DIE.getOffset() + getULEB128Size(Abbrev->getCode());
2109
2110   // Mark all DIEs referenced through atttributes as kept.
2111   for (const auto &AttrSpec : Abbrev->attributes()) {
2112     DWARFFormValue Val(AttrSpec.Form);
2113
2114     if (!Val.isFormClass(DWARFFormValue::FC_Reference)) {
2115       DWARFFormValue::skipValue(AttrSpec.Form, Data, &Offset, &Unit);
2116       continue;
2117     }
2118
2119     Val.extractValue(Data, &Offset, &Unit);
2120     CompileUnit *ReferencedCU;
2121     if (const auto *RefDIE =
2122             resolveDIEReference(Val, Unit, DIE, ReferencedCU)) {
2123       uint32_t RefIdx = ReferencedCU->getOrigUnit().getDIEIndex(RefDIE);
2124       CompileUnit::DIEInfo &Info = ReferencedCU->getInfo(RefIdx);
2125       // If the referenced DIE has a DeclContext that has already been
2126       // emitted, then do not keep the one in this CU. We'll link to
2127       // the canonical DIE in cloneDieReferenceAttribute.
2128       // FIXME: compatibility with dsymutil-classic. UseODR shouldn't
2129       // be necessary and could be advantageously replaced by
2130       // ReferencedCU->hasODR() && CU.hasODR().
2131       // FIXME: compatibility with dsymutil-classic. There is no
2132       // reason not to unique ref_addr references.
2133       if (AttrSpec.Form != dwarf::DW_FORM_ref_addr && UseODR && Info.Ctxt &&
2134           Info.Ctxt != ReferencedCU->getInfo(Info.ParentIdx).Ctxt &&
2135           Info.Ctxt->getCanonicalDIEOffset() && isODRAttribute(AttrSpec.Attr))
2136         continue;
2137
2138       unsigned ODRFlag = UseODR ? TF_ODR : 0;
2139       lookForDIEsToKeep(*RefDIE, DMO, *ReferencedCU,
2140                         TF_Keep | TF_DependencyWalk | ODRFlag);
2141     }
2142   }
2143 }
2144
2145 /// \brief Recursively walk the \p DIE tree and look for DIEs to
2146 /// keep. Store that information in \p CU's DIEInfo.
2147 ///
2148 /// This function is the entry point of the DIE selection
2149 /// algorithm. It is expected to walk the DIE tree in file order and
2150 /// (though the mediation of its helper) call hasValidRelocation() on
2151 /// each DIE that might be a 'root DIE' (See DwarfLinker class
2152 /// comment).
2153 /// While walking the dependencies of root DIEs, this function is
2154 /// also called, but during these dependency walks the file order is
2155 /// not respected. The TF_DependencyWalk flag tells us which kind of
2156 /// traversal we are currently doing.
2157 void DwarfLinker::lookForDIEsToKeep(const DWARFDebugInfoEntryMinimal &DIE,
2158                                     const DebugMapObject &DMO, CompileUnit &CU,
2159                                     unsigned Flags) {
2160   unsigned Idx = CU.getOrigUnit().getDIEIndex(&DIE);
2161   CompileUnit::DIEInfo &MyInfo = CU.getInfo(Idx);
2162   bool AlreadyKept = MyInfo.Keep;
2163
2164   // If the Keep flag is set, we are marking a required DIE's
2165   // dependencies. If our target is already marked as kept, we're all
2166   // set.
2167   if ((Flags & TF_DependencyWalk) && AlreadyKept)
2168     return;
2169
2170   // We must not call shouldKeepDIE while called from keepDIEAndDenpendencies,
2171   // because it would screw up the relocation finding logic.
2172   if (!(Flags & TF_DependencyWalk))
2173     Flags = shouldKeepDIE(DIE, CU, MyInfo, Flags);
2174
2175   // If it is a newly kept DIE mark it as well as all its dependencies as kept.
2176   if (!AlreadyKept && (Flags & TF_Keep)) {
2177     bool UseOdr = (Flags & TF_DependencyWalk) ? (Flags & TF_ODR) : CU.hasODR();
2178     keepDIEAndDenpendencies(DIE, MyInfo, DMO, CU, UseOdr);
2179   }
2180   // The TF_ParentWalk flag tells us that we are currently walking up
2181   // the parent chain of a required DIE, and we don't want to mark all
2182   // the children of the parents as kept (consider for example a
2183   // DW_TAG_namespace node in the parent chain). There are however a
2184   // set of DIE types for which we want to ignore that directive and still
2185   // walk their children.
2186   if (dieNeedsChildrenToBeMeaningful(DIE.getTag()))
2187     Flags &= ~TF_ParentWalk;
2188
2189   if (!DIE.hasChildren() || (Flags & TF_ParentWalk))
2190     return;
2191
2192   for (auto *Child = DIE.getFirstChild(); Child && !Child->isNULL();
2193        Child = Child->getSibling())
2194     lookForDIEsToKeep(*Child, DMO, CU, Flags);
2195 }
2196
2197 /// \brief Assign an abbreviation numer to \p Abbrev.
2198 ///
2199 /// Our DIEs get freed after every DebugMapObject has been processed,
2200 /// thus the FoldingSet we use to unique DIEAbbrevs cannot refer to
2201 /// the instances hold by the DIEs. When we encounter an abbreviation
2202 /// that we don't know, we create a permanent copy of it.
2203 void DwarfLinker::AssignAbbrev(DIEAbbrev &Abbrev) {
2204   // Check the set for priors.
2205   FoldingSetNodeID ID;
2206   Abbrev.Profile(ID);
2207   void *InsertToken;
2208   DIEAbbrev *InSet = AbbreviationsSet.FindNodeOrInsertPos(ID, InsertToken);
2209
2210   // If it's newly added.
2211   if (InSet) {
2212     // Assign existing abbreviation number.
2213     Abbrev.setNumber(InSet->getNumber());
2214   } else {
2215     // Add to abbreviation list.
2216     Abbreviations.push_back(
2217         new DIEAbbrev(Abbrev.getTag(), Abbrev.hasChildren()));
2218     for (const auto &Attr : Abbrev.getData())
2219       Abbreviations.back()->AddAttribute(Attr.getAttribute(), Attr.getForm());
2220     AbbreviationsSet.InsertNode(Abbreviations.back(), InsertToken);
2221     // Assign the unique abbreviation number.
2222     Abbrev.setNumber(Abbreviations.size());
2223     Abbreviations.back()->setNumber(Abbreviations.size());
2224   }
2225 }
2226
2227 /// \brief Clone a string attribute described by \p AttrSpec and add
2228 /// it to \p Die.
2229 /// \returns the size of the new attribute.
2230 unsigned DwarfLinker::cloneStringAttribute(DIE &Die, AttributeSpec AttrSpec,
2231                                            const DWARFFormValue &Val,
2232                                            const DWARFUnit &U) {
2233   // Switch everything to out of line strings.
2234   const char *String = *Val.getAsCString(&U);
2235   unsigned Offset = StringPool.getStringOffset(String);
2236   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr), dwarf::DW_FORM_strp,
2237                DIEInteger(Offset));
2238   return 4;
2239 }
2240
2241 /// \brief Clone an attribute referencing another DIE and add
2242 /// it to \p Die.
2243 /// \returns the size of the new attribute.
2244 unsigned DwarfLinker::cloneDieReferenceAttribute(
2245     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE,
2246     AttributeSpec AttrSpec, unsigned AttrSize, const DWARFFormValue &Val,
2247     CompileUnit &Unit) {
2248   const DWARFUnit &U = Unit.getOrigUnit();
2249   uint32_t Ref = *Val.getAsReference(&U);
2250   DIE *NewRefDie = nullptr;
2251   CompileUnit *RefUnit = nullptr;
2252   DeclContext *Ctxt = nullptr;
2253
2254   const DWARFDebugInfoEntryMinimal *RefDie =
2255       resolveDIEReference(Val, U, InputDIE, RefUnit);
2256
2257   // If the referenced DIE is not found,  drop the attribute.
2258   if (!RefDie)
2259     return 0;
2260
2261   unsigned Idx = RefUnit->getOrigUnit().getDIEIndex(RefDie);
2262   CompileUnit::DIEInfo &RefInfo = RefUnit->getInfo(Idx);
2263
2264   // If we already have emitted an equivalent DeclContext, just point
2265   // at it.
2266   if (isODRAttribute(AttrSpec.Attr)) {
2267     Ctxt = RefInfo.Ctxt;
2268     if (Ctxt && Ctxt->getCanonicalDIEOffset()) {
2269       DIEInteger Attr(Ctxt->getCanonicalDIEOffset());
2270       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2271                    dwarf::DW_FORM_ref_addr, Attr);
2272       return getRefAddrSize(U);
2273     }
2274   }
2275
2276   if (!RefInfo.Clone) {
2277     assert(Ref > InputDIE.getOffset());
2278     // We haven't cloned this DIE yet. Just create an empty one and
2279     // store it. It'll get really cloned when we process it.
2280     RefInfo.Clone = DIE::get(DIEAlloc, dwarf::Tag(RefDie->getTag()));
2281   }
2282   NewRefDie = RefInfo.Clone;
2283
2284   if (AttrSpec.Form == dwarf::DW_FORM_ref_addr ||
2285       (Unit.hasODR() && isODRAttribute(AttrSpec.Attr))) {
2286     // We cannot currently rely on a DIEEntry to emit ref_addr
2287     // references, because the implementation calls back to DwarfDebug
2288     // to find the unit offset. (We don't have a DwarfDebug)
2289     // FIXME: we should be able to design DIEEntry reliance on
2290     // DwarfDebug away.
2291     uint64_t Attr;
2292     if (Ref < InputDIE.getOffset()) {
2293       // We must have already cloned that DIE.
2294       uint32_t NewRefOffset =
2295           RefUnit->getStartOffset() + NewRefDie->getOffset();
2296       Attr = NewRefOffset;
2297       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2298                    dwarf::DW_FORM_ref_addr, DIEInteger(Attr));
2299     } else {
2300       // A forward reference. Note and fixup later.
2301       Attr = 0xBADDEF;
2302       Unit.noteForwardReference(
2303           NewRefDie, RefUnit, Ctxt,
2304           Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2305                        dwarf::DW_FORM_ref_addr, DIEInteger(Attr)));
2306     }
2307     return getRefAddrSize(U);
2308   }
2309
2310   Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2311                dwarf::Form(AttrSpec.Form), DIEEntry(*NewRefDie));
2312   return AttrSize;
2313 }
2314
2315 /// \brief Clone an attribute of block form (locations, constants) and add
2316 /// it to \p Die.
2317 /// \returns the size of the new attribute.
2318 unsigned DwarfLinker::cloneBlockAttribute(DIE &Die, AttributeSpec AttrSpec,
2319                                           const DWARFFormValue &Val,
2320                                           unsigned AttrSize) {
2321   DIE *Attr;
2322   DIEValue Value;
2323   DIELoc *Loc = nullptr;
2324   DIEBlock *Block = nullptr;
2325   // Just copy the block data over.
2326   if (AttrSpec.Form == dwarf::DW_FORM_exprloc) {
2327     Loc = new (DIEAlloc) DIELoc;
2328     DIELocs.push_back(Loc);
2329   } else {
2330     Block = new (DIEAlloc) DIEBlock;
2331     DIEBlocks.push_back(Block);
2332   }
2333   Attr = Loc ? static_cast<DIE *>(Loc) : static_cast<DIE *>(Block);
2334
2335   if (Loc)
2336     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2337                      dwarf::Form(AttrSpec.Form), Loc);
2338   else
2339     Value = DIEValue(dwarf::Attribute(AttrSpec.Attr),
2340                      dwarf::Form(AttrSpec.Form), Block);
2341   ArrayRef<uint8_t> Bytes = *Val.getAsBlock();
2342   for (auto Byte : Bytes)
2343     Attr->addValue(DIEAlloc, static_cast<dwarf::Attribute>(0),
2344                    dwarf::DW_FORM_data1, DIEInteger(Byte));
2345   // FIXME: If DIEBlock and DIELoc just reuses the Size field of
2346   // the DIE class, this if could be replaced by
2347   // Attr->setSize(Bytes.size()).
2348   if (Streamer) {
2349     if (Loc)
2350       Loc->ComputeSize(&Streamer->getAsmPrinter());
2351     else
2352       Block->ComputeSize(&Streamer->getAsmPrinter());
2353   }
2354   Die.addValue(DIEAlloc, Value);
2355   return AttrSize;
2356 }
2357
2358 /// \brief Clone an address attribute and add it to \p Die.
2359 /// \returns the size of the new attribute.
2360 unsigned DwarfLinker::cloneAddressAttribute(DIE &Die, AttributeSpec AttrSpec,
2361                                             const DWARFFormValue &Val,
2362                                             const CompileUnit &Unit,
2363                                             AttributesInfo &Info) {
2364   uint64_t Addr = *Val.getAsAddress(&Unit.getOrigUnit());
2365   if (AttrSpec.Attr == dwarf::DW_AT_low_pc) {
2366     if (Die.getTag() == dwarf::DW_TAG_inlined_subroutine ||
2367         Die.getTag() == dwarf::DW_TAG_lexical_block)
2368       Addr += Info.PCOffset;
2369     else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2370       Addr = Unit.getLowPc();
2371       if (Addr == UINT64_MAX)
2372         return 0;
2373     }
2374     Info.HasLowPc = true;
2375   } else if (AttrSpec.Attr == dwarf::DW_AT_high_pc) {
2376     if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
2377       if (uint64_t HighPc = Unit.getHighPc())
2378         Addr = HighPc;
2379       else
2380         return 0;
2381     } else
2382       // If we have a high_pc recorded for the input DIE, use
2383       // it. Otherwise (when no relocations where applied) just use the
2384       // one we just decoded.
2385       Addr = (Info.OrigHighPc ? Info.OrigHighPc : Addr) + Info.PCOffset;
2386   }
2387
2388   Die.addValue(DIEAlloc, static_cast<dwarf::Attribute>(AttrSpec.Attr),
2389                static_cast<dwarf::Form>(AttrSpec.Form), DIEInteger(Addr));
2390   return Unit.getOrigUnit().getAddressByteSize();
2391 }
2392
2393 /// \brief Clone a scalar attribute  and add it to \p Die.
2394 /// \returns the size of the new attribute.
2395 unsigned DwarfLinker::cloneScalarAttribute(
2396     DIE &Die, const DWARFDebugInfoEntryMinimal &InputDIE, CompileUnit &Unit,
2397     AttributeSpec AttrSpec, const DWARFFormValue &Val, unsigned AttrSize,
2398     AttributesInfo &Info) {
2399   uint64_t Value;
2400   if (AttrSpec.Attr == dwarf::DW_AT_high_pc &&
2401       Die.getTag() == dwarf::DW_TAG_compile_unit) {
2402     if (Unit.getLowPc() == -1ULL)
2403       return 0;
2404     // Dwarf >= 4 high_pc is an size, not an address.
2405     Value = Unit.getHighPc() - Unit.getLowPc();
2406   } else if (AttrSpec.Form == dwarf::DW_FORM_sec_offset)
2407     Value = *Val.getAsSectionOffset();
2408   else if (AttrSpec.Form == dwarf::DW_FORM_sdata)
2409     Value = *Val.getAsSignedConstant();
2410   else if (auto OptionalValue = Val.getAsUnsignedConstant())
2411     Value = *OptionalValue;
2412   else {
2413     reportWarning("Unsupported scalar attribute form. Dropping attribute.",
2414                   &Unit.getOrigUnit(), &InputDIE);
2415     return 0;
2416   }
2417   PatchLocation Patch =
2418       Die.addValue(DIEAlloc, dwarf::Attribute(AttrSpec.Attr),
2419                    dwarf::Form(AttrSpec.Form), DIEInteger(Value));
2420   if (AttrSpec.Attr == dwarf::DW_AT_ranges)
2421     Unit.noteRangeAttribute(Die, Patch);
2422   // A more generic way to check for location attributes would be
2423   // nice, but it's very unlikely that any other attribute needs a
2424   // location list.
2425   else if (AttrSpec.Attr == dwarf::DW_AT_location ||
2426            AttrSpec.Attr == dwarf::DW_AT_frame_base)
2427     Unit.noteLocationAttribute(Patch, Info.PCOffset);
2428   else if (AttrSpec.Attr == dwarf::DW_AT_declaration && Value)
2429     Info.IsDeclaration = true;
2430
2431   return AttrSize;
2432 }
2433
2434 /// \brief Clone \p InputDIE's attribute described by \p AttrSpec with
2435 /// value \p Val, and add it to \p Die.
2436 /// \returns the size of the cloned attribute.
2437 unsigned DwarfLinker::cloneAttribute(DIE &Die,
2438                                      const DWARFDebugInfoEntryMinimal &InputDIE,
2439                                      CompileUnit &Unit,
2440                                      const DWARFFormValue &Val,
2441                                      const AttributeSpec AttrSpec,
2442                                      unsigned AttrSize, AttributesInfo &Info) {
2443   const DWARFUnit &U = Unit.getOrigUnit();
2444
2445   switch (AttrSpec.Form) {
2446   case dwarf::DW_FORM_strp:
2447   case dwarf::DW_FORM_string:
2448     return cloneStringAttribute(Die, AttrSpec, Val, U);
2449   case dwarf::DW_FORM_ref_addr:
2450   case dwarf::DW_FORM_ref1:
2451   case dwarf::DW_FORM_ref2:
2452   case dwarf::DW_FORM_ref4:
2453   case dwarf::DW_FORM_ref8:
2454     return cloneDieReferenceAttribute(Die, InputDIE, AttrSpec, AttrSize, Val,
2455                                       Unit);
2456   case dwarf::DW_FORM_block:
2457   case dwarf::DW_FORM_block1:
2458   case dwarf::DW_FORM_block2:
2459   case dwarf::DW_FORM_block4:
2460   case dwarf::DW_FORM_exprloc:
2461     return cloneBlockAttribute(Die, AttrSpec, Val, AttrSize);
2462   case dwarf::DW_FORM_addr:
2463     return cloneAddressAttribute(Die, AttrSpec, Val, Unit, Info);
2464   case dwarf::DW_FORM_data1:
2465   case dwarf::DW_FORM_data2:
2466   case dwarf::DW_FORM_data4:
2467   case dwarf::DW_FORM_data8:
2468   case dwarf::DW_FORM_udata:
2469   case dwarf::DW_FORM_sdata:
2470   case dwarf::DW_FORM_sec_offset:
2471   case dwarf::DW_FORM_flag:
2472   case dwarf::DW_FORM_flag_present:
2473     return cloneScalarAttribute(Die, InputDIE, Unit, AttrSpec, Val, AttrSize,
2474                                 Info);
2475   default:
2476     reportWarning("Unsupported attribute form in cloneAttribute. Dropping.", &U,
2477                   &InputDIE);
2478   }
2479
2480   return 0;
2481 }
2482
2483 /// \brief Apply the valid relocations found by findValidRelocs() to
2484 /// the buffer \p Data, taking into account that Data is at \p BaseOffset
2485 /// in the debug_info section.
2486 ///
2487 /// Like for findValidRelocs(), this function must be called with
2488 /// monotonic \p BaseOffset values.
2489 ///
2490 /// \returns wether any reloc has been applied.
2491 bool DwarfLinker::applyValidRelocs(MutableArrayRef<char> Data,
2492                                    uint32_t BaseOffset, bool isLittleEndian) {
2493   assert((NextValidReloc == 0 ||
2494           BaseOffset > ValidRelocs[NextValidReloc - 1].Offset) &&
2495          "BaseOffset should only be increasing.");
2496   if (NextValidReloc >= ValidRelocs.size())
2497     return false;
2498
2499   // Skip relocs that haven't been applied.
2500   while (NextValidReloc < ValidRelocs.size() &&
2501          ValidRelocs[NextValidReloc].Offset < BaseOffset)
2502     ++NextValidReloc;
2503
2504   bool Applied = false;
2505   uint64_t EndOffset = BaseOffset + Data.size();
2506   while (NextValidReloc < ValidRelocs.size() &&
2507          ValidRelocs[NextValidReloc].Offset >= BaseOffset &&
2508          ValidRelocs[NextValidReloc].Offset < EndOffset) {
2509     const auto &ValidReloc = ValidRelocs[NextValidReloc++];
2510     assert(ValidReloc.Offset - BaseOffset < Data.size());
2511     assert(ValidReloc.Offset - BaseOffset + ValidReloc.Size <= Data.size());
2512     char Buf[8];
2513     uint64_t Value = ValidReloc.Mapping->getValue().BinaryAddress;
2514     Value += ValidReloc.Addend;
2515     for (unsigned i = 0; i != ValidReloc.Size; ++i) {
2516       unsigned Index = isLittleEndian ? i : (ValidReloc.Size - i - 1);
2517       Buf[i] = uint8_t(Value >> (Index * 8));
2518     }
2519     assert(ValidReloc.Size <= sizeof(Buf));
2520     memcpy(&Data[ValidReloc.Offset - BaseOffset], Buf, ValidReloc.Size);
2521     Applied = true;
2522   }
2523
2524   return Applied;
2525 }
2526
2527 static bool isTypeTag(uint16_t Tag) {
2528   switch (Tag) {
2529   case dwarf::DW_TAG_array_type:
2530   case dwarf::DW_TAG_class_type:
2531   case dwarf::DW_TAG_enumeration_type:
2532   case dwarf::DW_TAG_pointer_type:
2533   case dwarf::DW_TAG_reference_type:
2534   case dwarf::DW_TAG_string_type:
2535   case dwarf::DW_TAG_structure_type:
2536   case dwarf::DW_TAG_subroutine_type:
2537   case dwarf::DW_TAG_typedef:
2538   case dwarf::DW_TAG_union_type:
2539   case dwarf::DW_TAG_ptr_to_member_type:
2540   case dwarf::DW_TAG_set_type:
2541   case dwarf::DW_TAG_subrange_type:
2542   case dwarf::DW_TAG_base_type:
2543   case dwarf::DW_TAG_const_type:
2544   case dwarf::DW_TAG_constant:
2545   case dwarf::DW_TAG_file_type:
2546   case dwarf::DW_TAG_namelist:
2547   case dwarf::DW_TAG_packed_type:
2548   case dwarf::DW_TAG_volatile_type:
2549   case dwarf::DW_TAG_restrict_type:
2550   case dwarf::DW_TAG_interface_type:
2551   case dwarf::DW_TAG_unspecified_type:
2552   case dwarf::DW_TAG_shared_type:
2553     return true;
2554   default:
2555     break;
2556   }
2557   return false;
2558 }
2559
2560 /// \brief Recursively clone \p InputDIE's subtrees that have been
2561 /// selected to appear in the linked output.
2562 ///
2563 /// \param OutOffset is the Offset where the newly created DIE will
2564 /// lie in the linked compile unit.
2565 ///
2566 /// \returns the cloned DIE object or null if nothing was selected.
2567 DIE *DwarfLinker::cloneDIE(const DWARFDebugInfoEntryMinimal &InputDIE,
2568                            CompileUnit &Unit, int64_t PCOffset,
2569                            uint32_t OutOffset) {
2570   DWARFUnit &U = Unit.getOrigUnit();
2571   unsigned Idx = U.getDIEIndex(&InputDIE);
2572   CompileUnit::DIEInfo &Info = Unit.getInfo(Idx);
2573
2574   // Should the DIE appear in the output?
2575   if (!Unit.getInfo(Idx).Keep)
2576     return nullptr;
2577
2578   uint32_t Offset = InputDIE.getOffset();
2579   // The DIE might have been already created by a forward reference
2580   // (see cloneDieReferenceAttribute()).
2581   DIE *Die = Info.Clone;
2582   if (!Die)
2583     Die = Info.Clone = DIE::get(DIEAlloc, dwarf::Tag(InputDIE.getTag()));
2584   assert(Die->getTag() == InputDIE.getTag());
2585   Die->setOffset(OutOffset);
2586   if (Unit.hasODR() && Die->getTag() != dwarf::DW_TAG_namespace && Info.Ctxt &&
2587       Info.Ctxt != Unit.getInfo(Info.ParentIdx).Ctxt &&
2588       !Info.Ctxt->getCanonicalDIEOffset()) {
2589     // We are about to emit a DIE that is the root of its own valid
2590     // DeclContext tree. Make the current offset the canonical offset
2591     // for this context.
2592     Info.Ctxt->setCanonicalDIEOffset(OutOffset + Unit.getStartOffset());
2593   }
2594
2595   // Extract and clone every attribute.
2596   DataExtractor Data = U.getDebugInfoExtractor();
2597   uint32_t NextOffset = U.getDIEAtIndex(Idx + 1)->getOffset();
2598   AttributesInfo AttrInfo;
2599
2600   // We could copy the data only if we need to aply a relocation to
2601   // it. After testing, it seems there is no performance downside to
2602   // doing the copy unconditionally, and it makes the code simpler.
2603   SmallString<40> DIECopy(Data.getData().substr(Offset, NextOffset - Offset));
2604   Data = DataExtractor(DIECopy, Data.isLittleEndian(), Data.getAddressSize());
2605   // Modify the copy with relocated addresses.
2606   if (applyValidRelocs(DIECopy, Offset, Data.isLittleEndian())) {
2607     // If we applied relocations, we store the value of high_pc that was
2608     // potentially stored in the input DIE. If high_pc is an address
2609     // (Dwarf version == 2), then it might have been relocated to a
2610     // totally unrelated value (because the end address in the object
2611     // file might be start address of another function which got moved
2612     // independantly by the linker). The computation of the actual
2613     // high_pc value is done in cloneAddressAttribute().
2614     AttrInfo.OrigHighPc =
2615         InputDIE.getAttributeValueAsAddress(&U, dwarf::DW_AT_high_pc, 0);
2616   }
2617
2618   // Reset the Offset to 0 as we will be working on the local copy of
2619   // the data.
2620   Offset = 0;
2621
2622   const auto *Abbrev = InputDIE.getAbbreviationDeclarationPtr();
2623   Offset += getULEB128Size(Abbrev->getCode());
2624
2625   // We are entering a subprogram. Get and propagate the PCOffset.
2626   if (Die->getTag() == dwarf::DW_TAG_subprogram)
2627     PCOffset = Info.AddrAdjust;
2628   AttrInfo.PCOffset = PCOffset;
2629
2630   for (const auto &AttrSpec : Abbrev->attributes()) {
2631     DWARFFormValue Val(AttrSpec.Form);
2632     uint32_t AttrSize = Offset;
2633     Val.extractValue(Data, &Offset, &U);
2634     AttrSize = Offset - AttrSize;
2635
2636     OutOffset +=
2637         cloneAttribute(*Die, InputDIE, Unit, Val, AttrSpec, AttrSize, AttrInfo);
2638   }
2639
2640   // Look for accelerator entries.
2641   uint16_t Tag = InputDIE.getTag();
2642   // FIXME: This is slightly wrong. An inline_subroutine without a
2643   // low_pc, but with AT_ranges might be interesting to get into the
2644   // accelerator tables too. For now stick with dsymutil's behavior.
2645   if ((Info.InDebugMap || AttrInfo.HasLowPc) &&
2646       Tag != dwarf::DW_TAG_compile_unit &&
2647       getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2648     if (AttrInfo.MangledName && AttrInfo.MangledName != AttrInfo.Name)
2649       Unit.addNameAccelerator(Die, AttrInfo.MangledName,
2650                               AttrInfo.MangledNameOffset,
2651                               Tag == dwarf::DW_TAG_inlined_subroutine);
2652     if (AttrInfo.Name)
2653       Unit.addNameAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset,
2654                               Tag == dwarf::DW_TAG_inlined_subroutine);
2655   } else if (isTypeTag(Tag) && !AttrInfo.IsDeclaration &&
2656              getDIENames(InputDIE, Unit.getOrigUnit(), AttrInfo)) {
2657     Unit.addTypeAccelerator(Die, AttrInfo.Name, AttrInfo.NameOffset);
2658   }
2659
2660   DIEAbbrev NewAbbrev = Die->generateAbbrev();
2661   // If a scope DIE is kept, we must have kept at least one child. If
2662   // it's not the case, we'll just be emitting one wasteful end of
2663   // children marker, but things won't break.
2664   if (InputDIE.hasChildren())
2665     NewAbbrev.setChildrenFlag(dwarf::DW_CHILDREN_yes);
2666   // Assign a permanent abbrev number
2667   AssignAbbrev(NewAbbrev);
2668   Die->setAbbrevNumber(NewAbbrev.getNumber());
2669
2670   // Add the size of the abbreviation number to the output offset.
2671   OutOffset += getULEB128Size(Die->getAbbrevNumber());
2672
2673   if (!Abbrev->hasChildren()) {
2674     // Update our size.
2675     Die->setSize(OutOffset - Die->getOffset());
2676     return Die;
2677   }
2678
2679   // Recursively clone children.
2680   for (auto *Child = InputDIE.getFirstChild(); Child && !Child->isNULL();
2681        Child = Child->getSibling()) {
2682     if (DIE *Clone = cloneDIE(*Child, Unit, PCOffset, OutOffset)) {
2683       Die->addChild(Clone);
2684       OutOffset = Clone->getOffset() + Clone->getSize();
2685     }
2686   }
2687
2688   // Account for the end of children marker.
2689   OutOffset += sizeof(int8_t);
2690   // Update our size.
2691   Die->setSize(OutOffset - Die->getOffset());
2692   return Die;
2693 }
2694
2695 /// \brief Patch the input object file relevant debug_ranges entries
2696 /// and emit them in the output file. Update the relevant attributes
2697 /// to point at the new entries.
2698 void DwarfLinker::patchRangesForUnit(const CompileUnit &Unit,
2699                                      DWARFContext &OrigDwarf) const {
2700   DWARFDebugRangeList RangeList;
2701   const auto &FunctionRanges = Unit.getFunctionRanges();
2702   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
2703   DataExtractor RangeExtractor(OrigDwarf.getRangeSection(),
2704                                OrigDwarf.isLittleEndian(), AddressSize);
2705   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2706   DWARFUnit &OrigUnit = Unit.getOrigUnit();
2707   const auto *OrigUnitDie = OrigUnit.getUnitDIE(false);
2708   uint64_t OrigLowPc = OrigUnitDie->getAttributeValueAsAddress(
2709       &OrigUnit, dwarf::DW_AT_low_pc, -1ULL);
2710   // Ranges addresses are based on the unit's low_pc. Compute the
2711   // offset we need to apply to adapt to the the new unit's low_pc.
2712   int64_t UnitPcOffset = 0;
2713   if (OrigLowPc != -1ULL)
2714     UnitPcOffset = int64_t(OrigLowPc) - Unit.getLowPc();
2715
2716   for (const auto &RangeAttribute : Unit.getRangesAttributes()) {
2717     uint32_t Offset = RangeAttribute.get();
2718     RangeAttribute.set(Streamer->getRangesSectionSize());
2719     RangeList.extract(RangeExtractor, &Offset);
2720     const auto &Entries = RangeList.getEntries();
2721     const DWARFDebugRangeList::RangeListEntry &First = Entries.front();
2722
2723     if (CurrRange == InvalidRange || First.StartAddress < CurrRange.start() ||
2724         First.StartAddress >= CurrRange.stop()) {
2725       CurrRange = FunctionRanges.find(First.StartAddress + OrigLowPc);
2726       if (CurrRange == InvalidRange ||
2727           CurrRange.start() > First.StartAddress + OrigLowPc) {
2728         reportWarning("no mapping for range.");
2729         continue;
2730       }
2731     }
2732
2733     Streamer->emitRangesEntries(UnitPcOffset, OrigLowPc, CurrRange, Entries,
2734                                 AddressSize);
2735   }
2736 }
2737
2738 /// \brief Generate the debug_aranges entries for \p Unit and if the
2739 /// unit has a DW_AT_ranges attribute, also emit the debug_ranges
2740 /// contribution for this attribute.
2741 /// FIXME: this could actually be done right in patchRangesForUnit,
2742 /// but for the sake of initial bit-for-bit compatibility with legacy
2743 /// dsymutil, we have to do it in a delayed pass.
2744 void DwarfLinker::generateUnitRanges(CompileUnit &Unit) const {
2745   auto Attr = Unit.getUnitRangesAttribute();
2746   if (Attr)
2747     Attr->set(Streamer->getRangesSectionSize());
2748   Streamer->emitUnitRangesEntries(Unit, static_cast<bool>(Attr));
2749 }
2750
2751 /// \brief Insert the new line info sequence \p Seq into the current
2752 /// set of already linked line info \p Rows.
2753 static void insertLineSequence(std::vector<DWARFDebugLine::Row> &Seq,
2754                                std::vector<DWARFDebugLine::Row> &Rows) {
2755   if (Seq.empty())
2756     return;
2757
2758   if (!Rows.empty() && Rows.back().Address < Seq.front().Address) {
2759     Rows.insert(Rows.end(), Seq.begin(), Seq.end());
2760     Seq.clear();
2761     return;
2762   }
2763
2764   auto InsertPoint = std::lower_bound(
2765       Rows.begin(), Rows.end(), Seq.front(),
2766       [](const DWARFDebugLine::Row &LHS, const DWARFDebugLine::Row &RHS) {
2767         return LHS.Address < RHS.Address;
2768       });
2769
2770   // FIXME: this only removes the unneeded end_sequence if the
2771   // sequences have been inserted in order. using a global sort like
2772   // described in patchLineTableForUnit() and delaying the end_sequene
2773   // elimination to emitLineTableForUnit() we can get rid of all of them.
2774   if (InsertPoint != Rows.end() &&
2775       InsertPoint->Address == Seq.front().Address && InsertPoint->EndSequence) {
2776     *InsertPoint = Seq.front();
2777     Rows.insert(InsertPoint + 1, Seq.begin() + 1, Seq.end());
2778   } else {
2779     Rows.insert(InsertPoint, Seq.begin(), Seq.end());
2780   }
2781
2782   Seq.clear();
2783 }
2784
2785 static void patchStmtList(DIE &Die, DIEInteger Offset) {
2786   for (auto &V : Die.values())
2787     if (V.getAttribute() == dwarf::DW_AT_stmt_list) {
2788       V = DIEValue(V.getAttribute(), V.getForm(), Offset);
2789       return;
2790     }
2791
2792   llvm_unreachable("Didn't find DW_AT_stmt_list in cloned DIE!");
2793 }
2794
2795 /// \brief Extract the line table for \p Unit from \p OrigDwarf, and
2796 /// recreate a relocated version of these for the address ranges that
2797 /// are present in the binary.
2798 void DwarfLinker::patchLineTableForUnit(CompileUnit &Unit,
2799                                         DWARFContext &OrigDwarf) {
2800   const DWARFDebugInfoEntryMinimal *CUDie = Unit.getOrigUnit().getUnitDIE();
2801   uint64_t StmtList = CUDie->getAttributeValueAsSectionOffset(
2802       &Unit.getOrigUnit(), dwarf::DW_AT_stmt_list, -1ULL);
2803   if (StmtList == -1ULL)
2804     return;
2805
2806   // Update the cloned DW_AT_stmt_list with the correct debug_line offset.
2807   if (auto *OutputDIE = Unit.getOutputUnitDIE())
2808     patchStmtList(*OutputDIE, DIEInteger(Streamer->getLineSectionSize()));
2809
2810   // Parse the original line info for the unit.
2811   DWARFDebugLine::LineTable LineTable;
2812   uint32_t StmtOffset = StmtList;
2813   StringRef LineData = OrigDwarf.getLineSection().Data;
2814   DataExtractor LineExtractor(LineData, OrigDwarf.isLittleEndian(),
2815                               Unit.getOrigUnit().getAddressByteSize());
2816   LineTable.parse(LineExtractor, &OrigDwarf.getLineSection().Relocs,
2817                   &StmtOffset);
2818
2819   // This vector is the output line table.
2820   std::vector<DWARFDebugLine::Row> NewRows;
2821   NewRows.reserve(LineTable.Rows.size());
2822
2823   // Current sequence of rows being extracted, before being inserted
2824   // in NewRows.
2825   std::vector<DWARFDebugLine::Row> Seq;
2826   const auto &FunctionRanges = Unit.getFunctionRanges();
2827   auto InvalidRange = FunctionRanges.end(), CurrRange = InvalidRange;
2828
2829   // FIXME: This logic is meant to generate exactly the same output as
2830   // Darwin's classic dsynutil. There is a nicer way to implement this
2831   // by simply putting all the relocated line info in NewRows and simply
2832   // sorting NewRows before passing it to emitLineTableForUnit. This
2833   // should be correct as sequences for a function should stay
2834   // together in the sorted output. There are a few corner cases that
2835   // look suspicious though, and that required to implement the logic
2836   // this way. Revisit that once initial validation is finished.
2837
2838   // Iterate over the object file line info and extract the sequences
2839   // that correspond to linked functions.
2840   for (auto &Row : LineTable.Rows) {
2841     // Check wether we stepped out of the range. The range is
2842     // half-open, but consider accept the end address of the range if
2843     // it is marked as end_sequence in the input (because in that
2844     // case, the relocation offset is accurate and that entry won't
2845     // serve as the start of another function).
2846     if (CurrRange == InvalidRange || Row.Address < CurrRange.start() ||
2847         Row.Address > CurrRange.stop() ||
2848         (Row.Address == CurrRange.stop() && !Row.EndSequence)) {
2849       // We just stepped out of a known range. Insert a end_sequence
2850       // corresponding to the end of the range.
2851       uint64_t StopAddress = CurrRange != InvalidRange
2852                                  ? CurrRange.stop() + CurrRange.value()
2853                                  : -1ULL;
2854       CurrRange = FunctionRanges.find(Row.Address);
2855       bool CurrRangeValid =
2856           CurrRange != InvalidRange && CurrRange.start() <= Row.Address;
2857       if (!CurrRangeValid) {
2858         CurrRange = InvalidRange;
2859         if (StopAddress != -1ULL) {
2860           // Try harder by looking in the DebugMapObject function
2861           // ranges map. There are corner cases where this finds a
2862           // valid entry. It's unclear if this is right or wrong, but
2863           // for now do as dsymutil.
2864           // FIXME: Understand exactly what cases this addresses and
2865           // potentially remove it along with the Ranges map.
2866           auto Range = Ranges.lower_bound(Row.Address);
2867           if (Range != Ranges.begin() && Range != Ranges.end())
2868             --Range;
2869
2870           if (Range != Ranges.end() && Range->first <= Row.Address &&
2871               Range->second.first >= Row.Address) {
2872             StopAddress = Row.Address + Range->second.second;
2873           }
2874         }
2875       }
2876       if (StopAddress != -1ULL && !Seq.empty()) {
2877         // Insert end sequence row with the computed end address, but
2878         // the same line as the previous one.
2879         Seq.emplace_back(Seq.back());
2880         Seq.back().Address = StopAddress;
2881         Seq.back().EndSequence = 1;
2882         Seq.back().PrologueEnd = 0;
2883         Seq.back().BasicBlock = 0;
2884         Seq.back().EpilogueBegin = 0;
2885         insertLineSequence(Seq, NewRows);
2886       }
2887
2888       if (!CurrRangeValid)
2889         continue;
2890     }
2891
2892     // Ignore empty sequences.
2893     if (Row.EndSequence && Seq.empty())
2894       continue;
2895
2896     // Relocate row address and add it to the current sequence.
2897     Row.Address += CurrRange.value();
2898     Seq.emplace_back(Row);
2899
2900     if (Row.EndSequence)
2901       insertLineSequence(Seq, NewRows);
2902   }
2903
2904   // Finished extracting, now emit the line tables.
2905   uint32_t PrologueEnd = StmtList + 10 + LineTable.Prologue.PrologueLength;
2906   // FIXME: LLVM hardcodes it's prologue values. We just copy the
2907   // prologue over and that works because we act as both producer and
2908   // consumer. It would be nicer to have a real configurable line
2909   // table emitter.
2910   if (LineTable.Prologue.Version != 2 ||
2911       LineTable.Prologue.DefaultIsStmt != DWARF2_LINE_DEFAULT_IS_STMT ||
2912       LineTable.Prologue.LineBase != -5 || LineTable.Prologue.LineRange != 14 ||
2913       LineTable.Prologue.OpcodeBase != 13)
2914     reportWarning("line table paramters mismatch. Cannot emit.");
2915   else
2916     Streamer->emitLineTableForUnit(LineData.slice(StmtList + 4, PrologueEnd),
2917                                    LineTable.Prologue.MinInstLength, NewRows,
2918                                    Unit.getOrigUnit().getAddressByteSize());
2919 }
2920
2921 void DwarfLinker::emitAcceleratorEntriesForUnit(CompileUnit &Unit) {
2922   Streamer->emitPubNamesForUnit(Unit);
2923   Streamer->emitPubTypesForUnit(Unit);
2924 }
2925
2926 /// \brief Read the frame info stored in the object, and emit the
2927 /// patched frame descriptions for the linked binary.
2928 ///
2929 /// This is actually pretty easy as the data of the CIEs and FDEs can
2930 /// be considered as black boxes and moved as is. The only thing to do
2931 /// is to patch the addresses in the headers.
2932 void DwarfLinker::patchFrameInfoForObject(const DebugMapObject &DMO,
2933                                           DWARFContext &OrigDwarf,
2934                                           unsigned AddrSize) {
2935   StringRef FrameData = OrigDwarf.getDebugFrameSection();
2936   if (FrameData.empty())
2937     return;
2938
2939   DataExtractor Data(FrameData, OrigDwarf.isLittleEndian(), 0);
2940   uint32_t InputOffset = 0;
2941
2942   // Store the data of the CIEs defined in this object, keyed by their
2943   // offsets.
2944   DenseMap<uint32_t, StringRef> LocalCIES;
2945
2946   while (Data.isValidOffset(InputOffset)) {
2947     uint32_t EntryOffset = InputOffset;
2948     uint32_t InitialLength = Data.getU32(&InputOffset);
2949     if (InitialLength == 0xFFFFFFFF)
2950       return reportWarning("Dwarf64 bits no supported");
2951
2952     uint32_t CIEId = Data.getU32(&InputOffset);
2953     if (CIEId == 0xFFFFFFFF) {
2954       // This is a CIE, store it.
2955       StringRef CIEData = FrameData.substr(EntryOffset, InitialLength + 4);
2956       LocalCIES[EntryOffset] = CIEData;
2957       // The -4 is to account for the CIEId we just read.
2958       InputOffset += InitialLength - 4;
2959       continue;
2960     }
2961
2962     uint32_t Loc = Data.getUnsigned(&InputOffset, AddrSize);
2963
2964     // Some compilers seem to emit frame info that doesn't start at
2965     // the function entry point, thus we can't just lookup the address
2966     // in the debug map. Use the linker's range map to see if the FDE
2967     // describes something that we can relocate.
2968     auto Range = Ranges.upper_bound(Loc);
2969     if (Range != Ranges.begin())
2970       --Range;
2971     if (Range == Ranges.end() || Range->first > Loc ||
2972         Range->second.first <= Loc) {
2973       // The +4 is to account for the size of the InitialLength field itself.
2974       InputOffset = EntryOffset + InitialLength + 4;
2975       continue;
2976     }
2977
2978     // This is an FDE, and we have a mapping.
2979     // Have we already emitted a corresponding CIE?
2980     StringRef CIEData = LocalCIES[CIEId];
2981     if (CIEData.empty())
2982       return reportWarning("Inconsistent debug_frame content. Dropping.");
2983
2984     // Look if we already emitted a CIE that corresponds to the
2985     // referenced one (the CIE data is the key of that lookup).
2986     auto IteratorInserted = EmittedCIEs.insert(
2987         std::make_pair(CIEData, Streamer->getFrameSectionSize()));
2988     // If there is no CIE yet for this ID, emit it.
2989     if (IteratorInserted.second ||
2990         // FIXME: dsymutil-classic only caches the last used CIE for
2991         // reuse. Mimic that behavior for now. Just removing that
2992         // second half of the condition and the LastCIEOffset variable
2993         // makes the code DTRT.
2994         LastCIEOffset != IteratorInserted.first->getValue()) {
2995       LastCIEOffset = Streamer->getFrameSectionSize();
2996       IteratorInserted.first->getValue() = LastCIEOffset;
2997       Streamer->emitCIE(CIEData);
2998     }
2999
3000     // Emit the FDE with updated address and CIE pointer.
3001     // (4 + AddrSize) is the size of the CIEId + initial_location
3002     // fields that will get reconstructed by emitFDE().
3003     unsigned FDERemainingBytes = InitialLength - (4 + AddrSize);
3004     Streamer->emitFDE(IteratorInserted.first->getValue(), AddrSize,
3005                       Loc + Range->second.second,
3006                       FrameData.substr(InputOffset, FDERemainingBytes));
3007     InputOffset += FDERemainingBytes;
3008   }
3009 }
3010
3011 bool DwarfLinker::link(const DebugMap &Map) {
3012
3013   if (Map.begin() == Map.end()) {
3014     errs() << "Empty debug map.\n";
3015     return false;
3016   }
3017
3018   if (!createStreamer(Map.getTriple(), OutputFilename))
3019     return false;
3020
3021   // Size of the DIEs (and headers) generated for the linked output.
3022   uint64_t OutputDebugInfoSize = 0;
3023   // A unique ID that identifies each compile unit.
3024   unsigned UnitID = 0;
3025   for (const auto &Obj : Map.objects()) {
3026     CurrentDebugObject = Obj.get();
3027
3028     if (Options.Verbose)
3029       outs() << "DEBUG MAP OBJECT: " << Obj->getObjectFilename() << "\n";
3030     auto ErrOrObj = BinHolder.GetObjectFile(Obj->getObjectFilename());
3031     if (std::error_code EC = ErrOrObj.getError()) {
3032       reportWarning(Twine(Obj->getObjectFilename()) + ": " + EC.message());
3033       continue;
3034     }
3035
3036     // Look for relocations that correspond to debug map entries.
3037     if (!findValidRelocsInDebugInfo(*ErrOrObj, *Obj)) {
3038       if (Options.Verbose)
3039         outs() << "No valid relocations found. Skipping.\n";
3040       continue;
3041     }
3042
3043     // Setup access to the debug info.
3044     DWARFContextInMemory DwarfContext(*ErrOrObj);
3045     startDebugObject(DwarfContext, *Obj);
3046
3047     // In a first phase, just read in the debug info and store the DIE
3048     // parent links that we will use during the next phase.
3049     for (const auto &CU : DwarfContext.compile_units()) {
3050       auto *CUDie = CU->getUnitDIE(false);
3051       if (Options.Verbose) {
3052         outs() << "Input compilation unit:";
3053         CUDie->dump(outs(), CU.get(), 0);
3054       }
3055       Units.emplace_back(*CU, UnitID++, !Options.NoODR);
3056       gatherDIEParents(CUDie, 0, Units.back(), &ODRContexts.getRoot(),
3057                        StringPool, ODRContexts);
3058     }
3059
3060     // Then mark all the DIEs that need to be present in the linked
3061     // output and collect some information about them. Note that this
3062     // loop can not be merged with the previous one becaue cross-cu
3063     // references require the ParentIdx to be setup for every CU in
3064     // the object file before calling this.
3065     for (auto &CurrentUnit : Units)
3066       lookForDIEsToKeep(*CurrentUnit.getOrigUnit().getUnitDIE(), *Obj,
3067                         CurrentUnit, 0);
3068
3069     // The calls to applyValidRelocs inside cloneDIE will walk the
3070     // reloc array again (in the same way findValidRelocsInDebugInfo()
3071     // did). We need to reset the NextValidReloc index to the beginning.
3072     NextValidReloc = 0;
3073
3074     // Construct the output DIE tree by cloning the DIEs we chose to
3075     // keep above. If there are no valid relocs, then there's nothing
3076     // to clone/emit.
3077     if (!ValidRelocs.empty())
3078       for (auto &CurrentUnit : Units) {
3079         const auto *InputDIE = CurrentUnit.getOrigUnit().getUnitDIE();
3080         CurrentUnit.setStartOffset(OutputDebugInfoSize);
3081         DIE *OutputDIE = cloneDIE(*InputDIE, CurrentUnit, 0 /* PCOffset */,
3082                                   11 /* Unit Header size */);
3083         CurrentUnit.setOutputUnitDIE(OutputDIE);
3084         OutputDebugInfoSize = CurrentUnit.computeNextUnitOffset();
3085         if (Options.NoOutput)
3086           continue;
3087         // FIXME: for compatibility with the classic dsymutil, we emit
3088         // an empty line table for the unit, even if the unit doesn't
3089         // actually exist in the DIE tree.
3090         patchLineTableForUnit(CurrentUnit, DwarfContext);
3091         if (!OutputDIE)
3092           continue;
3093         patchRangesForUnit(CurrentUnit, DwarfContext);
3094         Streamer->emitLocationsForUnit(CurrentUnit, DwarfContext);
3095         emitAcceleratorEntriesForUnit(CurrentUnit);
3096       }
3097
3098     // Emit all the compile unit's debug information.
3099     if (!ValidRelocs.empty() && !Options.NoOutput)
3100       for (auto &CurrentUnit : Units) {
3101         generateUnitRanges(CurrentUnit);
3102         CurrentUnit.fixupForwardReferences();
3103         Streamer->emitCompileUnitHeader(CurrentUnit);
3104         if (!CurrentUnit.getOutputUnitDIE())
3105           continue;
3106         Streamer->emitDIE(*CurrentUnit.getOutputUnitDIE());
3107       }
3108
3109     if (!ValidRelocs.empty() && !Options.NoOutput && !Units.empty())
3110       patchFrameInfoForObject(*Obj, DwarfContext,
3111                               Units[0].getOrigUnit().getAddressByteSize());
3112
3113     // Clean-up before starting working on the next object.
3114     endDebugObject();
3115   }
3116
3117   // Emit everything that's global.
3118   if (!Options.NoOutput) {
3119     Streamer->emitAbbrevs(Abbreviations);
3120     Streamer->emitStrings(StringPool);
3121   }
3122
3123   return Options.NoOutput ? true : Streamer->finish();
3124 }
3125 }
3126
3127 bool linkDwarf(StringRef OutputFilename, const DebugMap &DM,
3128                const LinkOptions &Options) {
3129   DwarfLinker Linker(OutputFilename, Options);
3130   return Linker.link(DM);
3131 }
3132 }
3133 }