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