There are two reasons why we might want to use
[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/MCAsmInfo.h"
11 #include "llvm/MC/MCDwarf.h"
12 #include "llvm/MC/MCAssembler.h"
13 #include "llvm/MC/MCStreamer.h"
14 #include "llvm/MC/MCSymbol.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCContext.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/raw_ostream.h"
21 #include "llvm/Target/TargetAsmBackend.h"
22 using namespace llvm;
23
24 // Given a special op, return the address skip amount (in units of
25 // DWARF2_LINE_MIN_INSN_LENGTH.
26 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
27
28 // The maximum address skip amount that can be encoded with a special op.
29 #define MAX_SPECIAL_ADDR_DELTA          SPECIAL_ADDR(255)
30
31 // First special line opcode - leave room for the standard opcodes.
32 // Note: If you want to change this, you'll have to update the
33 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().  
34 #define DWARF2_LINE_OPCODE_BASE         13
35
36 // Minimum line offset in a special line info. opcode.  This value
37 // was chosen to give a reasonable range of values.
38 #define DWARF2_LINE_BASE                -5
39
40 // Range of line offsets in a special line info. opcode.
41 # define DWARF2_LINE_RANGE              14
42
43 // Define the architecture-dependent minimum instruction length (in bytes).
44 // This value should be rather too small than too big.
45 # define DWARF2_LINE_MIN_INSN_LENGTH    1
46
47 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
48 // this routine is a nop and will be optimized away.
49 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta)
50 {
51   if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
52     return AddrDelta;
53   if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
54     // TODO: report this error, but really only once.
55     ;
56   }
57   return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
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   // Get the MCLineSection for this section, if one does not exist for this
84   // section create it.
85   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
86     MCOS->getContext().getMCLineSections();
87   MCLineSection *LineSection = MCLineSections.lookup(Section);
88   if (!LineSection) {
89     // Create a new MCLineSection.  This will be deleted after the dwarf line
90     // table is created using it by iterating through the MCLineSections
91     // DenseMap.
92     LineSection = new MCLineSection;
93     // Save a pointer to the new LineSection into the MCLineSections DenseMap.
94     MCOS->getContext().addMCLineSection(Section, LineSection);
95   }
96
97   // Add the line entry to this section's entries.
98   LineSection->addLineEntry(LineEntry);
99 }
100
101 //
102 // This helper routine returns an expression of End - Start + IntVal .
103 // 
104 static inline const MCExpr *MakeStartMinusEndExpr(MCStreamer *MCOS,
105                                                   MCSymbol *Start,
106                                                   MCSymbol *End, int IntVal) {
107   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
108   const MCExpr *Res =
109     MCSymbolRefExpr::Create(End, Variant, MCOS->getContext());
110   const MCExpr *RHS =
111     MCSymbolRefExpr::Create(Start, Variant, MCOS->getContext());
112   const MCExpr *Res1 =
113     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS->getContext());
114   const MCExpr *Res2 =
115     MCConstantExpr::Create(IntVal, MCOS->getContext());
116   const MCExpr *Res3 =
117     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS->getContext());
118   return Res3;
119 }
120
121 //
122 // This emits the Dwarf line table for the specified section from the entries
123 // in the LineSection.
124 //
125 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
126                                       const MCSection *Section,
127                                       const MCLineSection *LineSection,
128                                       const MCSection *DwarfLineSection) {
129   unsigned FileNum = 1;
130   unsigned LastLine = 1;
131   unsigned Column = 0;
132   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
133   unsigned Isa = 0;
134   MCSymbol *LastLabel = NULL;
135
136   // Loop through each MCLineEntry and encode the dwarf line number table.
137   for (MCLineSection::const_iterator
138          it = LineSection->getMCLineEntries()->begin(),
139          ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
140
141     if (FileNum != it->getFileNum()) {
142       FileNum = it->getFileNum();
143       MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
144       MCOS->EmitULEB128IntValue(FileNum);
145     }
146     if (Column != it->getColumn()) {
147       Column = it->getColumn();
148       MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
149       MCOS->EmitULEB128IntValue(Column);
150     }
151     if (Isa != it->getIsa()) {
152       Isa = it->getIsa();
153       MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
154       MCOS->EmitULEB128IntValue(Isa);
155     }
156     if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
157       Flags = it->getFlags();
158       MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
159     }
160     if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
161       MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
162     if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
163       MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
164     if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
165       MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
166
167     int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
168     MCSymbol *Label = it->getLabel();
169
170     // At this point we want to emit/create the sequence to encode the delta in
171     // line numbers and the increment of the address from the previous Label
172     // and the current Label.
173     MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label);
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   MCOS->SwitchSection(Section);
187   // Create a symbol at the end of the section.
188   MCSymbol *SectionEnd = MCOS->getContext().CreateTempSymbol();
189   // Set the value of the symbol, as we are at the end of the section.
190   MCOS->EmitLabel(SectionEnd);
191
192   // Switch back the the dwarf line section.
193   MCOS->SwitchSection(DwarfLineSection);
194
195   MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd);
196 }
197
198 //
199 // This emits the Dwarf file and the line tables.
200 //
201 void MCDwarfFileTable::Emit(MCStreamer *MCOS,
202                             const MCSection *DwarfLineSection) {
203   // Switch to the section where the table will be emitted into.
204   MCOS->SwitchSection(DwarfLineSection);
205
206   // Create a symbol at the beginning of this section.
207   MCSymbol *LineStartSym = MCOS->getContext().CreateTempSymbol();
208   // Set the value of the symbol, as we are at the start of the section.
209   MCOS->EmitLabel(LineStartSym);
210
211   // Create a symbol for the end of the section (to be set when we get there).
212   MCSymbol *LineEndSym = MCOS->getContext().CreateTempSymbol();
213
214   // The first 4 bytes is the total length of the information for this
215   // compilation unit (not including these 4 bytes for the length).
216   // FIXME: We create the dummy TotalLength variable because LineEndSym points
217   // to the end of the section and the darwin assembler doesn't consider that
218   // difference an assembly time constant. It might be better for this to be
219   // proected by a flag.
220   MCSymbol *TotalLength = MCOS->getContext().CreateTempSymbol();
221   MCOS->EmitAssignment(TotalLength,
222                        MakeStartMinusEndExpr(MCOS, LineStartSym, LineEndSym,
223                                              4));
224   MCOS->EmitSymbolValue(TotalLength, 4, 0);
225
226   // Next 2 bytes is the Version, which is Dwarf 2.
227   MCOS->EmitIntValue(2, 2);
228
229   // Create a symbol for the end of the prologue (to be set when we get there).
230   MCSymbol *ProEndSym = MCOS->getContext().CreateTempSymbol(); // Lprologue_end
231
232   // Length of the prologue, is the next 4 bytes.  Which is the start of the
233   // section to the end of the prologue.  Not including the 4 bytes for the
234   // total length, the 2 bytes for the version, and these 4 bytes for the
235   // length of the prologue.
236   MCOS->EmitValue(MakeStartMinusEndExpr(MCOS, LineStartSym, ProEndSym,
237                                         (4 + 2 + 4)),
238                   4, 0);
239
240   // Parameters of the state machine, are next.
241   MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
242   MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
243   MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
244   MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
245   MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
246
247   // Standard opcode lengths
248   MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
249   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
250   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
251   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
252   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
253   MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
254   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
255   MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
256   MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
257   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
258   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
259   MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
260
261   // Put out the directory and file tables.
262
263   // First the directory table.
264   const std::vector<StringRef> &MCDwarfDirs =
265     MCOS->getContext().getMCDwarfDirs();
266   for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
267     MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
268     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
269   }
270   MCOS->EmitIntValue(0, 1); // Terminate the directory list
271
272   // Second the file table.
273   const std::vector<MCDwarfFile *> &MCDwarfFiles =
274     MCOS->getContext().getMCDwarfFiles();
275   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
276     MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
277     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
278     // the Directory num
279     MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
280     MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
281     MCOS->EmitIntValue(0, 1); // filesize (always 0)
282   }
283   MCOS->EmitIntValue(0, 1); // Terminate the file list
284
285   // This is the end of the prologue, so set the value of the symbol at the
286   // end of the prologue (that was used in a previous expression).
287   MCOS->EmitLabel(ProEndSym);
288
289   // Put out the line tables.
290   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
291     MCOS->getContext().getMCLineSections();
292   const std::vector<const MCSection *> &MCLineSectionOrder =
293     MCOS->getContext().getMCLineSectionOrder();
294   for (std::vector<const MCSection*>::const_iterator it =
295         MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
296        ++it) {
297     const MCSection *Sec = *it;
298     const MCLineSection *Line = MCLineSections.lookup(Sec);
299     EmitDwarfLineTable(MCOS, Sec, Line, DwarfLineSection);
300
301     // Now delete the MCLineSections that were created in MCLineEntry::Make()
302     // and used to emit the line table.
303     delete Line;
304   }
305
306   if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
307       && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
308     // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
309     // it requires:  
310     // total_length >= prologue_length + 10
311     // We are 4 bytes short, since we have total_length = 51 and
312     // prologue_length = 45
313
314     // The regular end_sequence should be sufficient.
315     MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
316   }
317
318   // This is the end of the section, so set the value of the symbol at the end
319   // of this section (that was used in a previous expression).
320   MCOS->EmitLabel(LineEndSym);
321 }
322
323 /// Utility function to compute the size of the encoding.
324 uint64_t MCDwarfLineAddr::ComputeSize(int64_t LineDelta, uint64_t AddrDelta) {
325   SmallString<256> Tmp;
326   raw_svector_ostream OS(Tmp);
327   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
328   return OS.GetNumBytesInBuffer();
329 }
330
331 /// Utility function to write the encoding to an object writer.
332 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
333                             uint64_t AddrDelta) {
334   SmallString<256> Tmp;
335   raw_svector_ostream OS(Tmp);
336   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
337   OW->WriteBytes(OS.str());
338 }
339
340 /// Utility function to emit the encoding to a streamer.
341 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
342                            uint64_t AddrDelta) {
343   SmallString<256> Tmp;
344   raw_svector_ostream OS(Tmp);
345   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
346   MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
347 }
348
349 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
350 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
351                              raw_ostream &OS) {
352   uint64_t Temp, Opcode;
353   bool NeedCopy = false;
354
355   // Scale the address delta by the minimum instruction length.
356   AddrDelta = ScaleAddrDelta(AddrDelta);
357
358   // A LineDelta of INT64_MAX is a signal that this is actually a
359   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 
360   // end_sequence to emit the matrix entry.
361   if (LineDelta == INT64_MAX) {
362     if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
363       OS << char(dwarf::DW_LNS_const_add_pc);
364     else {
365       OS << char(dwarf::DW_LNS_advance_pc);
366       SmallString<32> Tmp;
367       raw_svector_ostream OSE(Tmp);
368       MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
369       OS << OSE.str();
370     }
371     OS << char(dwarf::DW_LNS_extended_op);
372     OS << char(1);
373     OS << char(dwarf::DW_LNE_end_sequence);
374     return;
375   }
376
377   // Bias the line delta by the base.
378   Temp = LineDelta - DWARF2_LINE_BASE;
379
380   // If the line increment is out of range of a special opcode, we must encode
381   // it with DW_LNS_advance_line.
382   if (Temp >= DWARF2_LINE_RANGE) {
383     OS << char(dwarf::DW_LNS_advance_line);
384     SmallString<32> Tmp;
385     raw_svector_ostream OSE(Tmp);
386     MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
387     OS << OSE.str();
388
389     LineDelta = 0;
390     Temp = 0 - DWARF2_LINE_BASE;
391     NeedCopy = true;
392   }
393
394   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
395   if (LineDelta == 0 && AddrDelta == 0) {
396     OS << char(dwarf::DW_LNS_copy);
397     return;
398   }
399
400   // Bias the opcode by the special opcode base.
401   Temp += DWARF2_LINE_OPCODE_BASE;
402
403   // Avoid overflow when addr_delta is large.
404   if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
405     // Try using a special opcode.
406     Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
407     if (Opcode <= 255) {
408       OS << char(Opcode);
409       return;
410     }
411
412     // Try using DW_LNS_const_add_pc followed by special op.
413     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
414     if (Opcode <= 255) {
415       OS << char(dwarf::DW_LNS_const_add_pc);
416       OS << char(Opcode);
417       return;
418     }
419   }
420
421   // Otherwise use DW_LNS_advance_pc.
422   OS << char(dwarf::DW_LNS_advance_pc);
423   SmallString<32> Tmp;
424   raw_svector_ostream OSE(Tmp);
425   MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
426   OS << OSE.str();
427
428   if (NeedCopy)
429     OS << char(dwarf::DW_LNS_copy);
430   else
431     OS << char(Temp);
432 }
433
434 void MCDwarfFile::print(raw_ostream &OS) const {
435   OS << '"' << getName() << '"';
436 }
437
438 void MCDwarfFile::dump() const {
439   print(dbgs());
440 }
441