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