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