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