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