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