Home | History | Annotate | Download | only in dsymutil
      1 //===- tools/dsymutil/DwarfStreamer.cpp - Dwarf Streamer ------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include "DwarfStreamer.h"
     11 #include "CompileUnit.h"
     12 #include "LinkUtils.h"
     13 #include "MachOUtils.h"
     14 #include "llvm/ADT/Triple.h"
     15 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
     16 #include "llvm/MC/MCTargetOptions.h"
     17 #include "llvm/MC/MCTargetOptionsCommandFlags.inc"
     18 #include "llvm/Support/LEB128.h"
     19 #include "llvm/Support/TargetRegistry.h"
     20 #include "llvm/Target/TargetMachine.h"
     21 #include "llvm/Target/TargetOptions.h"
     22 
     23 namespace llvm {
     24 namespace dsymutil {
     25 
     26 /// Retrieve the section named \a SecName in \a Obj.
     27 ///
     28 /// To accommodate for platform discrepancies, the name passed should be
     29 /// (for example) 'debug_info' to match either '__debug_info' or '.debug_info'.
     30 /// This function will strip the initial platform-specific characters.
     31 static Optional<object::SectionRef>
     32 getSectionByName(const object::ObjectFile &Obj, StringRef SecName) {
     33   for (const object::SectionRef &Section : Obj.sections()) {
     34     StringRef SectionName;
     35     Section.getName(SectionName);
     36     SectionName = SectionName.substr(SectionName.find_first_not_of("._"));
     37     if (SectionName != SecName)
     38       continue;
     39     return Section;
     40   }
     41   return None;
     42 }
     43 
     44 bool DwarfStreamer::init(Triple TheTriple) {
     45   std::string ErrorStr;
     46   std::string TripleName;
     47   StringRef Context = "dwarf streamer init";
     48 
     49   // Get the target.
     50   const Target *TheTarget =
     51       TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
     52   if (!TheTarget)
     53     return error(ErrorStr, Context);
     54   TripleName = TheTriple.getTriple();
     55 
     56   // Create all the MC Objects.
     57   MRI.reset(TheTarget->createMCRegInfo(TripleName));
     58   if (!MRI)
     59     return error(Twine("no register info for target ") + TripleName, Context);
     60 
     61   MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
     62   if (!MAI)
     63     return error("no asm info for target " + TripleName, Context);
     64 
     65   MOFI.reset(new MCObjectFileInfo);
     66   MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
     67   MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, *MC);
     68 
     69   MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
     70   if (!MSTI)
     71     return error("no subtarget info for target " + TripleName, Context);
     72 
     73   MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
     74   MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
     75   if (!MAB)
     76     return error("no asm backend for target " + TripleName, Context);
     77 
     78   MII.reset(TheTarget->createMCInstrInfo());
     79   if (!MII)
     80     return error("no instr info info for target " + TripleName, Context);
     81 
     82   MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
     83   if (!MCE)
     84     return error("no code emitter for target " + TripleName, Context);
     85 
     86   switch (Options.FileType) {
     87   case OutputFileType::Assembly: {
     88     MIP = TheTarget->createMCInstPrinter(TheTriple, MAI->getAssemblerDialect(),
     89                                          *MAI, *MII, *MRI);
     90     MS = TheTarget->createAsmStreamer(
     91         *MC, llvm::make_unique<formatted_raw_ostream>(OutFile), true, true, MIP,
     92         std::unique_ptr<MCCodeEmitter>(MCE), std::unique_ptr<MCAsmBackend>(MAB),
     93         true);
     94     break;
     95   }
     96   case OutputFileType::Object: {
     97     MS = TheTarget->createMCObjectStreamer(
     98         TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB),
     99         MAB->createObjectWriter(OutFile), std::unique_ptr<MCCodeEmitter>(MCE),
    100         *MSTI, MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
    101         /*DWARFMustBeAtTheEnd*/ false);
    102     break;
    103   }
    104   }
    105 
    106   if (!MS)
    107     return error("no object streamer for target " + TripleName, Context);
    108 
    109   // Finally create the AsmPrinter we'll use to emit the DIEs.
    110   TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
    111                                           None));
    112   if (!TM)
    113     return error("no target machine for target " + TripleName, Context);
    114 
    115   Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
    116   if (!Asm)
    117     return error("no asm printer for target " + TripleName, Context);
    118 
    119   RangesSectionSize = 0;
    120   LocSectionSize = 0;
    121   LineSectionSize = 0;
    122   FrameSectionSize = 0;
    123 
    124   return true;
    125 }
    126 
    127 bool DwarfStreamer::finish(const DebugMap &DM) {
    128   bool Result = true;
    129   if (DM.getTriple().isOSDarwin() && !DM.getBinaryPath().empty() &&
    130       Options.FileType == OutputFileType::Object)
    131     Result = MachOUtils::generateDsymCompanion(DM, *MS, OutFile);
    132   else
    133     MS->Finish();
    134   return Result;
    135 }
    136 
    137 void DwarfStreamer::switchToDebugInfoSection(unsigned DwarfVersion) {
    138   MS->SwitchSection(MOFI->getDwarfInfoSection());
    139   MC->setDwarfVersion(DwarfVersion);
    140 }
    141 
    142 /// Emit the compilation unit header for \p Unit in the debug_info section.
    143 ///
    144 /// A Dwarf section header is encoded as:
    145 ///  uint32_t   Unit length (omitting this field)
    146 ///  uint16_t   Version
    147 ///  uint32_t   Abbreviation table offset
    148 ///  uint8_t    Address size
    149 ///
    150 /// Leading to a total of 11 bytes.
    151 void DwarfStreamer::emitCompileUnitHeader(CompileUnit &Unit) {
    152   unsigned Version = Unit.getOrigUnit().getVersion();
    153   switchToDebugInfoSection(Version);
    154 
    155   /// The start of the unit within its section.
    156   Unit.setLabelBegin(Asm->createTempSymbol("cu_begin"));
    157   Asm->OutStreamer->EmitLabel(Unit.getLabelBegin());
    158 
    159   // Emit size of content not including length itself. The size has already
    160   // been computed in CompileUnit::computeOffsets(). Subtract 4 to that size to
    161   // account for the length field.
    162   Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset() - 4);
    163   Asm->emitInt16(Version);
    164 
    165   // We share one abbreviations table across all units so it's always at the
    166   // start of the section.
    167   Asm->emitInt32(0);
    168   Asm->emitInt8(Unit.getOrigUnit().getAddressByteSize());
    169 
    170   // Remember this CU.
    171   EmittedUnits.push_back({Unit.getUniqueID(), Unit.getLabelBegin()});
    172 }
    173 
    174 /// Emit the \p Abbrevs array as the shared abbreviation table
    175 /// for the linked Dwarf file.
    176 void DwarfStreamer::emitAbbrevs(
    177     const std::vector<std::unique_ptr<DIEAbbrev>> &Abbrevs,
    178     unsigned DwarfVersion) {
    179   MS->SwitchSection(MOFI->getDwarfAbbrevSection());
    180   MC->setDwarfVersion(DwarfVersion);
    181   Asm->emitDwarfAbbrevs(Abbrevs);
    182 }
    183 
    184 /// Recursively emit the DIE tree rooted at \p Die.
    185 void DwarfStreamer::emitDIE(DIE &Die) {
    186   MS->SwitchSection(MOFI->getDwarfInfoSection());
    187   Asm->emitDwarfDIE(Die);
    188 }
    189 
    190 /// Emit the debug_str section stored in \p Pool.
    191 void DwarfStreamer::emitStrings(const NonRelocatableStringpool &Pool) {
    192   Asm->OutStreamer->SwitchSection(MOFI->getDwarfStrSection());
    193   std::vector<DwarfStringPoolEntryRef> Entries = Pool.getEntries();
    194   for (auto Entry : Entries) {
    195     if (Entry.getIndex() == -1U)
    196       break;
    197     // Emit the string itself.
    198     Asm->OutStreamer->EmitBytes(Entry.getString());
    199     // Emit a null terminator.
    200     Asm->emitInt8(0);
    201   }
    202 }
    203 
    204 void DwarfStreamer::emitDebugNames(
    205     AccelTable<DWARF5AccelTableStaticData> &Table) {
    206   if (EmittedUnits.empty())
    207     return;
    208 
    209   // Build up data structures needed to emit this section.
    210   std::vector<MCSymbol *> CompUnits;
    211   DenseMap<unsigned, size_t> UniqueIdToCuMap;
    212   unsigned Id = 0;
    213   for (auto &CU : EmittedUnits) {
    214     CompUnits.push_back(CU.LabelBegin);
    215     // We might be omitting CUs, so we need to remap them.
    216     UniqueIdToCuMap[CU.ID] = Id++;
    217   }
    218 
    219   Asm->OutStreamer->SwitchSection(MOFI->getDwarfDebugNamesSection());
    220   emitDWARF5AccelTable(
    221       Asm.get(), Table, CompUnits,
    222       [&UniqueIdToCuMap](const DWARF5AccelTableStaticData &Entry) {
    223         return UniqueIdToCuMap[Entry.getCUIndex()];
    224       });
    225 }
    226 
    227 void DwarfStreamer::emitAppleNamespaces(
    228     AccelTable<AppleAccelTableStaticOffsetData> &Table) {
    229   Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamespaceSection());
    230   auto *SectionBegin = Asm->createTempSymbol("namespac_begin");
    231   Asm->OutStreamer->EmitLabel(SectionBegin);
    232   emitAppleAccelTable(Asm.get(), Table, "namespac", SectionBegin);
    233 }
    234 
    235 void DwarfStreamer::emitAppleNames(
    236     AccelTable<AppleAccelTableStaticOffsetData> &Table) {
    237   Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelNamesSection());
    238   auto *SectionBegin = Asm->createTempSymbol("names_begin");
    239   Asm->OutStreamer->EmitLabel(SectionBegin);
    240   emitAppleAccelTable(Asm.get(), Table, "names", SectionBegin);
    241 }
    242 
    243 void DwarfStreamer::emitAppleObjc(
    244     AccelTable<AppleAccelTableStaticOffsetData> &Table) {
    245   Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelObjCSection());
    246   auto *SectionBegin = Asm->createTempSymbol("objc_begin");
    247   Asm->OutStreamer->EmitLabel(SectionBegin);
    248   emitAppleAccelTable(Asm.get(), Table, "objc", SectionBegin);
    249 }
    250 
    251 void DwarfStreamer::emitAppleTypes(
    252     AccelTable<AppleAccelTableStaticTypeData> &Table) {
    253   Asm->OutStreamer->SwitchSection(MOFI->getDwarfAccelTypesSection());
    254   auto *SectionBegin = Asm->createTempSymbol("types_begin");
    255   Asm->OutStreamer->EmitLabel(SectionBegin);
    256   emitAppleAccelTable(Asm.get(), Table, "types", SectionBegin);
    257 }
    258 
    259 /// Emit the swift_ast section stored in \p Buffers.
    260 void DwarfStreamer::emitSwiftAST(StringRef Buffer) {
    261   MCSection *SwiftASTSection = MOFI->getDwarfSwiftASTSection();
    262   SwiftASTSection->setAlignment(1 << 5);
    263   MS->SwitchSection(SwiftASTSection);
    264   MS->EmitBytes(Buffer);
    265 }
    266 
    267 /// Emit the debug_range section contents for \p FuncRange by
    268 /// translating the original \p Entries. The debug_range section
    269 /// format is totally trivial, consisting just of pairs of address
    270 /// sized addresses describing the ranges.
    271 void DwarfStreamer::emitRangesEntries(
    272     int64_t UnitPcOffset, uint64_t OrigLowPc,
    273     const FunctionIntervals::const_iterator &FuncRange,
    274     const std::vector<DWARFDebugRangeList::RangeListEntry> &Entries,
    275     unsigned AddressSize) {
    276   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
    277 
    278   // Offset each range by the right amount.
    279   int64_t PcOffset = Entries.empty() ? 0 : FuncRange.value() + UnitPcOffset;
    280   for (const auto &Range : Entries) {
    281     if (Range.isBaseAddressSelectionEntry(AddressSize)) {
    282       warn("unsupported base address selection operation",
    283            "emitting debug_ranges");
    284       break;
    285     }
    286     // Do not emit empty ranges.
    287     if (Range.StartAddress == Range.EndAddress)
    288       continue;
    289 
    290     // All range entries should lie in the function range.
    291     if (!(Range.StartAddress + OrigLowPc >= FuncRange.start() &&
    292           Range.EndAddress + OrigLowPc <= FuncRange.stop()))
    293       warn("inconsistent range data.", "emitting debug_ranges");
    294     MS->EmitIntValue(Range.StartAddress + PcOffset, AddressSize);
    295     MS->EmitIntValue(Range.EndAddress + PcOffset, AddressSize);
    296     RangesSectionSize += 2 * AddressSize;
    297   }
    298 
    299   // Add the terminator entry.
    300   MS->EmitIntValue(0, AddressSize);
    301   MS->EmitIntValue(0, AddressSize);
    302   RangesSectionSize += 2 * AddressSize;
    303 }
    304 
    305 /// Emit the debug_aranges contribution of a unit and
    306 /// if \p DoDebugRanges is true the debug_range contents for a
    307 /// compile_unit level DW_AT_ranges attribute (Which are basically the
    308 /// same thing with a different base address).
    309 /// Just aggregate all the ranges gathered inside that unit.
    310 void DwarfStreamer::emitUnitRangesEntries(CompileUnit &Unit,
    311                                           bool DoDebugRanges) {
    312   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
    313   // Gather the ranges in a vector, so that we can simplify them. The
    314   // IntervalMap will have coalesced the non-linked ranges, but here
    315   // we want to coalesce the linked addresses.
    316   std::vector<std::pair<uint64_t, uint64_t>> Ranges;
    317   const auto &FunctionRanges = Unit.getFunctionRanges();
    318   for (auto Range = FunctionRanges.begin(), End = FunctionRanges.end();
    319        Range != End; ++Range)
    320     Ranges.push_back(std::make_pair(Range.start() + Range.value(),
    321                                     Range.stop() + Range.value()));
    322 
    323   // The object addresses where sorted, but again, the linked
    324   // addresses might end up in a different order.
    325   llvm::sort(Ranges.begin(), Ranges.end());
    326 
    327   if (!Ranges.empty()) {
    328     MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
    329 
    330     MCSymbol *BeginLabel = Asm->createTempSymbol("Barange");
    331     MCSymbol *EndLabel = Asm->createTempSymbol("Earange");
    332 
    333     unsigned HeaderSize =
    334         sizeof(int32_t) + // Size of contents (w/o this field
    335         sizeof(int16_t) + // DWARF ARange version number
    336         sizeof(int32_t) + // Offset of CU in the .debug_info section
    337         sizeof(int8_t) +  // Pointer Size (in bytes)
    338         sizeof(int8_t);   // Segment Size (in bytes)
    339 
    340     unsigned TupleSize = AddressSize * 2;
    341     unsigned Padding = OffsetToAlignment(HeaderSize, TupleSize);
    342 
    343     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Arange length
    344     Asm->OutStreamer->EmitLabel(BeginLabel);
    345     Asm->emitInt16(dwarf::DW_ARANGES_VERSION); // Version number
    346     Asm->emitInt32(Unit.getStartOffset());     // Corresponding unit's offset
    347     Asm->emitInt8(AddressSize);                // Address size
    348     Asm->emitInt8(0);                          // Segment size
    349 
    350     Asm->OutStreamer->emitFill(Padding, 0x0);
    351 
    352     for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End;
    353          ++Range) {
    354       uint64_t RangeStart = Range->first;
    355       MS->EmitIntValue(RangeStart, AddressSize);
    356       while ((Range + 1) != End && Range->second == (Range + 1)->first)
    357         ++Range;
    358       MS->EmitIntValue(Range->second - RangeStart, AddressSize);
    359     }
    360 
    361     // Emit terminator
    362     Asm->OutStreamer->EmitIntValue(0, AddressSize);
    363     Asm->OutStreamer->EmitIntValue(0, AddressSize);
    364     Asm->OutStreamer->EmitLabel(EndLabel);
    365   }
    366 
    367   if (!DoDebugRanges)
    368     return;
    369 
    370   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
    371   // Offset each range by the right amount.
    372   int64_t PcOffset = -Unit.getLowPc();
    373   // Emit coalesced ranges.
    374   for (auto Range = Ranges.begin(), End = Ranges.end(); Range != End; ++Range) {
    375     MS->EmitIntValue(Range->first + PcOffset, AddressSize);
    376     while (Range + 1 != End && Range->second == (Range + 1)->first)
    377       ++Range;
    378     MS->EmitIntValue(Range->second + PcOffset, AddressSize);
    379     RangesSectionSize += 2 * AddressSize;
    380   }
    381 
    382   // Add the terminator entry.
    383   MS->EmitIntValue(0, AddressSize);
    384   MS->EmitIntValue(0, AddressSize);
    385   RangesSectionSize += 2 * AddressSize;
    386 }
    387 
    388 /// Emit location lists for \p Unit and update attributes to point to the new
    389 /// entries.
    390 void DwarfStreamer::emitLocationsForUnit(const CompileUnit &Unit,
    391                                          DWARFContext &Dwarf) {
    392   const auto &Attributes = Unit.getLocationAttributes();
    393 
    394   if (Attributes.empty())
    395     return;
    396 
    397   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
    398 
    399   unsigned AddressSize = Unit.getOrigUnit().getAddressByteSize();
    400   const DWARFSection &InputSec = Dwarf.getDWARFObj().getLocSection();
    401   DataExtractor Data(InputSec.Data, Dwarf.isLittleEndian(), AddressSize);
    402   DWARFUnit &OrigUnit = Unit.getOrigUnit();
    403   auto OrigUnitDie = OrigUnit.getUnitDIE(false);
    404   int64_t UnitPcOffset = 0;
    405   if (auto OrigLowPc = dwarf::toAddress(OrigUnitDie.find(dwarf::DW_AT_low_pc)))
    406     UnitPcOffset = int64_t(*OrigLowPc) - Unit.getLowPc();
    407 
    408   for (const auto &Attr : Attributes) {
    409     uint32_t Offset = Attr.first.get();
    410     Attr.first.set(LocSectionSize);
    411     // This is the quantity to add to the old location address to get
    412     // the correct address for the new one.
    413     int64_t LocPcOffset = Attr.second + UnitPcOffset;
    414     while (Data.isValidOffset(Offset)) {
    415       uint64_t Low = Data.getUnsigned(&Offset, AddressSize);
    416       uint64_t High = Data.getUnsigned(&Offset, AddressSize);
    417       LocSectionSize += 2 * AddressSize;
    418       if (Low == 0 && High == 0) {
    419         Asm->OutStreamer->EmitIntValue(0, AddressSize);
    420         Asm->OutStreamer->EmitIntValue(0, AddressSize);
    421         break;
    422       }
    423       Asm->OutStreamer->EmitIntValue(Low + LocPcOffset, AddressSize);
    424       Asm->OutStreamer->EmitIntValue(High + LocPcOffset, AddressSize);
    425       uint64_t Length = Data.getU16(&Offset);
    426       Asm->OutStreamer->EmitIntValue(Length, 2);
    427       // Just copy the bytes over.
    428       Asm->OutStreamer->EmitBytes(
    429           StringRef(InputSec.Data.substr(Offset, Length)));
    430       Offset += Length;
    431       LocSectionSize += Length + 2;
    432     }
    433   }
    434 }
    435 
    436 void DwarfStreamer::emitLineTableForUnit(MCDwarfLineTableParams Params,
    437                                          StringRef PrologueBytes,
    438                                          unsigned MinInstLength,
    439                                          std::vector<DWARFDebugLine::Row> &Rows,
    440                                          unsigned PointerSize) {
    441   // Switch to the section where the table will be emitted into.
    442   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
    443   MCSymbol *LineStartSym = MC->createTempSymbol();
    444   MCSymbol *LineEndSym = MC->createTempSymbol();
    445 
    446   // The first 4 bytes is the total length of the information for this
    447   // compilation unit (not including these 4 bytes for the length).
    448   Asm->EmitLabelDifference(LineEndSym, LineStartSym, 4);
    449   Asm->OutStreamer->EmitLabel(LineStartSym);
    450   // Copy Prologue.
    451   MS->EmitBytes(PrologueBytes);
    452   LineSectionSize += PrologueBytes.size() + 4;
    453 
    454   SmallString<128> EncodingBuffer;
    455   raw_svector_ostream EncodingOS(EncodingBuffer);
    456 
    457   if (Rows.empty()) {
    458     // We only have the dummy entry, dsymutil emits an entry with a 0
    459     // address in that case.
    460     MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
    461                             EncodingOS);
    462     MS->EmitBytes(EncodingOS.str());
    463     LineSectionSize += EncodingBuffer.size();
    464     MS->EmitLabel(LineEndSym);
    465     return;
    466   }
    467 
    468   // Line table state machine fields
    469   unsigned FileNum = 1;
    470   unsigned LastLine = 1;
    471   unsigned Column = 0;
    472   unsigned IsStatement = 1;
    473   unsigned Isa = 0;
    474   uint64_t Address = -1ULL;
    475 
    476   unsigned RowsSinceLastSequence = 0;
    477 
    478   for (unsigned Idx = 0; Idx < Rows.size(); ++Idx) {
    479     auto &Row = Rows[Idx];
    480 
    481     int64_t AddressDelta;
    482     if (Address == -1ULL) {
    483       MS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
    484       MS->EmitULEB128IntValue(PointerSize + 1);
    485       MS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
    486       MS->EmitIntValue(Row.Address, PointerSize);
    487       LineSectionSize += 2 + PointerSize + getULEB128Size(PointerSize + 1);
    488       AddressDelta = 0;
    489     } else {
    490       AddressDelta = (Row.Address - Address) / MinInstLength;
    491     }
    492 
    493     // FIXME: code copied and transformed from MCDwarf.cpp::EmitDwarfLineTable.
    494     // We should find a way to share this code, but the current compatibility
    495     // requirement with classic dsymutil makes it hard. Revisit that once this
    496     // requirement is dropped.
    497 
    498     if (FileNum != Row.File) {
    499       FileNum = Row.File;
    500       MS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
    501       MS->EmitULEB128IntValue(FileNum);
    502       LineSectionSize += 1 + getULEB128Size(FileNum);
    503     }
    504     if (Column != Row.Column) {
    505       Column = Row.Column;
    506       MS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
    507       MS->EmitULEB128IntValue(Column);
    508       LineSectionSize += 1 + getULEB128Size(Column);
    509     }
    510 
    511     // FIXME: We should handle the discriminator here, but dsymutil doesn't
    512     // consider it, thus ignore it for now.
    513 
    514     if (Isa != Row.Isa) {
    515       Isa = Row.Isa;
    516       MS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
    517       MS->EmitULEB128IntValue(Isa);
    518       LineSectionSize += 1 + getULEB128Size(Isa);
    519     }
    520     if (IsStatement != Row.IsStmt) {
    521       IsStatement = Row.IsStmt;
    522       MS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
    523       LineSectionSize += 1;
    524     }
    525     if (Row.BasicBlock) {
    526       MS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
    527       LineSectionSize += 1;
    528     }
    529 
    530     if (Row.PrologueEnd) {
    531       MS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
    532       LineSectionSize += 1;
    533     }
    534 
    535     if (Row.EpilogueBegin) {
    536       MS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
    537       LineSectionSize += 1;
    538     }
    539 
    540     int64_t LineDelta = int64_t(Row.Line) - LastLine;
    541     if (!Row.EndSequence) {
    542       MCDwarfLineAddr::Encode(*MC, Params, LineDelta, AddressDelta, EncodingOS);
    543       MS->EmitBytes(EncodingOS.str());
    544       LineSectionSize += EncodingBuffer.size();
    545       EncodingBuffer.resize(0);
    546       Address = Row.Address;
    547       LastLine = Row.Line;
    548       RowsSinceLastSequence++;
    549     } else {
    550       if (LineDelta) {
    551         MS->EmitIntValue(dwarf::DW_LNS_advance_line, 1);
    552         MS->EmitSLEB128IntValue(LineDelta);
    553         LineSectionSize += 1 + getSLEB128Size(LineDelta);
    554       }
    555       if (AddressDelta) {
    556         MS->EmitIntValue(dwarf::DW_LNS_advance_pc, 1);
    557         MS->EmitULEB128IntValue(AddressDelta);
    558         LineSectionSize += 1 + getULEB128Size(AddressDelta);
    559       }
    560       MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(),
    561                               0, EncodingOS);
    562       MS->EmitBytes(EncodingOS.str());
    563       LineSectionSize += EncodingBuffer.size();
    564       EncodingBuffer.resize(0);
    565       Address = -1ULL;
    566       LastLine = FileNum = IsStatement = 1;
    567       RowsSinceLastSequence = Column = Isa = 0;
    568     }
    569   }
    570 
    571   if (RowsSinceLastSequence) {
    572     MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits<int64_t>::max(), 0,
    573                             EncodingOS);
    574     MS->EmitBytes(EncodingOS.str());
    575     LineSectionSize += EncodingBuffer.size();
    576     EncodingBuffer.resize(0);
    577   }
    578 
    579   MS->EmitLabel(LineEndSym);
    580 }
    581 
    582 static void emitSectionContents(const object::ObjectFile &Obj,
    583                                 StringRef SecName, MCStreamer *MS) {
    584   StringRef Contents;
    585   if (auto Sec = getSectionByName(Obj, SecName))
    586     if (!Sec->getContents(Contents))
    587       MS->EmitBytes(Contents);
    588 }
    589 
    590 void DwarfStreamer::copyInvariantDebugSection(const object::ObjectFile &Obj) {
    591   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLineSection());
    592   emitSectionContents(Obj, "debug_line", MS);
    593 
    594   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfLocSection());
    595   emitSectionContents(Obj, "debug_loc", MS);
    596 
    597   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfRangesSection());
    598   emitSectionContents(Obj, "debug_ranges", MS);
    599 
    600   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
    601   emitSectionContents(Obj, "debug_frame", MS);
    602 
    603   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfARangesSection());
    604   emitSectionContents(Obj, "debug_aranges", MS);
    605 }
    606 
    607 /// Emit the pubnames or pubtypes section contribution for \p
    608 /// Unit into \p Sec. The data is provided in \p Names.
    609 void DwarfStreamer::emitPubSectionForUnit(
    610     MCSection *Sec, StringRef SecName, const CompileUnit &Unit,
    611     const std::vector<CompileUnit::AccelInfo> &Names) {
    612   if (Names.empty())
    613     return;
    614 
    615   // Start the dwarf pubnames section.
    616   Asm->OutStreamer->SwitchSection(Sec);
    617   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + SecName + "_begin");
    618   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + SecName + "_end");
    619 
    620   bool HeaderEmitted = false;
    621   // Emit the pubnames for this compilation unit.
    622   for (const auto &Name : Names) {
    623     if (Name.SkipPubSection)
    624       continue;
    625 
    626     if (!HeaderEmitted) {
    627       // Emit the header.
    628       Asm->EmitLabelDifference(EndLabel, BeginLabel, 4); // Length
    629       Asm->OutStreamer->EmitLabel(BeginLabel);
    630       Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION); // Version
    631       Asm->emitInt32(Unit.getStartOffset());      // Unit offset
    632       Asm->emitInt32(Unit.getNextUnitOffset() - Unit.getStartOffset()); // Size
    633       HeaderEmitted = true;
    634     }
    635     Asm->emitInt32(Name.Die->getOffset());
    636 
    637     // Emit the string itself.
    638     Asm->OutStreamer->EmitBytes(Name.Name.getString());
    639     // Emit a null terminator.
    640     Asm->emitInt8(0);
    641   }
    642 
    643   if (!HeaderEmitted)
    644     return;
    645   Asm->emitInt32(0); // End marker.
    646   Asm->OutStreamer->EmitLabel(EndLabel);
    647 }
    648 
    649 /// Emit .debug_pubnames for \p Unit.
    650 void DwarfStreamer::emitPubNamesForUnit(const CompileUnit &Unit) {
    651   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubNamesSection(),
    652                         "names", Unit, Unit.getPubnames());
    653 }
    654 
    655 /// Emit .debug_pubtypes for \p Unit.
    656 void DwarfStreamer::emitPubTypesForUnit(const CompileUnit &Unit) {
    657   emitPubSectionForUnit(MC->getObjectFileInfo()->getDwarfPubTypesSection(),
    658                         "types", Unit, Unit.getPubtypes());
    659 }
    660 
    661 /// Emit a CIE into the debug_frame section.
    662 void DwarfStreamer::emitCIE(StringRef CIEBytes) {
    663   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
    664 
    665   MS->EmitBytes(CIEBytes);
    666   FrameSectionSize += CIEBytes.size();
    667 }
    668 
    669 /// Emit a FDE into the debug_frame section. \p FDEBytes
    670 /// contains the FDE data without the length, CIE offset and address
    671 /// which will be replaced with the parameter values.
    672 void DwarfStreamer::emitFDE(uint32_t CIEOffset, uint32_t AddrSize,
    673                             uint32_t Address, StringRef FDEBytes) {
    674   MS->SwitchSection(MC->getObjectFileInfo()->getDwarfFrameSection());
    675 
    676   MS->EmitIntValue(FDEBytes.size() + 4 + AddrSize, 4);
    677   MS->EmitIntValue(CIEOffset, 4);
    678   MS->EmitIntValue(Address, AddrSize);
    679   MS->EmitBytes(FDEBytes);
    680   FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
    681 }
    682 
    683 } // namespace dsymutil
    684 } // namespace llvm
    685