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