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