OSDN Git Service

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