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