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