1 //===- lib/MC/MCDwarf.cpp - MCDwarf implementation ------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/MC/MCDwarf.h"
10 #include "llvm/ADT/ArrayRef.h"
11 #include "llvm/ADT/DenseMap.h"
12 #include "llvm/ADT/Hashing.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/BinaryFormat/Dwarf.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCObjectFileInfo.h"
25 #include "llvm/MC/MCObjectStreamer.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/Endian.h"
32 #include "llvm/Support/EndianStream.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/LEB128.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/Path.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <string>
42 #include <utility>
43 #include <vector>
44 
45 using namespace llvm;
46 
47 MCSymbol *mcdwarf::emitListsTableHeaderStart(MCStreamer &S) {
48   MCSymbol *Start = S.getContext().createTempSymbol("debug_list_header_start");
49   MCSymbol *End = S.getContext().createTempSymbol("debug_list_header_end");
50   auto DwarfFormat = S.getContext().getDwarfFormat();
51   if (DwarfFormat == dwarf::DWARF64) {
52     S.AddComment("DWARF64 mark");
53     S.emitInt32(dwarf::DW_LENGTH_DWARF64);
54   }
55   S.AddComment("Length");
56   S.emitAbsoluteSymbolDiff(End, Start,
57                            dwarf::getDwarfOffsetByteSize(DwarfFormat));
58   S.emitLabel(Start);
59   S.AddComment("Version");
60   S.emitInt16(S.getContext().getDwarfVersion());
61   S.AddComment("Address size");
62   S.emitInt8(S.getContext().getAsmInfo()->getCodePointerSize());
63   S.AddComment("Segment selector size");
64   S.emitInt8(0);
65   return End;
66 }
67 
68 static inline uint64_t ScaleAddrDelta(MCContext &Context, uint64_t AddrDelta) {
69   unsigned MinInsnLength = Context.getAsmInfo()->getMinInstAlignment();
70   if (MinInsnLength == 1)
71     return AddrDelta;
72   if (AddrDelta % MinInsnLength != 0) {
73     // TODO: report this error, but really only once.
74     ;
75   }
76   return AddrDelta / MinInsnLength;
77 }
78 
79 MCDwarfLineStr::MCDwarfLineStr(MCContext &Ctx) {
80   UseRelocs = Ctx.getAsmInfo()->doesDwarfUseRelocationsAcrossSections();
81   if (UseRelocs)
82     LineStrLabel =
83         Ctx.getObjectFileInfo()->getDwarfLineStrSection()->getBeginSymbol();
84 }
85 
86 //
87 // This is called when an instruction is assembled into the specified section
88 // and if there is information from the last .loc directive that has yet to have
89 // a line entry made for it is made.
90 //
91 void MCDwarfLineEntry::make(MCStreamer *MCOS, MCSection *Section) {
92   if (!MCOS->getContext().getDwarfLocSeen())
93     return;
94 
95   // Create a symbol at in the current section for use in the line entry.
96   MCSymbol *LineSym = MCOS->getContext().createTempSymbol();
97   // Set the value of the symbol to use for the MCDwarfLineEntry.
98   MCOS->emitLabel(LineSym);
99 
100   // Get the current .loc info saved in the context.
101   const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
102 
103   // Create a (local) line entry with the symbol and the current .loc info.
104   MCDwarfLineEntry LineEntry(LineSym, DwarfLoc);
105 
106   // clear DwarfLocSeen saying the current .loc info is now used.
107   MCOS->getContext().clearDwarfLocSeen();
108 
109   // Add the line entry to this section's entries.
110   MCOS->getContext()
111       .getMCDwarfLineTable(MCOS->getContext().getDwarfCompileUnitID())
112       .getMCLineSections()
113       .addLineEntry(LineEntry, Section);
114 }
115 
116 //
117 // This helper routine returns an expression of End - Start + IntVal .
118 //
119 static inline const MCExpr *makeEndMinusStartExpr(MCContext &Ctx,
120                                                   const MCSymbol &Start,
121                                                   const MCSymbol &End,
122                                                   int IntVal) {
123   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
124   const MCExpr *Res = MCSymbolRefExpr::create(&End, Variant, Ctx);
125   const MCExpr *RHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
126   const MCExpr *Res1 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res, RHS, Ctx);
127   const MCExpr *Res2 = MCConstantExpr::create(IntVal, Ctx);
128   const MCExpr *Res3 = MCBinaryExpr::create(MCBinaryExpr::Sub, Res1, Res2, Ctx);
129   return Res3;
130 }
131 
132 //
133 // This helper routine returns an expression of Start + IntVal .
134 //
135 static inline const MCExpr *
136 makeStartPlusIntExpr(MCContext &Ctx, const MCSymbol &Start, int IntVal) {
137   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
138   const MCExpr *LHS = MCSymbolRefExpr::create(&Start, Variant, Ctx);
139   const MCExpr *RHS = MCConstantExpr::create(IntVal, Ctx);
140   const MCExpr *Res = MCBinaryExpr::create(MCBinaryExpr::Add, LHS, RHS, Ctx);
141   return Res;
142 }
143 
144 void MCLineSection::addEndEntry(MCSymbol *EndLabel) {
145   auto *Sec = &EndLabel->getSection();
146   // The line table may be empty, which we should skip adding an end entry.
147   // There are two cases:
148   // (1) MCAsmStreamer - emitDwarfLocDirective emits a location directive in
149   //     place instead of adding a line entry if the target has
150   //     usesDwarfFileAndLocDirectives.
151   // (2) MCObjectStreamer - if a function has incomplete debug info where
152   //     instructions don't have DILocations, the line entries are missing.
153   auto I = MCLineDivisions.find(Sec);
154   if (I != MCLineDivisions.end()) {
155     auto &Entries = I->second;
156     auto EndEntry = Entries.back();
157     EndEntry.setEndLabel(EndLabel);
158     Entries.push_back(EndEntry);
159   }
160 }
161 
162 //
163 // This emits the Dwarf line table for the specified section from the entries
164 // in the LineSection.
165 //
166 void MCDwarfLineTable::emitOne(
167     MCStreamer *MCOS, MCSection *Section,
168     const MCLineSection::MCDwarfLineEntryCollection &LineEntries) {
169 
170   unsigned FileNum, LastLine, Column, Flags, Isa, Discriminator;
171   MCSymbol *LastLabel;
172   auto init = [&]() {
173     FileNum = 1;
174     LastLine = 1;
175     Column = 0;
176     Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
177     Isa = 0;
178     Discriminator = 0;
179     LastLabel = nullptr;
180   };
181   init();
182 
183   // Loop through each MCDwarfLineEntry and encode the dwarf line number table.
184   bool EndEntryEmitted = false;
185   for (const MCDwarfLineEntry &LineEntry : LineEntries) {
186     MCSymbol *Label = LineEntry.getLabel();
187     const MCAsmInfo *asmInfo = MCOS->getContext().getAsmInfo();
188     if (LineEntry.IsEndEntry) {
189       MCOS->emitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, Label,
190                                      asmInfo->getCodePointerSize());
191       init();
192       EndEntryEmitted = true;
193       continue;
194     }
195 
196     int64_t LineDelta = static_cast<int64_t>(LineEntry.getLine()) - LastLine;
197 
198     if (FileNum != LineEntry.getFileNum()) {
199       FileNum = LineEntry.getFileNum();
200       MCOS->emitInt8(dwarf::DW_LNS_set_file);
201       MCOS->emitULEB128IntValue(FileNum);
202     }
203     if (Column != LineEntry.getColumn()) {
204       Column = LineEntry.getColumn();
205       MCOS->emitInt8(dwarf::DW_LNS_set_column);
206       MCOS->emitULEB128IntValue(Column);
207     }
208     if (Discriminator != LineEntry.getDiscriminator() &&
209         MCOS->getContext().getDwarfVersion() >= 4) {
210       Discriminator = LineEntry.getDiscriminator();
211       unsigned Size = getULEB128Size(Discriminator);
212       MCOS->emitInt8(dwarf::DW_LNS_extended_op);
213       MCOS->emitULEB128IntValue(Size + 1);
214       MCOS->emitInt8(dwarf::DW_LNE_set_discriminator);
215       MCOS->emitULEB128IntValue(Discriminator);
216     }
217     if (Isa != LineEntry.getIsa()) {
218       Isa = LineEntry.getIsa();
219       MCOS->emitInt8(dwarf::DW_LNS_set_isa);
220       MCOS->emitULEB128IntValue(Isa);
221     }
222     if ((LineEntry.getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
223       Flags = LineEntry.getFlags();
224       MCOS->emitInt8(dwarf::DW_LNS_negate_stmt);
225     }
226     if (LineEntry.getFlags() & DWARF2_FLAG_BASIC_BLOCK)
227       MCOS->emitInt8(dwarf::DW_LNS_set_basic_block);
228     if (LineEntry.getFlags() & DWARF2_FLAG_PROLOGUE_END)
229       MCOS->emitInt8(dwarf::DW_LNS_set_prologue_end);
230     if (LineEntry.getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
231       MCOS->emitInt8(dwarf::DW_LNS_set_epilogue_begin);
232 
233     // At this point we want to emit/create the sequence to encode the delta in
234     // line numbers and the increment of the address from the previous Label
235     // and the current Label.
236     MCOS->emitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label,
237                                    asmInfo->getCodePointerSize());
238 
239     Discriminator = 0;
240     LastLine = LineEntry.getLine();
241     LastLabel = Label;
242   }
243 
244   // Generate DWARF line end entry.
245   // We do not need this for DwarfDebug that explicitly terminates the line
246   // table using ranges whenever CU or section changes. However, the MC path
247   // does not track ranges nor terminate the line table. In that case,
248   // conservatively use the section end symbol to end the line table.
249   if (!EndEntryEmitted)
250     MCOS->emitDwarfLineEndEntry(Section, LastLabel);
251 }
252 
253 //
254 // This emits the Dwarf file and the line tables.
255 //
256 void MCDwarfLineTable::emit(MCStreamer *MCOS, MCDwarfLineTableParams Params) {
257   MCContext &context = MCOS->getContext();
258 
259   auto &LineTables = context.getMCDwarfLineTables();
260 
261   // Bail out early so we don't switch to the debug_line section needlessly and
262   // in doing so create an unnecessary (if empty) section.
263   if (LineTables.empty())
264     return;
265 
266   // In a v5 non-split line table, put the strings in a separate section.
267   Optional<MCDwarfLineStr> LineStr;
268   if (context.getDwarfVersion() >= 5)
269     LineStr = MCDwarfLineStr(context);
270 
271   // Switch to the section where the table will be emitted into.
272   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfLineSection());
273 
274   // Handle the rest of the Compile Units.
275   for (const auto &CUIDTablePair : LineTables) {
276     CUIDTablePair.second.emitCU(MCOS, Params, LineStr);
277   }
278 
279   if (LineStr)
280     LineStr->emitSection(MCOS);
281 }
282 
283 void MCDwarfDwoLineTable::Emit(MCStreamer &MCOS, MCDwarfLineTableParams Params,
284                                MCSection *Section) const {
285   if (!HasSplitLineTable)
286     return;
287   Optional<MCDwarfLineStr> NoLineStr(None);
288   MCOS.SwitchSection(Section);
289   MCOS.emitLabel(Header.Emit(&MCOS, Params, None, NoLineStr).second);
290 }
291 
292 std::pair<MCSymbol *, MCSymbol *>
293 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
294                              Optional<MCDwarfLineStr> &LineStr) const {
295   static const char StandardOpcodeLengths[] = {
296       0, // length of DW_LNS_copy
297       1, // length of DW_LNS_advance_pc
298       1, // length of DW_LNS_advance_line
299       1, // length of DW_LNS_set_file
300       1, // length of DW_LNS_set_column
301       0, // length of DW_LNS_negate_stmt
302       0, // length of DW_LNS_set_basic_block
303       0, // length of DW_LNS_const_add_pc
304       1, // length of DW_LNS_fixed_advance_pc
305       0, // length of DW_LNS_set_prologue_end
306       0, // length of DW_LNS_set_epilogue_begin
307       1  // DW_LNS_set_isa
308   };
309   assert(array_lengthof(StandardOpcodeLengths) >=
310          (Params.DWARF2LineOpcodeBase - 1U));
311   return Emit(
312       MCOS, Params,
313       makeArrayRef(StandardOpcodeLengths, Params.DWARF2LineOpcodeBase - 1),
314       LineStr);
315 }
316 
317 static const MCExpr *forceExpAbs(MCStreamer &OS, const MCExpr* Expr) {
318   MCContext &Context = OS.getContext();
319   assert(!isa<MCSymbolRefExpr>(Expr));
320   if (Context.getAsmInfo()->hasAggressiveSymbolFolding())
321     return Expr;
322 
323   MCSymbol *ABS = Context.createTempSymbol();
324   OS.emitAssignment(ABS, Expr);
325   return MCSymbolRefExpr::create(ABS, Context);
326 }
327 
328 static void emitAbsValue(MCStreamer &OS, const MCExpr *Value, unsigned Size) {
329   const MCExpr *ABS = forceExpAbs(OS, Value);
330   OS.emitValue(ABS, Size);
331 }
332 
333 void MCDwarfLineStr::emitSection(MCStreamer *MCOS) {
334   // Switch to the .debug_line_str section.
335   MCOS->SwitchSection(
336       MCOS->getContext().getObjectFileInfo()->getDwarfLineStrSection());
337   // Emit the strings without perturbing the offsets we used.
338   LineStrings.finalizeInOrder();
339   SmallString<0> Data;
340   Data.resize(LineStrings.getSize());
341   LineStrings.write((uint8_t *)Data.data());
342   MCOS->emitBinaryData(Data.str());
343 }
344 
345 void MCDwarfLineStr::emitRef(MCStreamer *MCOS, StringRef Path) {
346   int RefSize =
347       dwarf::getDwarfOffsetByteSize(MCOS->getContext().getDwarfFormat());
348   size_t Offset = LineStrings.add(Path);
349   if (UseRelocs) {
350     MCContext &Ctx = MCOS->getContext();
351     MCOS->emitValue(makeStartPlusIntExpr(Ctx, *LineStrLabel, Offset), RefSize);
352   } else
353     MCOS->emitIntValue(Offset, RefSize);
354 }
355 
356 void MCDwarfLineTableHeader::emitV2FileDirTables(MCStreamer *MCOS) const {
357   // First the directory table.
358   for (auto &Dir : MCDwarfDirs) {
359     MCOS->emitBytes(Dir);                // The DirectoryName, and...
360     MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
361   }
362   MCOS->emitInt8(0); // Terminate the directory list.
363 
364   // Second the file table.
365   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
366     assert(!MCDwarfFiles[i].Name.empty());
367     MCOS->emitBytes(MCDwarfFiles[i].Name); // FileName and...
368     MCOS->emitBytes(StringRef("\0", 1));   // its null terminator.
369     MCOS->emitULEB128IntValue(MCDwarfFiles[i].DirIndex); // Directory number.
370     MCOS->emitInt8(0); // Last modification timestamp (always 0).
371     MCOS->emitInt8(0); // File size (always 0).
372   }
373   MCOS->emitInt8(0); // Terminate the file list.
374 }
375 
376 static void emitOneV5FileEntry(MCStreamer *MCOS, const MCDwarfFile &DwarfFile,
377                                bool EmitMD5, bool HasSource,
378                                Optional<MCDwarfLineStr> &LineStr) {
379   assert(!DwarfFile.Name.empty());
380   if (LineStr)
381     LineStr->emitRef(MCOS, DwarfFile.Name);
382   else {
383     MCOS->emitBytes(DwarfFile.Name);     // FileName and...
384     MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
385   }
386   MCOS->emitULEB128IntValue(DwarfFile.DirIndex); // Directory number.
387   if (EmitMD5) {
388     const MD5::MD5Result &Cksum = *DwarfFile.Checksum;
389     MCOS->emitBinaryData(
390         StringRef(reinterpret_cast<const char *>(Cksum.Bytes.data()),
391                   Cksum.Bytes.size()));
392   }
393   if (HasSource) {
394     if (LineStr)
395       LineStr->emitRef(MCOS, DwarfFile.Source.getValueOr(StringRef()));
396     else {
397       MCOS->emitBytes(
398           DwarfFile.Source.getValueOr(StringRef())); // Source and...
399       MCOS->emitBytes(StringRef("\0", 1));           // its null terminator.
400     }
401   }
402 }
403 
404 void MCDwarfLineTableHeader::emitV5FileDirTables(
405     MCStreamer *MCOS, Optional<MCDwarfLineStr> &LineStr) const {
406   // The directory format, which is just a list of the directory paths.  In a
407   // non-split object, these are references to .debug_line_str; in a split
408   // object, they are inline strings.
409   MCOS->emitInt8(1);
410   MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
411   MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
412                                     : dwarf::DW_FORM_string);
413   MCOS->emitULEB128IntValue(MCDwarfDirs.size() + 1);
414   // Try not to emit an empty compilation directory.
415   const StringRef CompDir = CompilationDir.empty()
416                                 ? MCOS->getContext().getCompilationDir()
417                                 : StringRef(CompilationDir);
418   if (LineStr) {
419     // Record path strings, emit references here.
420     LineStr->emitRef(MCOS, CompDir);
421     for (const auto &Dir : MCDwarfDirs)
422       LineStr->emitRef(MCOS, Dir);
423   } else {
424     // The list of directory paths.  Compilation directory comes first.
425     MCOS->emitBytes(CompDir);
426     MCOS->emitBytes(StringRef("\0", 1));
427     for (const auto &Dir : MCDwarfDirs) {
428       MCOS->emitBytes(Dir);                // The DirectoryName, and...
429       MCOS->emitBytes(StringRef("\0", 1)); // its null terminator.
430     }
431   }
432 
433   // The file format, which is the inline null-terminated filename and a
434   // directory index.  We don't track file size/timestamp so don't emit them
435   // in the v5 table.  Emit MD5 checksums and source if we have them.
436   uint64_t Entries = 2;
437   if (HasAllMD5)
438     Entries += 1;
439   if (HasSource)
440     Entries += 1;
441   MCOS->emitInt8(Entries);
442   MCOS->emitULEB128IntValue(dwarf::DW_LNCT_path);
443   MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
444                                     : dwarf::DW_FORM_string);
445   MCOS->emitULEB128IntValue(dwarf::DW_LNCT_directory_index);
446   MCOS->emitULEB128IntValue(dwarf::DW_FORM_udata);
447   if (HasAllMD5) {
448     MCOS->emitULEB128IntValue(dwarf::DW_LNCT_MD5);
449     MCOS->emitULEB128IntValue(dwarf::DW_FORM_data16);
450   }
451   if (HasSource) {
452     MCOS->emitULEB128IntValue(dwarf::DW_LNCT_LLVM_source);
453     MCOS->emitULEB128IntValue(LineStr ? dwarf::DW_FORM_line_strp
454                                       : dwarf::DW_FORM_string);
455   }
456   // Then the counted list of files. The root file is file #0, then emit the
457   // files as provide by .file directives.
458   // MCDwarfFiles has an unused element [0] so use size() not size()+1.
459   // But sometimes MCDwarfFiles is empty, in which case we still emit one file.
460   MCOS->emitULEB128IntValue(MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size());
461   // To accommodate assembler source written for DWARF v4 but trying to emit
462   // v5: If we didn't see a root file explicitly, replicate file #1.
463   assert((!RootFile.Name.empty() || MCDwarfFiles.size() >= 1) &&
464          "No root file and no .file directives");
465   emitOneV5FileEntry(MCOS, RootFile.Name.empty() ? MCDwarfFiles[1] : RootFile,
466                      HasAllMD5, HasSource, LineStr);
467   for (unsigned i = 1; i < MCDwarfFiles.size(); ++i)
468     emitOneV5FileEntry(MCOS, MCDwarfFiles[i], HasAllMD5, HasSource, LineStr);
469 }
470 
471 std::pair<MCSymbol *, MCSymbol *>
472 MCDwarfLineTableHeader::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
473                              ArrayRef<char> StandardOpcodeLengths,
474                              Optional<MCDwarfLineStr> &LineStr) const {
475   MCContext &context = MCOS->getContext();
476 
477   // Create a symbol at the beginning of the line table.
478   MCSymbol *LineStartSym = Label;
479   if (!LineStartSym)
480     LineStartSym = context.createTempSymbol();
481 
482   // Set the value of the symbol, as we are at the start of the line table.
483   MCOS->emitDwarfLineStartLabel(LineStartSym);
484 
485   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
486 
487   MCSymbol *LineEndSym = MCOS->emitDwarfUnitLength("debug_line", "unit length");
488 
489   // Next 2 bytes is the Version.
490   unsigned LineTableVersion = context.getDwarfVersion();
491   MCOS->emitInt16(LineTableVersion);
492 
493   // In v5, we get address info next.
494   if (LineTableVersion >= 5) {
495     MCOS->emitInt8(context.getAsmInfo()->getCodePointerSize());
496     MCOS->emitInt8(0); // Segment selector; same as EmitGenDwarfAranges.
497   }
498 
499   // Create symbols for the start/end of the prologue.
500   MCSymbol *ProStartSym = context.createTempSymbol("prologue_start");
501   MCSymbol *ProEndSym = context.createTempSymbol("prologue_end");
502 
503   // Length of the prologue, is the next 4 bytes (8 bytes for DWARF64). This is
504   // actually the length from after the length word, to the end of the prologue.
505   MCOS->emitAbsoluteSymbolDiff(ProEndSym, ProStartSym, OffsetSize);
506 
507   MCOS->emitLabel(ProStartSym);
508 
509   // Parameters of the state machine, are next.
510   MCOS->emitInt8(context.getAsmInfo()->getMinInstAlignment());
511   // maximum_operations_per_instruction
512   // For non-VLIW architectures this field is always 1.
513   // FIXME: VLIW architectures need to update this field accordingly.
514   if (LineTableVersion >= 4)
515     MCOS->emitInt8(1);
516   MCOS->emitInt8(DWARF2_LINE_DEFAULT_IS_STMT);
517   MCOS->emitInt8(Params.DWARF2LineBase);
518   MCOS->emitInt8(Params.DWARF2LineRange);
519   MCOS->emitInt8(StandardOpcodeLengths.size() + 1);
520 
521   // Standard opcode lengths
522   for (char Length : StandardOpcodeLengths)
523     MCOS->emitInt8(Length);
524 
525   // Put out the directory and file tables.  The formats vary depending on
526   // the version.
527   if (LineTableVersion >= 5)
528     emitV5FileDirTables(MCOS, LineStr);
529   else
530     emitV2FileDirTables(MCOS);
531 
532   // This is the end of the prologue, so set the value of the symbol at the
533   // end of the prologue (that was used in a previous expression).
534   MCOS->emitLabel(ProEndSym);
535 
536   return std::make_pair(LineStartSym, LineEndSym);
537 }
538 
539 void MCDwarfLineTable::emitCU(MCStreamer *MCOS, MCDwarfLineTableParams Params,
540                               Optional<MCDwarfLineStr> &LineStr) const {
541   MCSymbol *LineEndSym = Header.Emit(MCOS, Params, LineStr).second;
542 
543   // Put out the line tables.
544   for (const auto &LineSec : MCLineSections.getMCLineEntries())
545     emitOne(MCOS, LineSec.first, LineSec.second);
546 
547   // This is the end of the section, so set the value of the symbol at the end
548   // of this section (that was used in a previous expression).
549   MCOS->emitLabel(LineEndSym);
550 }
551 
552 Expected<unsigned> MCDwarfLineTable::tryGetFile(StringRef &Directory,
553                                                 StringRef &FileName,
554                                                 Optional<MD5::MD5Result> Checksum,
555                                                 Optional<StringRef> Source,
556                                                 uint16_t DwarfVersion,
557                                                 unsigned FileNumber) {
558   return Header.tryGetFile(Directory, FileName, Checksum, Source, DwarfVersion,
559                            FileNumber);
560 }
561 
562 static bool isRootFile(const MCDwarfFile &RootFile, StringRef &Directory,
563                        StringRef &FileName, Optional<MD5::MD5Result> Checksum) {
564   if (RootFile.Name.empty() || StringRef(RootFile.Name) != FileName)
565     return false;
566   return RootFile.Checksum == Checksum;
567 }
568 
569 Expected<unsigned>
570 MCDwarfLineTableHeader::tryGetFile(StringRef &Directory,
571                                    StringRef &FileName,
572                                    Optional<MD5::MD5Result> Checksum,
573                                    Optional<StringRef> Source,
574                                    uint16_t DwarfVersion,
575                                    unsigned FileNumber) {
576   if (Directory == CompilationDir)
577     Directory = "";
578   if (FileName.empty()) {
579     FileName = "<stdin>";
580     Directory = "";
581   }
582   assert(!FileName.empty());
583   // Keep track of whether any or all files have an MD5 checksum.
584   // If any files have embedded source, they all must.
585   if (MCDwarfFiles.empty()) {
586     trackMD5Usage(Checksum.hasValue());
587     HasSource = (Source != None);
588   }
589   if (DwarfVersion >= 5 && isRootFile(RootFile, Directory, FileName, Checksum))
590     return 0;
591   if (FileNumber == 0) {
592     // File numbers start with 1 and/or after any file numbers
593     // allocated by inline-assembler .file directives.
594     FileNumber = MCDwarfFiles.empty() ? 1 : MCDwarfFiles.size();
595     SmallString<256> Buffer;
596     auto IterBool = SourceIdMap.insert(
597         std::make_pair((Directory + Twine('\0') + FileName).toStringRef(Buffer),
598                        FileNumber));
599     if (!IterBool.second)
600       return IterBool.first->second;
601   }
602   // Make space for this FileNumber in the MCDwarfFiles vector if needed.
603   if (FileNumber >= MCDwarfFiles.size())
604     MCDwarfFiles.resize(FileNumber + 1);
605 
606   // Get the new MCDwarfFile slot for this FileNumber.
607   MCDwarfFile &File = MCDwarfFiles[FileNumber];
608 
609   // It is an error to see the same number more than once.
610   if (!File.Name.empty())
611     return make_error<StringError>("file number already allocated",
612                                    inconvertibleErrorCode());
613 
614   // If any files have embedded source, they all must.
615   if (HasSource != (Source != None))
616     return make_error<StringError>("inconsistent use of embedded source",
617                                    inconvertibleErrorCode());
618 
619   if (Directory.empty()) {
620     // Separate the directory part from the basename of the FileName.
621     StringRef tFileName = sys::path::filename(FileName);
622     if (!tFileName.empty()) {
623       Directory = sys::path::parent_path(FileName);
624       if (!Directory.empty())
625         FileName = tFileName;
626     }
627   }
628 
629   // Find or make an entry in the MCDwarfDirs vector for this Directory.
630   // Capture directory name.
631   unsigned DirIndex;
632   if (Directory.empty()) {
633     // For FileNames with no directories a DirIndex of 0 is used.
634     DirIndex = 0;
635   } else {
636     DirIndex = llvm::find(MCDwarfDirs, Directory) - MCDwarfDirs.begin();
637     if (DirIndex >= MCDwarfDirs.size())
638       MCDwarfDirs.push_back(std::string(Directory));
639     // The DirIndex is one based, as DirIndex of 0 is used for FileNames with
640     // no directories.  MCDwarfDirs[] is unlike MCDwarfFiles[] in that the
641     // directory names are stored at MCDwarfDirs[DirIndex-1] where FileNames
642     // are stored at MCDwarfFiles[FileNumber].Name .
643     DirIndex++;
644   }
645 
646   File.Name = std::string(FileName);
647   File.DirIndex = DirIndex;
648   File.Checksum = Checksum;
649   trackMD5Usage(Checksum.hasValue());
650   File.Source = Source;
651   if (Source)
652     HasSource = true;
653 
654   // return the allocated FileNumber.
655   return FileNumber;
656 }
657 
658 /// Utility function to emit the encoding to a streamer.
659 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, MCDwarfLineTableParams Params,
660                            int64_t LineDelta, uint64_t AddrDelta) {
661   MCContext &Context = MCOS->getContext();
662   SmallString<256> Tmp;
663   raw_svector_ostream OS(Tmp);
664   MCDwarfLineAddr::Encode(Context, Params, LineDelta, AddrDelta, OS);
665   MCOS->emitBytes(OS.str());
666 }
667 
668 /// Given a special op, return the address skip amount (in units of
669 /// DWARF2_LINE_MIN_INSN_LENGTH).
670 static uint64_t SpecialAddr(MCDwarfLineTableParams Params, uint64_t op) {
671   return (op - Params.DWARF2LineOpcodeBase) / Params.DWARF2LineRange;
672 }
673 
674 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
675 void MCDwarfLineAddr::Encode(MCContext &Context, MCDwarfLineTableParams Params,
676                              int64_t LineDelta, uint64_t AddrDelta,
677                              raw_ostream &OS) {
678   uint64_t Temp, Opcode;
679   bool NeedCopy = false;
680 
681   // The maximum address skip amount that can be encoded with a special op.
682   uint64_t MaxSpecialAddrDelta = SpecialAddr(Params, 255);
683 
684   // Scale the address delta by the minimum instruction length.
685   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
686 
687   // A LineDelta of INT64_MAX is a signal that this is actually a
688   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the
689   // end_sequence to emit the matrix entry.
690   if (LineDelta == INT64_MAX) {
691     if (AddrDelta == MaxSpecialAddrDelta)
692       OS << char(dwarf::DW_LNS_const_add_pc);
693     else if (AddrDelta) {
694       OS << char(dwarf::DW_LNS_advance_pc);
695       encodeULEB128(AddrDelta, OS);
696     }
697     OS << char(dwarf::DW_LNS_extended_op);
698     OS << char(1);
699     OS << char(dwarf::DW_LNE_end_sequence);
700     return;
701   }
702 
703   // Bias the line delta by the base.
704   Temp = LineDelta - Params.DWARF2LineBase;
705 
706   // If the line increment is out of range of a special opcode, we must encode
707   // it with DW_LNS_advance_line.
708   if (Temp >= Params.DWARF2LineRange ||
709       Temp + Params.DWARF2LineOpcodeBase > 255) {
710     OS << char(dwarf::DW_LNS_advance_line);
711     encodeSLEB128(LineDelta, OS);
712 
713     LineDelta = 0;
714     Temp = 0 - Params.DWARF2LineBase;
715     NeedCopy = true;
716   }
717 
718   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
719   if (LineDelta == 0 && AddrDelta == 0) {
720     OS << char(dwarf::DW_LNS_copy);
721     return;
722   }
723 
724   // Bias the opcode by the special opcode base.
725   Temp += Params.DWARF2LineOpcodeBase;
726 
727   // Avoid overflow when addr_delta is large.
728   if (AddrDelta < 256 + MaxSpecialAddrDelta) {
729     // Try using a special opcode.
730     Opcode = Temp + AddrDelta * Params.DWARF2LineRange;
731     if (Opcode <= 255) {
732       OS << char(Opcode);
733       return;
734     }
735 
736     // Try using DW_LNS_const_add_pc followed by special op.
737     Opcode = Temp + (AddrDelta - MaxSpecialAddrDelta) * Params.DWARF2LineRange;
738     if (Opcode <= 255) {
739       OS << char(dwarf::DW_LNS_const_add_pc);
740       OS << char(Opcode);
741       return;
742     }
743   }
744 
745   // Otherwise use DW_LNS_advance_pc.
746   OS << char(dwarf::DW_LNS_advance_pc);
747   encodeULEB128(AddrDelta, OS);
748 
749   if (NeedCopy)
750     OS << char(dwarf::DW_LNS_copy);
751   else {
752     assert(Temp <= 255 && "Buggy special opcode encoding.");
753     OS << char(Temp);
754   }
755 }
756 
757 // Utility function to write a tuple for .debug_abbrev.
758 static void EmitAbbrev(MCStreamer *MCOS, uint64_t Name, uint64_t Form) {
759   MCOS->emitULEB128IntValue(Name);
760   MCOS->emitULEB128IntValue(Form);
761 }
762 
763 // When generating dwarf for assembly source files this emits
764 // the data for .debug_abbrev section which contains three DIEs.
765 static void EmitGenDwarfAbbrev(MCStreamer *MCOS) {
766   MCContext &context = MCOS->getContext();
767   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
768 
769   // DW_TAG_compile_unit DIE abbrev (1).
770   MCOS->emitULEB128IntValue(1);
771   MCOS->emitULEB128IntValue(dwarf::DW_TAG_compile_unit);
772   MCOS->emitInt8(dwarf::DW_CHILDREN_yes);
773   dwarf::Form SecOffsetForm =
774       context.getDwarfVersion() >= 4
775           ? dwarf::DW_FORM_sec_offset
776           : (context.getDwarfFormat() == dwarf::DWARF64 ? dwarf::DW_FORM_data8
777                                                         : dwarf::DW_FORM_data4);
778   EmitAbbrev(MCOS, dwarf::DW_AT_stmt_list, SecOffsetForm);
779   if (context.getGenDwarfSectionSyms().size() > 1 &&
780       context.getDwarfVersion() >= 3) {
781     EmitAbbrev(MCOS, dwarf::DW_AT_ranges, SecOffsetForm);
782   } else {
783     EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
784     EmitAbbrev(MCOS, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr);
785   }
786   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
787   if (!context.getCompilationDir().empty())
788     EmitAbbrev(MCOS, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string);
789   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
790   if (!DwarfDebugFlags.empty())
791     EmitAbbrev(MCOS, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string);
792   EmitAbbrev(MCOS, dwarf::DW_AT_producer, dwarf::DW_FORM_string);
793   EmitAbbrev(MCOS, dwarf::DW_AT_language, dwarf::DW_FORM_data2);
794   EmitAbbrev(MCOS, 0, 0);
795 
796   // DW_TAG_label DIE abbrev (2).
797   MCOS->emitULEB128IntValue(2);
798   MCOS->emitULEB128IntValue(dwarf::DW_TAG_label);
799   MCOS->emitInt8(dwarf::DW_CHILDREN_no);
800   EmitAbbrev(MCOS, dwarf::DW_AT_name, dwarf::DW_FORM_string);
801   EmitAbbrev(MCOS, dwarf::DW_AT_decl_file, dwarf::DW_FORM_data4);
802   EmitAbbrev(MCOS, dwarf::DW_AT_decl_line, dwarf::DW_FORM_data4);
803   EmitAbbrev(MCOS, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr);
804   EmitAbbrev(MCOS, 0, 0);
805 
806   // Terminate the abbreviations for this compilation unit.
807   MCOS->emitInt8(0);
808 }
809 
810 // When generating dwarf for assembly source files this emits the data for
811 // .debug_aranges section. This section contains a header and a table of pairs
812 // of PointerSize'ed values for the address and size of section(s) with line
813 // table entries.
814 static void EmitGenDwarfAranges(MCStreamer *MCOS,
815                                 const MCSymbol *InfoSectionSymbol) {
816   MCContext &context = MCOS->getContext();
817 
818   auto &Sections = context.getGenDwarfSectionSyms();
819 
820   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
821 
822   unsigned UnitLengthBytes =
823       dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
824   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
825 
826   // This will be the length of the .debug_aranges section, first account for
827   // the size of each item in the header (see below where we emit these items).
828   int Length = UnitLengthBytes + 2 + OffsetSize + 1 + 1;
829 
830   // Figure the padding after the header before the table of address and size
831   // pairs who's values are PointerSize'ed.
832   const MCAsmInfo *asmInfo = context.getAsmInfo();
833   int AddrSize = asmInfo->getCodePointerSize();
834   int Pad = 2 * AddrSize - (Length & (2 * AddrSize - 1));
835   if (Pad == 2 * AddrSize)
836     Pad = 0;
837   Length += Pad;
838 
839   // Add the size of the pair of PointerSize'ed values for the address and size
840   // of each section we have in the table.
841   Length += 2 * AddrSize * Sections.size();
842   // And the pair of terminating zeros.
843   Length += 2 * AddrSize;
844 
845   // Emit the header for this section.
846   if (context.getDwarfFormat() == dwarf::DWARF64)
847     // The DWARF64 mark.
848     MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
849   // The 4 (8 for DWARF64) byte length not including the length of the unit
850   // length field itself.
851   MCOS->emitIntValue(Length - UnitLengthBytes, OffsetSize);
852   // The 2 byte version, which is 2.
853   MCOS->emitInt16(2);
854   // The 4 (8 for DWARF64) byte offset to the compile unit in the .debug_info
855   // from the start of the .debug_info.
856   if (InfoSectionSymbol)
857     MCOS->emitSymbolValue(InfoSectionSymbol, OffsetSize,
858                           asmInfo->needsDwarfSectionOffsetDirective());
859   else
860     MCOS->emitIntValue(0, OffsetSize);
861   // The 1 byte size of an address.
862   MCOS->emitInt8(AddrSize);
863   // The 1 byte size of a segment descriptor, we use a value of zero.
864   MCOS->emitInt8(0);
865   // Align the header with the padding if needed, before we put out the table.
866   for(int i = 0; i < Pad; i++)
867     MCOS->emitInt8(0);
868 
869   // Now emit the table of pairs of PointerSize'ed values for the section
870   // addresses and sizes.
871   for (MCSection *Sec : Sections) {
872     const MCSymbol *StartSymbol = Sec->getBeginSymbol();
873     MCSymbol *EndSymbol = Sec->getEndSymbol(context);
874     assert(StartSymbol && "StartSymbol must not be NULL");
875     assert(EndSymbol && "EndSymbol must not be NULL");
876 
877     const MCExpr *Addr = MCSymbolRefExpr::create(
878       StartSymbol, MCSymbolRefExpr::VK_None, context);
879     const MCExpr *Size =
880         makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
881     MCOS->emitValue(Addr, AddrSize);
882     emitAbsValue(*MCOS, Size, AddrSize);
883   }
884 
885   // And finally the pair of terminating zeros.
886   MCOS->emitIntValue(0, AddrSize);
887   MCOS->emitIntValue(0, AddrSize);
888 }
889 
890 // When generating dwarf for assembly source files this emits the data for
891 // .debug_info section which contains three parts.  The header, the compile_unit
892 // DIE and a list of label DIEs.
893 static void EmitGenDwarfInfo(MCStreamer *MCOS,
894                              const MCSymbol *AbbrevSectionSymbol,
895                              const MCSymbol *LineSectionSymbol,
896                              const MCSymbol *RangesSymbol) {
897   MCContext &context = MCOS->getContext();
898 
899   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
900 
901   // Create a symbol at the start and end of this section used in here for the
902   // expression to calculate the length in the header.
903   MCSymbol *InfoStart = context.createTempSymbol();
904   MCOS->emitLabel(InfoStart);
905   MCSymbol *InfoEnd = context.createTempSymbol();
906 
907   // First part: the header.
908 
909   unsigned UnitLengthBytes =
910       dwarf::getUnitLengthFieldByteSize(context.getDwarfFormat());
911   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(context.getDwarfFormat());
912 
913   if (context.getDwarfFormat() == dwarf::DWARF64)
914     // Emit DWARF64 mark.
915     MCOS->emitInt32(dwarf::DW_LENGTH_DWARF64);
916 
917   // The 4 (8 for DWARF64) byte total length of the information for this
918   // compilation unit, not including the unit length field itself.
919   const MCExpr *Length =
920       makeEndMinusStartExpr(context, *InfoStart, *InfoEnd, UnitLengthBytes);
921   emitAbsValue(*MCOS, Length, OffsetSize);
922 
923   // The 2 byte DWARF version.
924   MCOS->emitInt16(context.getDwarfVersion());
925 
926   // The DWARF v5 header has unit type, address size, abbrev offset.
927   // Earlier versions have abbrev offset, address size.
928   const MCAsmInfo &AsmInfo = *context.getAsmInfo();
929   int AddrSize = AsmInfo.getCodePointerSize();
930   if (context.getDwarfVersion() >= 5) {
931     MCOS->emitInt8(dwarf::DW_UT_compile);
932     MCOS->emitInt8(AddrSize);
933   }
934   // The 4 (8 for DWARF64) byte offset to the debug abbrevs from the start of
935   // the .debug_abbrev.
936   if (AbbrevSectionSymbol)
937     MCOS->emitSymbolValue(AbbrevSectionSymbol, OffsetSize,
938                           AsmInfo.needsDwarfSectionOffsetDirective());
939   else
940     // Since the abbrevs are at the start of the section, the offset is zero.
941     MCOS->emitIntValue(0, OffsetSize);
942   if (context.getDwarfVersion() <= 4)
943     MCOS->emitInt8(AddrSize);
944 
945   // Second part: the compile_unit DIE.
946 
947   // The DW_TAG_compile_unit DIE abbrev (1).
948   MCOS->emitULEB128IntValue(1);
949 
950   // DW_AT_stmt_list, a 4 (8 for DWARF64) byte offset from the start of the
951   // .debug_line section.
952   if (LineSectionSymbol)
953     MCOS->emitSymbolValue(LineSectionSymbol, OffsetSize,
954                           AsmInfo.needsDwarfSectionOffsetDirective());
955   else
956     // The line table is at the start of the section, so the offset is zero.
957     MCOS->emitIntValue(0, OffsetSize);
958 
959   if (RangesSymbol) {
960     // There are multiple sections containing code, so we must use
961     // .debug_ranges/.debug_rnglists. AT_ranges, the 4/8 byte offset from the
962     // start of the .debug_ranges/.debug_rnglists.
963     MCOS->emitSymbolValue(RangesSymbol, OffsetSize);
964   } else {
965     // If we only have one non-empty code section, we can use the simpler
966     // AT_low_pc and AT_high_pc attributes.
967 
968     // Find the first (and only) non-empty text section
969     auto &Sections = context.getGenDwarfSectionSyms();
970     const auto TextSection = Sections.begin();
971     assert(TextSection != Sections.end() && "No text section found");
972 
973     MCSymbol *StartSymbol = (*TextSection)->getBeginSymbol();
974     MCSymbol *EndSymbol = (*TextSection)->getEndSymbol(context);
975     assert(StartSymbol && "StartSymbol must not be NULL");
976     assert(EndSymbol && "EndSymbol must not be NULL");
977 
978     // AT_low_pc, the first address of the default .text section.
979     const MCExpr *Start = MCSymbolRefExpr::create(
980         StartSymbol, MCSymbolRefExpr::VK_None, context);
981     MCOS->emitValue(Start, AddrSize);
982 
983     // AT_high_pc, the last address of the default .text section.
984     const MCExpr *End = MCSymbolRefExpr::create(
985       EndSymbol, MCSymbolRefExpr::VK_None, context);
986     MCOS->emitValue(End, AddrSize);
987   }
988 
989   // AT_name, the name of the source file.  Reconstruct from the first directory
990   // and file table entries.
991   const SmallVectorImpl<std::string> &MCDwarfDirs = context.getMCDwarfDirs();
992   if (MCDwarfDirs.size() > 0) {
993     MCOS->emitBytes(MCDwarfDirs[0]);
994     MCOS->emitBytes(sys::path::get_separator());
995   }
996   const SmallVectorImpl<MCDwarfFile> &MCDwarfFiles = context.getMCDwarfFiles();
997   // MCDwarfFiles might be empty if we have an empty source file.
998   // If it's not empty, [0] is unused and [1] is the first actual file.
999   assert(MCDwarfFiles.empty() || MCDwarfFiles.size() >= 2);
1000   const MCDwarfFile &RootFile =
1001       MCDwarfFiles.empty()
1002           ? context.getMCDwarfLineTable(/*CUID=*/0).getRootFile()
1003           : MCDwarfFiles[1];
1004   MCOS->emitBytes(RootFile.Name);
1005   MCOS->emitInt8(0); // NULL byte to terminate the string.
1006 
1007   // AT_comp_dir, the working directory the assembly was done in.
1008   if (!context.getCompilationDir().empty()) {
1009     MCOS->emitBytes(context.getCompilationDir());
1010     MCOS->emitInt8(0); // NULL byte to terminate the string.
1011   }
1012 
1013   // AT_APPLE_flags, the command line arguments of the assembler tool.
1014   StringRef DwarfDebugFlags = context.getDwarfDebugFlags();
1015   if (!DwarfDebugFlags.empty()){
1016     MCOS->emitBytes(DwarfDebugFlags);
1017     MCOS->emitInt8(0); // NULL byte to terminate the string.
1018   }
1019 
1020   // AT_producer, the version of the assembler tool.
1021   StringRef DwarfDebugProducer = context.getDwarfDebugProducer();
1022   if (!DwarfDebugProducer.empty())
1023     MCOS->emitBytes(DwarfDebugProducer);
1024   else
1025     MCOS->emitBytes(StringRef("llvm-mc (based on LLVM " PACKAGE_VERSION ")"));
1026   MCOS->emitInt8(0); // NULL byte to terminate the string.
1027 
1028   // AT_language, a 4 byte value.  We use DW_LANG_Mips_Assembler as the dwarf2
1029   // draft has no standard code for assembler.
1030   MCOS->emitInt16(dwarf::DW_LANG_Mips_Assembler);
1031 
1032   // Third part: the list of label DIEs.
1033 
1034   // Loop on saved info for dwarf labels and create the DIEs for them.
1035   const std::vector<MCGenDwarfLabelEntry> &Entries =
1036       MCOS->getContext().getMCGenDwarfLabelEntries();
1037   for (const auto &Entry : Entries) {
1038     // The DW_TAG_label DIE abbrev (2).
1039     MCOS->emitULEB128IntValue(2);
1040 
1041     // AT_name, of the label without any leading underbar.
1042     MCOS->emitBytes(Entry.getName());
1043     MCOS->emitInt8(0); // NULL byte to terminate the string.
1044 
1045     // AT_decl_file, index into the file table.
1046     MCOS->emitInt32(Entry.getFileNumber());
1047 
1048     // AT_decl_line, source line number.
1049     MCOS->emitInt32(Entry.getLineNumber());
1050 
1051     // AT_low_pc, start address of the label.
1052     const MCExpr *AT_low_pc = MCSymbolRefExpr::create(Entry.getLabel(),
1053                                              MCSymbolRefExpr::VK_None, context);
1054     MCOS->emitValue(AT_low_pc, AddrSize);
1055   }
1056 
1057   // Add the NULL DIE terminating the Compile Unit DIE's.
1058   MCOS->emitInt8(0);
1059 
1060   // Now set the value of the symbol at the end of the info section.
1061   MCOS->emitLabel(InfoEnd);
1062 }
1063 
1064 // When generating dwarf for assembly source files this emits the data for
1065 // .debug_ranges section. We only emit one range list, which spans all of the
1066 // executable sections of this file.
1067 static MCSymbol *emitGenDwarfRanges(MCStreamer *MCOS) {
1068   MCContext &context = MCOS->getContext();
1069   auto &Sections = context.getGenDwarfSectionSyms();
1070 
1071   const MCAsmInfo *AsmInfo = context.getAsmInfo();
1072   int AddrSize = AsmInfo->getCodePointerSize();
1073   MCSymbol *RangesSymbol;
1074 
1075   if (MCOS->getContext().getDwarfVersion() >= 5) {
1076     MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRnglistsSection());
1077     MCSymbol *EndSymbol = mcdwarf::emitListsTableHeaderStart(*MCOS);
1078     MCOS->AddComment("Offset entry count");
1079     MCOS->emitInt32(0);
1080     RangesSymbol = context.createTempSymbol("debug_rnglist0_start");
1081     MCOS->emitLabel(RangesSymbol);
1082     for (MCSection *Sec : Sections) {
1083       const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1084       const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1085       const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1086           StartSymbol, MCSymbolRefExpr::VK_None, context);
1087       const MCExpr *SectionSize =
1088           makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1089       MCOS->emitInt8(dwarf::DW_RLE_start_length);
1090       MCOS->emitValue(SectionStartAddr, AddrSize);
1091       MCOS->emitULEB128Value(SectionSize);
1092     }
1093     MCOS->emitInt8(dwarf::DW_RLE_end_of_list);
1094     MCOS->emitLabel(EndSymbol);
1095   } else {
1096     MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfRangesSection());
1097     RangesSymbol = context.createTempSymbol("debug_ranges_start");
1098     MCOS->emitLabel(RangesSymbol);
1099     for (MCSection *Sec : Sections) {
1100       const MCSymbol *StartSymbol = Sec->getBeginSymbol();
1101       const MCSymbol *EndSymbol = Sec->getEndSymbol(context);
1102 
1103       // Emit a base address selection entry for the section start.
1104       const MCExpr *SectionStartAddr = MCSymbolRefExpr::create(
1105           StartSymbol, MCSymbolRefExpr::VK_None, context);
1106       MCOS->emitFill(AddrSize, 0xFF);
1107       MCOS->emitValue(SectionStartAddr, AddrSize);
1108 
1109       // Emit a range list entry spanning this section.
1110       const MCExpr *SectionSize =
1111           makeEndMinusStartExpr(context, *StartSymbol, *EndSymbol, 0);
1112       MCOS->emitIntValue(0, AddrSize);
1113       emitAbsValue(*MCOS, SectionSize, AddrSize);
1114     }
1115 
1116     // Emit end of list entry
1117     MCOS->emitIntValue(0, AddrSize);
1118     MCOS->emitIntValue(0, AddrSize);
1119   }
1120 
1121   return RangesSymbol;
1122 }
1123 
1124 //
1125 // When generating dwarf for assembly source files this emits the Dwarf
1126 // sections.
1127 //
1128 void MCGenDwarfInfo::Emit(MCStreamer *MCOS) {
1129   MCContext &context = MCOS->getContext();
1130 
1131   // Create the dwarf sections in this order (.debug_line already created).
1132   const MCAsmInfo *AsmInfo = context.getAsmInfo();
1133   bool CreateDwarfSectionSymbols =
1134       AsmInfo->doesDwarfUseRelocationsAcrossSections();
1135   MCSymbol *LineSectionSymbol = nullptr;
1136   if (CreateDwarfSectionSymbols)
1137     LineSectionSymbol = MCOS->getDwarfLineTableSymbol(0);
1138   MCSymbol *AbbrevSectionSymbol = nullptr;
1139   MCSymbol *InfoSectionSymbol = nullptr;
1140   MCSymbol *RangesSymbol = nullptr;
1141 
1142   // Create end symbols for each section, and remove empty sections
1143   MCOS->getContext().finalizeDwarfSections(*MCOS);
1144 
1145   // If there are no sections to generate debug info for, we don't need
1146   // to do anything
1147   if (MCOS->getContext().getGenDwarfSectionSyms().empty())
1148     return;
1149 
1150   // We only use the .debug_ranges section if we have multiple code sections,
1151   // and we are emitting a DWARF version which supports it.
1152   const bool UseRangesSection =
1153       MCOS->getContext().getGenDwarfSectionSyms().size() > 1 &&
1154       MCOS->getContext().getDwarfVersion() >= 3;
1155   CreateDwarfSectionSymbols |= UseRangesSection;
1156 
1157   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfInfoSection());
1158   if (CreateDwarfSectionSymbols) {
1159     InfoSectionSymbol = context.createTempSymbol();
1160     MCOS->emitLabel(InfoSectionSymbol);
1161   }
1162   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfAbbrevSection());
1163   if (CreateDwarfSectionSymbols) {
1164     AbbrevSectionSymbol = context.createTempSymbol();
1165     MCOS->emitLabel(AbbrevSectionSymbol);
1166   }
1167 
1168   MCOS->SwitchSection(context.getObjectFileInfo()->getDwarfARangesSection());
1169 
1170   // Output the data for .debug_aranges section.
1171   EmitGenDwarfAranges(MCOS, InfoSectionSymbol);
1172 
1173   if (UseRangesSection) {
1174     RangesSymbol = emitGenDwarfRanges(MCOS);
1175     assert(RangesSymbol);
1176   }
1177 
1178   // Output the data for .debug_abbrev section.
1179   EmitGenDwarfAbbrev(MCOS);
1180 
1181   // Output the data for .debug_info section.
1182   EmitGenDwarfInfo(MCOS, AbbrevSectionSymbol, LineSectionSymbol, RangesSymbol);
1183 }
1184 
1185 //
1186 // When generating dwarf for assembly source files this is called when symbol
1187 // for a label is created.  If this symbol is not a temporary and is in the
1188 // section that dwarf is being generated for, save the needed info to create
1189 // a dwarf label.
1190 //
1191 void MCGenDwarfLabelEntry::Make(MCSymbol *Symbol, MCStreamer *MCOS,
1192                                      SourceMgr &SrcMgr, SMLoc &Loc) {
1193   // We won't create dwarf labels for temporary symbols.
1194   if (Symbol->isTemporary())
1195     return;
1196   MCContext &context = MCOS->getContext();
1197   // We won't create dwarf labels for symbols in sections that we are not
1198   // generating debug info for.
1199   if (!context.getGenDwarfSectionSyms().count(MCOS->getCurrentSectionOnly()))
1200     return;
1201 
1202   // The dwarf label's name does not have the symbol name's leading
1203   // underbar if any.
1204   StringRef Name = Symbol->getName();
1205   if (Name.startswith("_"))
1206     Name = Name.substr(1, Name.size()-1);
1207 
1208   // Get the dwarf file number to be used for the dwarf label.
1209   unsigned FileNumber = context.getGenDwarfFileNumber();
1210 
1211   // Finding the line number is the expensive part which is why we just don't
1212   // pass it in as for some symbols we won't create a dwarf label.
1213   unsigned CurBuffer = SrcMgr.FindBufferContainingLoc(Loc);
1214   unsigned LineNumber = SrcMgr.FindLineNumber(Loc, CurBuffer);
1215 
1216   // We create a temporary symbol for use for the AT_high_pc and AT_low_pc
1217   // values so that they don't have things like an ARM thumb bit from the
1218   // original symbol. So when used they won't get a low bit set after
1219   // relocation.
1220   MCSymbol *Label = context.createTempSymbol();
1221   MCOS->emitLabel(Label);
1222 
1223   // Create and entry for the info and add it to the other entries.
1224   MCOS->getContext().addMCGenDwarfLabelEntry(
1225       MCGenDwarfLabelEntry(Name, FileNumber, LineNumber, Label));
1226 }
1227 
1228 static int getDataAlignmentFactor(MCStreamer &streamer) {
1229   MCContext &context = streamer.getContext();
1230   const MCAsmInfo *asmInfo = context.getAsmInfo();
1231   int size = asmInfo->getCalleeSaveStackSlotSize();
1232   if (asmInfo->isStackGrowthDirectionUp())
1233     return size;
1234   else
1235     return -size;
1236 }
1237 
1238 static unsigned getSizeForEncoding(MCStreamer &streamer,
1239                                    unsigned symbolEncoding) {
1240   MCContext &context = streamer.getContext();
1241   unsigned format = symbolEncoding & 0x0f;
1242   switch (format) {
1243   default: llvm_unreachable("Unknown Encoding");
1244   case dwarf::DW_EH_PE_absptr:
1245   case dwarf::DW_EH_PE_signed:
1246     return context.getAsmInfo()->getCodePointerSize();
1247   case dwarf::DW_EH_PE_udata2:
1248   case dwarf::DW_EH_PE_sdata2:
1249     return 2;
1250   case dwarf::DW_EH_PE_udata4:
1251   case dwarf::DW_EH_PE_sdata4:
1252     return 4;
1253   case dwarf::DW_EH_PE_udata8:
1254   case dwarf::DW_EH_PE_sdata8:
1255     return 8;
1256   }
1257 }
1258 
1259 static void emitFDESymbol(MCObjectStreamer &streamer, const MCSymbol &symbol,
1260                        unsigned symbolEncoding, bool isEH) {
1261   MCContext &context = streamer.getContext();
1262   const MCAsmInfo *asmInfo = context.getAsmInfo();
1263   const MCExpr *v = asmInfo->getExprForFDESymbol(&symbol,
1264                                                  symbolEncoding,
1265                                                  streamer);
1266   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1267   if (asmInfo->doDwarfFDESymbolsUseAbsDiff() && isEH)
1268     emitAbsValue(streamer, v, size);
1269   else
1270     streamer.emitValue(v, size);
1271 }
1272 
1273 static void EmitPersonality(MCStreamer &streamer, const MCSymbol &symbol,
1274                             unsigned symbolEncoding) {
1275   MCContext &context = streamer.getContext();
1276   const MCAsmInfo *asmInfo = context.getAsmInfo();
1277   const MCExpr *v = asmInfo->getExprForPersonalitySymbol(&symbol,
1278                                                          symbolEncoding,
1279                                                          streamer);
1280   unsigned size = getSizeForEncoding(streamer, symbolEncoding);
1281   streamer.emitValue(v, size);
1282 }
1283 
1284 namespace {
1285 
1286 class FrameEmitterImpl {
1287   int CFAOffset = 0;
1288   int InitialCFAOffset = 0;
1289   bool IsEH;
1290   MCObjectStreamer &Streamer;
1291 
1292 public:
1293   FrameEmitterImpl(bool IsEH, MCObjectStreamer &Streamer)
1294       : IsEH(IsEH), Streamer(Streamer) {}
1295 
1296   /// Emit the unwind information in a compact way.
1297   void EmitCompactUnwind(const MCDwarfFrameInfo &frame);
1298 
1299   const MCSymbol &EmitCIE(const MCDwarfFrameInfo &F);
1300   void EmitFDE(const MCSymbol &cieStart, const MCDwarfFrameInfo &frame,
1301                bool LastInSection, const MCSymbol &SectionStart);
1302   void emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1303                            MCSymbol *BaseLabel);
1304   void emitCFIInstruction(const MCCFIInstruction &Instr);
1305 };
1306 
1307 } // end anonymous namespace
1308 
1309 static void emitEncodingByte(MCObjectStreamer &Streamer, unsigned Encoding) {
1310   Streamer.emitInt8(Encoding);
1311 }
1312 
1313 void FrameEmitterImpl::emitCFIInstruction(const MCCFIInstruction &Instr) {
1314   int dataAlignmentFactor = getDataAlignmentFactor(Streamer);
1315   auto *MRI = Streamer.getContext().getRegisterInfo();
1316 
1317   switch (Instr.getOperation()) {
1318   case MCCFIInstruction::OpRegister: {
1319     unsigned Reg1 = Instr.getRegister();
1320     unsigned Reg2 = Instr.getRegister2();
1321     if (!IsEH) {
1322       Reg1 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg1);
1323       Reg2 = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg2);
1324     }
1325     Streamer.emitInt8(dwarf::DW_CFA_register);
1326     Streamer.emitULEB128IntValue(Reg1);
1327     Streamer.emitULEB128IntValue(Reg2);
1328     return;
1329   }
1330   case MCCFIInstruction::OpWindowSave:
1331     Streamer.emitInt8(dwarf::DW_CFA_GNU_window_save);
1332     return;
1333 
1334   case MCCFIInstruction::OpNegateRAState:
1335     Streamer.emitInt8(dwarf::DW_CFA_AARCH64_negate_ra_state);
1336     return;
1337 
1338   case MCCFIInstruction::OpUndefined: {
1339     unsigned Reg = Instr.getRegister();
1340     Streamer.emitInt8(dwarf::DW_CFA_undefined);
1341     Streamer.emitULEB128IntValue(Reg);
1342     return;
1343   }
1344   case MCCFIInstruction::OpAdjustCfaOffset:
1345   case MCCFIInstruction::OpDefCfaOffset: {
1346     const bool IsRelative =
1347       Instr.getOperation() == MCCFIInstruction::OpAdjustCfaOffset;
1348 
1349     Streamer.emitInt8(dwarf::DW_CFA_def_cfa_offset);
1350 
1351     if (IsRelative)
1352       CFAOffset += Instr.getOffset();
1353     else
1354       CFAOffset = Instr.getOffset();
1355 
1356     Streamer.emitULEB128IntValue(CFAOffset);
1357 
1358     return;
1359   }
1360   case MCCFIInstruction::OpDefCfa: {
1361     unsigned Reg = Instr.getRegister();
1362     if (!IsEH)
1363       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1364     Streamer.emitInt8(dwarf::DW_CFA_def_cfa);
1365     Streamer.emitULEB128IntValue(Reg);
1366     CFAOffset = Instr.getOffset();
1367     Streamer.emitULEB128IntValue(CFAOffset);
1368 
1369     return;
1370   }
1371   case MCCFIInstruction::OpDefCfaRegister: {
1372     unsigned Reg = Instr.getRegister();
1373     if (!IsEH)
1374       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1375     Streamer.emitInt8(dwarf::DW_CFA_def_cfa_register);
1376     Streamer.emitULEB128IntValue(Reg);
1377 
1378     return;
1379   }
1380   // TODO: Implement `_sf` variants if/when they need to be emitted.
1381   case MCCFIInstruction::OpLLVMDefAspaceCfa: {
1382     unsigned Reg = Instr.getRegister();
1383     if (!IsEH)
1384       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1385     Streamer.emitIntValue(dwarf::DW_CFA_LLVM_def_aspace_cfa, 1);
1386     Streamer.emitULEB128IntValue(Reg);
1387     CFAOffset = Instr.getOffset();
1388     Streamer.emitULEB128IntValue(CFAOffset);
1389     Streamer.emitULEB128IntValue(Instr.getAddressSpace());
1390 
1391     return;
1392   }
1393   case MCCFIInstruction::OpOffset:
1394   case MCCFIInstruction::OpRelOffset: {
1395     const bool IsRelative =
1396       Instr.getOperation() == MCCFIInstruction::OpRelOffset;
1397 
1398     unsigned Reg = Instr.getRegister();
1399     if (!IsEH)
1400       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1401 
1402     int Offset = Instr.getOffset();
1403     if (IsRelative)
1404       Offset -= CFAOffset;
1405     Offset = Offset / dataAlignmentFactor;
1406 
1407     if (Offset < 0) {
1408       Streamer.emitInt8(dwarf::DW_CFA_offset_extended_sf);
1409       Streamer.emitULEB128IntValue(Reg);
1410       Streamer.emitSLEB128IntValue(Offset);
1411     } else if (Reg < 64) {
1412       Streamer.emitInt8(dwarf::DW_CFA_offset + Reg);
1413       Streamer.emitULEB128IntValue(Offset);
1414     } else {
1415       Streamer.emitInt8(dwarf::DW_CFA_offset_extended);
1416       Streamer.emitULEB128IntValue(Reg);
1417       Streamer.emitULEB128IntValue(Offset);
1418     }
1419     return;
1420   }
1421   case MCCFIInstruction::OpRememberState:
1422     Streamer.emitInt8(dwarf::DW_CFA_remember_state);
1423     return;
1424   case MCCFIInstruction::OpRestoreState:
1425     Streamer.emitInt8(dwarf::DW_CFA_restore_state);
1426     return;
1427   case MCCFIInstruction::OpSameValue: {
1428     unsigned Reg = Instr.getRegister();
1429     Streamer.emitInt8(dwarf::DW_CFA_same_value);
1430     Streamer.emitULEB128IntValue(Reg);
1431     return;
1432   }
1433   case MCCFIInstruction::OpRestore: {
1434     unsigned Reg = Instr.getRegister();
1435     if (!IsEH)
1436       Reg = MRI->getDwarfRegNumFromDwarfEHRegNum(Reg);
1437     if (Reg < 64) {
1438       Streamer.emitInt8(dwarf::DW_CFA_restore | Reg);
1439     } else {
1440       Streamer.emitInt8(dwarf::DW_CFA_restore_extended);
1441       Streamer.emitULEB128IntValue(Reg);
1442     }
1443     return;
1444   }
1445   case MCCFIInstruction::OpGnuArgsSize:
1446     Streamer.emitInt8(dwarf::DW_CFA_GNU_args_size);
1447     Streamer.emitULEB128IntValue(Instr.getOffset());
1448     return;
1449 
1450   case MCCFIInstruction::OpEscape:
1451     Streamer.emitBytes(Instr.getValues());
1452     return;
1453   }
1454   llvm_unreachable("Unhandled case in switch");
1455 }
1456 
1457 /// Emit frame instructions to describe the layout of the frame.
1458 void FrameEmitterImpl::emitCFIInstructions(ArrayRef<MCCFIInstruction> Instrs,
1459                                            MCSymbol *BaseLabel) {
1460   for (const MCCFIInstruction &Instr : Instrs) {
1461     MCSymbol *Label = Instr.getLabel();
1462     // Throw out move if the label is invalid.
1463     if (Label && !Label->isDefined()) continue; // Not emitted, in dead code.
1464 
1465     // Advance row if new location.
1466     if (BaseLabel && Label) {
1467       MCSymbol *ThisSym = Label;
1468       if (ThisSym != BaseLabel) {
1469         Streamer.emitDwarfAdvanceFrameAddr(BaseLabel, ThisSym);
1470         BaseLabel = ThisSym;
1471       }
1472     }
1473 
1474     emitCFIInstruction(Instr);
1475   }
1476 }
1477 
1478 /// Emit the unwind information in a compact way.
1479 void FrameEmitterImpl::EmitCompactUnwind(const MCDwarfFrameInfo &Frame) {
1480   MCContext &Context = Streamer.getContext();
1481   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1482 
1483   // range-start range-length  compact-unwind-enc personality-func   lsda
1484   //  _foo       LfooEnd-_foo  0x00000023          0                 0
1485   //  _bar       LbarEnd-_bar  0x00000025         __gxx_personality  except_tab1
1486   //
1487   //   .section __LD,__compact_unwind,regular,debug
1488   //
1489   //   # compact unwind for _foo
1490   //   .quad _foo
1491   //   .set L1,LfooEnd-_foo
1492   //   .long L1
1493   //   .long 0x01010001
1494   //   .quad 0
1495   //   .quad 0
1496   //
1497   //   # compact unwind for _bar
1498   //   .quad _bar
1499   //   .set L2,LbarEnd-_bar
1500   //   .long L2
1501   //   .long 0x01020011
1502   //   .quad __gxx_personality
1503   //   .quad except_tab1
1504 
1505   uint32_t Encoding = Frame.CompactUnwindEncoding;
1506   if (!Encoding) return;
1507   bool DwarfEHFrameOnly = (Encoding == MOFI->getCompactUnwindDwarfEHFrameOnly());
1508 
1509   // The encoding needs to know we have an LSDA.
1510   if (!DwarfEHFrameOnly && Frame.Lsda)
1511     Encoding |= 0x40000000;
1512 
1513   // Range Start
1514   unsigned FDEEncoding = MOFI->getFDEEncoding();
1515   unsigned Size = getSizeForEncoding(Streamer, FDEEncoding);
1516   Streamer.emitSymbolValue(Frame.Begin, Size);
1517 
1518   // Range Length
1519   const MCExpr *Range =
1520       makeEndMinusStartExpr(Context, *Frame.Begin, *Frame.End, 0);
1521   emitAbsValue(Streamer, Range, 4);
1522 
1523   // Compact Encoding
1524   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_udata4);
1525   Streamer.emitIntValue(Encoding, Size);
1526 
1527   // Personality Function
1528   Size = getSizeForEncoding(Streamer, dwarf::DW_EH_PE_absptr);
1529   if (!DwarfEHFrameOnly && Frame.Personality)
1530     Streamer.emitSymbolValue(Frame.Personality, Size);
1531   else
1532     Streamer.emitIntValue(0, Size); // No personality fn
1533 
1534   // LSDA
1535   Size = getSizeForEncoding(Streamer, Frame.LsdaEncoding);
1536   if (!DwarfEHFrameOnly && Frame.Lsda)
1537     Streamer.emitSymbolValue(Frame.Lsda, Size);
1538   else
1539     Streamer.emitIntValue(0, Size); // No LSDA
1540 }
1541 
1542 static unsigned getCIEVersion(bool IsEH, unsigned DwarfVersion) {
1543   if (IsEH)
1544     return 1;
1545   switch (DwarfVersion) {
1546   case 2:
1547     return 1;
1548   case 3:
1549     return 3;
1550   case 4:
1551   case 5:
1552     return 4;
1553   }
1554   llvm_unreachable("Unknown version");
1555 }
1556 
1557 const MCSymbol &FrameEmitterImpl::EmitCIE(const MCDwarfFrameInfo &Frame) {
1558   MCContext &context = Streamer.getContext();
1559   const MCRegisterInfo *MRI = context.getRegisterInfo();
1560   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1561 
1562   MCSymbol *sectionStart = context.createTempSymbol();
1563   Streamer.emitLabel(sectionStart);
1564 
1565   MCSymbol *sectionEnd = context.createTempSymbol();
1566 
1567   dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1568   unsigned UnitLengthBytes = dwarf::getUnitLengthFieldByteSize(Format);
1569   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1570   bool IsDwarf64 = Format == dwarf::DWARF64;
1571 
1572   if (IsDwarf64)
1573     // DWARF64 mark
1574     Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1575 
1576   // Length
1577   const MCExpr *Length = makeEndMinusStartExpr(context, *sectionStart,
1578                                                *sectionEnd, UnitLengthBytes);
1579   emitAbsValue(Streamer, Length, OffsetSize);
1580 
1581   // CIE ID
1582   uint64_t CIE_ID =
1583       IsEH ? 0 : (IsDwarf64 ? dwarf::DW64_CIE_ID : dwarf::DW_CIE_ID);
1584   Streamer.emitIntValue(CIE_ID, OffsetSize);
1585 
1586   // Version
1587   uint8_t CIEVersion = getCIEVersion(IsEH, context.getDwarfVersion());
1588   Streamer.emitInt8(CIEVersion);
1589 
1590   if (IsEH) {
1591     SmallString<8> Augmentation;
1592     Augmentation += "z";
1593     if (Frame.Personality)
1594       Augmentation += "P";
1595     if (Frame.Lsda)
1596       Augmentation += "L";
1597     Augmentation += "R";
1598     if (Frame.IsSignalFrame)
1599       Augmentation += "S";
1600     if (Frame.IsBKeyFrame)
1601       Augmentation += "B";
1602     Streamer.emitBytes(Augmentation);
1603   }
1604   Streamer.emitInt8(0);
1605 
1606   if (CIEVersion >= 4) {
1607     // Address Size
1608     Streamer.emitInt8(context.getAsmInfo()->getCodePointerSize());
1609 
1610     // Segment Descriptor Size
1611     Streamer.emitInt8(0);
1612   }
1613 
1614   // Code Alignment Factor
1615   Streamer.emitULEB128IntValue(context.getAsmInfo()->getMinInstAlignment());
1616 
1617   // Data Alignment Factor
1618   Streamer.emitSLEB128IntValue(getDataAlignmentFactor(Streamer));
1619 
1620   // Return Address Register
1621   unsigned RAReg = Frame.RAReg;
1622   if (RAReg == static_cast<unsigned>(INT_MAX))
1623     RAReg = MRI->getDwarfRegNum(MRI->getRARegister(), IsEH);
1624 
1625   if (CIEVersion == 1) {
1626     assert(RAReg <= 255 &&
1627            "DWARF 2 encodes return_address_register in one byte");
1628     Streamer.emitInt8(RAReg);
1629   } else {
1630     Streamer.emitULEB128IntValue(RAReg);
1631   }
1632 
1633   // Augmentation Data Length (optional)
1634   unsigned augmentationLength = 0;
1635   if (IsEH) {
1636     if (Frame.Personality) {
1637       // Personality Encoding
1638       augmentationLength += 1;
1639       // Personality
1640       augmentationLength +=
1641           getSizeForEncoding(Streamer, Frame.PersonalityEncoding);
1642     }
1643     if (Frame.Lsda)
1644       augmentationLength += 1;
1645     // Encoding of the FDE pointers
1646     augmentationLength += 1;
1647 
1648     Streamer.emitULEB128IntValue(augmentationLength);
1649 
1650     // Augmentation Data (optional)
1651     if (Frame.Personality) {
1652       // Personality Encoding
1653       emitEncodingByte(Streamer, Frame.PersonalityEncoding);
1654       // Personality
1655       EmitPersonality(Streamer, *Frame.Personality, Frame.PersonalityEncoding);
1656     }
1657 
1658     if (Frame.Lsda)
1659       emitEncodingByte(Streamer, Frame.LsdaEncoding);
1660 
1661     // Encoding of the FDE pointers
1662     emitEncodingByte(Streamer, MOFI->getFDEEncoding());
1663   }
1664 
1665   // Initial Instructions
1666 
1667   const MCAsmInfo *MAI = context.getAsmInfo();
1668   if (!Frame.IsSimple) {
1669     const std::vector<MCCFIInstruction> &Instructions =
1670         MAI->getInitialFrameState();
1671     emitCFIInstructions(Instructions, nullptr);
1672   }
1673 
1674   InitialCFAOffset = CFAOffset;
1675 
1676   // Padding
1677   Streamer.emitValueToAlignment(IsEH ? 4 : MAI->getCodePointerSize());
1678 
1679   Streamer.emitLabel(sectionEnd);
1680   return *sectionStart;
1681 }
1682 
1683 void FrameEmitterImpl::EmitFDE(const MCSymbol &cieStart,
1684                                const MCDwarfFrameInfo &frame,
1685                                bool LastInSection,
1686                                const MCSymbol &SectionStart) {
1687   MCContext &context = Streamer.getContext();
1688   MCSymbol *fdeStart = context.createTempSymbol();
1689   MCSymbol *fdeEnd = context.createTempSymbol();
1690   const MCObjectFileInfo *MOFI = context.getObjectFileInfo();
1691 
1692   CFAOffset = InitialCFAOffset;
1693 
1694   dwarf::DwarfFormat Format = IsEH ? dwarf::DWARF32 : context.getDwarfFormat();
1695   unsigned OffsetSize = dwarf::getDwarfOffsetByteSize(Format);
1696 
1697   if (Format == dwarf::DWARF64)
1698     // DWARF64 mark
1699     Streamer.emitInt32(dwarf::DW_LENGTH_DWARF64);
1700 
1701   // Length
1702   const MCExpr *Length = makeEndMinusStartExpr(context, *fdeStart, *fdeEnd, 0);
1703   emitAbsValue(Streamer, Length, OffsetSize);
1704 
1705   Streamer.emitLabel(fdeStart);
1706 
1707   // CIE Pointer
1708   const MCAsmInfo *asmInfo = context.getAsmInfo();
1709   if (IsEH) {
1710     const MCExpr *offset =
1711         makeEndMinusStartExpr(context, cieStart, *fdeStart, 0);
1712     emitAbsValue(Streamer, offset, OffsetSize);
1713   } else if (!asmInfo->doesDwarfUseRelocationsAcrossSections()) {
1714     const MCExpr *offset =
1715         makeEndMinusStartExpr(context, SectionStart, cieStart, 0);
1716     emitAbsValue(Streamer, offset, OffsetSize);
1717   } else {
1718     Streamer.emitSymbolValue(&cieStart, OffsetSize,
1719                              asmInfo->needsDwarfSectionOffsetDirective());
1720   }
1721 
1722   // PC Begin
1723   unsigned PCEncoding =
1724       IsEH ? MOFI->getFDEEncoding() : (unsigned)dwarf::DW_EH_PE_absptr;
1725   unsigned PCSize = getSizeForEncoding(Streamer, PCEncoding);
1726   emitFDESymbol(Streamer, *frame.Begin, PCEncoding, IsEH);
1727 
1728   // PC Range
1729   const MCExpr *Range =
1730       makeEndMinusStartExpr(context, *frame.Begin, *frame.End, 0);
1731   emitAbsValue(Streamer, Range, PCSize);
1732 
1733   if (IsEH) {
1734     // Augmentation Data Length
1735     unsigned augmentationLength = 0;
1736 
1737     if (frame.Lsda)
1738       augmentationLength += getSizeForEncoding(Streamer, frame.LsdaEncoding);
1739 
1740     Streamer.emitULEB128IntValue(augmentationLength);
1741 
1742     // Augmentation Data
1743     if (frame.Lsda)
1744       emitFDESymbol(Streamer, *frame.Lsda, frame.LsdaEncoding, true);
1745   }
1746 
1747   // Call Frame Instructions
1748   emitCFIInstructions(frame.Instructions, frame.Begin);
1749 
1750   // Padding
1751   // The size of a .eh_frame section has to be a multiple of the alignment
1752   // since a null CIE is interpreted as the end. Old systems overaligned
1753   // .eh_frame, so we do too and account for it in the last FDE.
1754   unsigned Align = LastInSection ? asmInfo->getCodePointerSize() : PCSize;
1755   Streamer.emitValueToAlignment(Align);
1756 
1757   Streamer.emitLabel(fdeEnd);
1758 }
1759 
1760 namespace {
1761 
1762 struct CIEKey {
1763   static const CIEKey getEmptyKey() {
1764     return CIEKey(nullptr, 0, -1, false, false, static_cast<unsigned>(INT_MAX),
1765                   false);
1766   }
1767 
1768   static const CIEKey getTombstoneKey() {
1769     return CIEKey(nullptr, -1, 0, false, false, static_cast<unsigned>(INT_MAX),
1770                   false);
1771   }
1772 
1773   CIEKey(const MCSymbol *Personality, unsigned PersonalityEncoding,
1774          unsigned LSDAEncoding, bool IsSignalFrame, bool IsSimple,
1775          unsigned RAReg, bool IsBKeyFrame)
1776       : Personality(Personality), PersonalityEncoding(PersonalityEncoding),
1777         LsdaEncoding(LSDAEncoding), IsSignalFrame(IsSignalFrame),
1778         IsSimple(IsSimple), RAReg(RAReg), IsBKeyFrame(IsBKeyFrame) {}
1779 
1780   explicit CIEKey(const MCDwarfFrameInfo &Frame)
1781       : Personality(Frame.Personality),
1782         PersonalityEncoding(Frame.PersonalityEncoding),
1783         LsdaEncoding(Frame.LsdaEncoding), IsSignalFrame(Frame.IsSignalFrame),
1784         IsSimple(Frame.IsSimple), RAReg(Frame.RAReg),
1785         IsBKeyFrame(Frame.IsBKeyFrame) {}
1786 
1787   StringRef PersonalityName() const {
1788     if (!Personality)
1789       return StringRef();
1790     return Personality->getName();
1791   }
1792 
1793   bool operator<(const CIEKey &Other) const {
1794     return std::make_tuple(PersonalityName(), PersonalityEncoding, LsdaEncoding,
1795                            IsSignalFrame, IsSimple, RAReg) <
1796            std::make_tuple(Other.PersonalityName(), Other.PersonalityEncoding,
1797                            Other.LsdaEncoding, Other.IsSignalFrame,
1798                            Other.IsSimple, Other.RAReg);
1799   }
1800 
1801   const MCSymbol *Personality;
1802   unsigned PersonalityEncoding;
1803   unsigned LsdaEncoding;
1804   bool IsSignalFrame;
1805   bool IsSimple;
1806   unsigned RAReg;
1807   bool IsBKeyFrame;
1808 };
1809 
1810 } // end anonymous namespace
1811 
1812 namespace llvm {
1813 
1814 template <> struct DenseMapInfo<CIEKey> {
1815   static CIEKey getEmptyKey() { return CIEKey::getEmptyKey(); }
1816   static CIEKey getTombstoneKey() { return CIEKey::getTombstoneKey(); }
1817 
1818   static unsigned getHashValue(const CIEKey &Key) {
1819     return static_cast<unsigned>(hash_combine(
1820         Key.Personality, Key.PersonalityEncoding, Key.LsdaEncoding,
1821         Key.IsSignalFrame, Key.IsSimple, Key.RAReg, Key.IsBKeyFrame));
1822   }
1823 
1824   static bool isEqual(const CIEKey &LHS, const CIEKey &RHS) {
1825     return LHS.Personality == RHS.Personality &&
1826            LHS.PersonalityEncoding == RHS.PersonalityEncoding &&
1827            LHS.LsdaEncoding == RHS.LsdaEncoding &&
1828            LHS.IsSignalFrame == RHS.IsSignalFrame &&
1829            LHS.IsSimple == RHS.IsSimple && LHS.RAReg == RHS.RAReg &&
1830            LHS.IsBKeyFrame == RHS.IsBKeyFrame;
1831   }
1832 };
1833 
1834 } // end namespace llvm
1835 
1836 void MCDwarfFrameEmitter::Emit(MCObjectStreamer &Streamer, MCAsmBackend *MAB,
1837                                bool IsEH) {
1838   Streamer.generateCompactUnwindEncodings(MAB);
1839 
1840   MCContext &Context = Streamer.getContext();
1841   const MCObjectFileInfo *MOFI = Context.getObjectFileInfo();
1842   const MCAsmInfo *AsmInfo = Context.getAsmInfo();
1843   FrameEmitterImpl Emitter(IsEH, Streamer);
1844   ArrayRef<MCDwarfFrameInfo> FrameArray = Streamer.getDwarfFrameInfos();
1845 
1846   // Emit the compact unwind info if available.
1847   bool NeedsEHFrameSection = !MOFI->getSupportsCompactUnwindWithoutEHFrame();
1848   if (IsEH && MOFI->getCompactUnwindSection()) {
1849     bool SectionEmitted = false;
1850     for (const MCDwarfFrameInfo &Frame : FrameArray) {
1851       if (Frame.CompactUnwindEncoding == 0) continue;
1852       if (!SectionEmitted) {
1853         Streamer.SwitchSection(MOFI->getCompactUnwindSection());
1854         Streamer.emitValueToAlignment(AsmInfo->getCodePointerSize());
1855         SectionEmitted = true;
1856       }
1857       NeedsEHFrameSection |=
1858         Frame.CompactUnwindEncoding ==
1859           MOFI->getCompactUnwindDwarfEHFrameOnly();
1860       Emitter.EmitCompactUnwind(Frame);
1861     }
1862   }
1863 
1864   if (!NeedsEHFrameSection) return;
1865 
1866   MCSection &Section =
1867       IsEH ? *const_cast<MCObjectFileInfo *>(MOFI)->getEHFrameSection()
1868            : *MOFI->getDwarfFrameSection();
1869 
1870   Streamer.SwitchSection(&Section);
1871   MCSymbol *SectionStart = Context.createTempSymbol();
1872   Streamer.emitLabel(SectionStart);
1873 
1874   DenseMap<CIEKey, const MCSymbol *> CIEStarts;
1875 
1876   const MCSymbol *DummyDebugKey = nullptr;
1877   bool CanOmitDwarf = MOFI->getOmitDwarfIfHaveCompactUnwind();
1878   // Sort the FDEs by their corresponding CIE before we emit them.
1879   // This isn't technically necessary according to the DWARF standard,
1880   // but the Android libunwindstack rejects eh_frame sections where
1881   // an FDE refers to a CIE other than the closest previous CIE.
1882   std::vector<MCDwarfFrameInfo> FrameArrayX(FrameArray.begin(), FrameArray.end());
1883   llvm::stable_sort(FrameArrayX,
1884                     [](const MCDwarfFrameInfo &X, const MCDwarfFrameInfo &Y) {
1885                       return CIEKey(X) < CIEKey(Y);
1886                     });
1887   for (auto I = FrameArrayX.begin(), E = FrameArrayX.end(); I != E;) {
1888     const MCDwarfFrameInfo &Frame = *I;
1889     ++I;
1890     if (CanOmitDwarf && Frame.CompactUnwindEncoding !=
1891           MOFI->getCompactUnwindDwarfEHFrameOnly())
1892       // Don't generate an EH frame if we don't need one. I.e., it's taken care
1893       // of by the compact unwind encoding.
1894       continue;
1895 
1896     CIEKey Key(Frame);
1897     const MCSymbol *&CIEStart = IsEH ? CIEStarts[Key] : DummyDebugKey;
1898     if (!CIEStart)
1899       CIEStart = &Emitter.EmitCIE(Frame);
1900 
1901     Emitter.EmitFDE(*CIEStart, Frame, I == E, *SectionStart);
1902   }
1903 }
1904 
1905 void MCDwarfFrameEmitter::EmitAdvanceLoc(MCObjectStreamer &Streamer,
1906                                          uint64_t AddrDelta) {
1907   MCContext &Context = Streamer.getContext();
1908   SmallString<256> Tmp;
1909   raw_svector_ostream OS(Tmp);
1910   MCDwarfFrameEmitter::EncodeAdvanceLoc(Context, AddrDelta, OS);
1911   Streamer.emitBytes(OS.str());
1912 }
1913 
1914 void MCDwarfFrameEmitter::EncodeAdvanceLoc(MCContext &Context,
1915                                            uint64_t AddrDelta,
1916                                            raw_ostream &OS) {
1917   // Scale the address delta by the minimum instruction length.
1918   AddrDelta = ScaleAddrDelta(Context, AddrDelta);
1919   if (AddrDelta == 0)
1920     return;
1921 
1922   support::endianness E =
1923       Context.getAsmInfo()->isLittleEndian() ? support::little : support::big;
1924 
1925   if (isUIntN(6, AddrDelta)) {
1926     uint8_t Opcode = dwarf::DW_CFA_advance_loc | AddrDelta;
1927     OS << Opcode;
1928   } else if (isUInt<8>(AddrDelta)) {
1929     OS << uint8_t(dwarf::DW_CFA_advance_loc1);
1930     OS << uint8_t(AddrDelta);
1931   } else if (isUInt<16>(AddrDelta)) {
1932     OS << uint8_t(dwarf::DW_CFA_advance_loc2);
1933     support::endian::write<uint16_t>(OS, AddrDelta, E);
1934   } else {
1935     assert(isUInt<32>(AddrDelta));
1936     OS << uint8_t(dwarf::DW_CFA_advance_loc4);
1937     support::endian::write<uint32_t>(OS, AddrDelta, E);
1938   }
1939 }
1940