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