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