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