Revert my previous patch to make the valgrind bots happy.
[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(const MCStreamer &MCOS,
105                                                   const MCSymbol &Start,
106                                                   const MCSymbol &End,
107                                                   int IntVal) {
108   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
109   const MCExpr *Res =
110     MCSymbolRefExpr::Create(&End, Variant, MCOS.getContext());
111   const MCExpr *RHS =
112     MCSymbolRefExpr::Create(&Start, Variant, MCOS.getContext());
113   const MCExpr *Res1 =
114     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS.getContext());
115   const MCExpr *Res2 =
116     MCConstantExpr::Create(IntVal, MCOS.getContext());
117   const MCExpr *Res3 =
118     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS.getContext());
119   return Res3;
120 }
121
122 //
123 // This emits the Dwarf line table for the specified section from the entries
124 // in the LineSection.
125 //
126 static inline void EmitDwarfLineTable(MCStreamer *MCOS,
127                                       const MCSection *Section,
128                                       const MCLineSection *LineSection,
129                                       const MCSection *DwarfLineSection) {
130   unsigned FileNum = 1;
131   unsigned LastLine = 1;
132   unsigned Column = 0;
133   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
134   unsigned Isa = 0;
135   MCSymbol *LastLabel = NULL;
136
137   // Loop through each MCLineEntry and encode the dwarf line number table.
138   for (MCLineSection::const_iterator
139          it = LineSection->getMCLineEntries()->begin(),
140          ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
141
142     if (FileNum != it->getFileNum()) {
143       FileNum = it->getFileNum();
144       MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
145       MCOS->EmitULEB128IntValue(FileNum);
146     }
147     if (Column != it->getColumn()) {
148       Column = it->getColumn();
149       MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
150       MCOS->EmitULEB128IntValue(Column);
151     }
152     if (Isa != it->getIsa()) {
153       Isa = it->getIsa();
154       MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
155       MCOS->EmitULEB128IntValue(Isa);
156     }
157     if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
158       Flags = it->getFlags();
159       MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
160     }
161     if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
162       MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
163     if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
164       MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
165     if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
166       MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
167
168     int64_t LineDelta = static_cast<int64_t>(it->getLine()) - LastLine;
169     MCSymbol *Label = it->getLabel();
170
171     // At this point we want to emit/create the sequence to encode the delta in
172     // line numbers and the increment of the address from the previous Label
173     // and the current Label.
174     MCOS->EmitDwarfAdvanceLineAddr(LineDelta, LastLabel, Label);
175
176     LastLine = it->getLine();
177     LastLabel = Label;
178   }
179
180   // Emit a DW_LNE_end_sequence for the end of the section.
181   // Using the pointer Section create a temporary label at the end of the
182   // section and use that and the LastLabel to compute the address delta
183   // and use INT64_MAX as the line delta which is the signal that this is
184   // actually a DW_LNE_end_sequence.
185
186   // Switch to the section to be able to create a symbol at its end.
187   MCOS->SwitchSection(Section);
188   // Create a symbol at the end of the section.
189   MCSymbol *SectionEnd = MCOS->getContext().CreateTempSymbol();
190   // Set the value of the symbol, as we are at the end of the section.
191   MCOS->EmitLabel(SectionEnd);
192
193   // Switch back the the dwarf line section.
194   MCOS->SwitchSection(DwarfLineSection);
195
196   MCOS->EmitDwarfAdvanceLineAddr(INT64_MAX, LastLabel, SectionEnd);
197 }
198
199 //
200 // This emits the Dwarf file and the line tables.
201 //
202 void MCDwarfFileTable::Emit(MCStreamer *MCOS,
203                             const MCSection *DwarfLineSection) {
204   // Switch to the section where the table will be emitted into.
205   MCOS->SwitchSection(DwarfLineSection);
206
207   // Create a symbol at the beginning of this section.
208   MCSymbol *LineStartSym = MCOS->getContext().CreateTempSymbol();
209   // Set the value of the symbol, as we are at the start of the section.
210   MCOS->EmitLabel(LineStartSym);
211
212   // Create a symbol for the end of the section (to be set when we get there).
213   MCSymbol *LineEndSym = MCOS->getContext().CreateTempSymbol();
214
215   // The first 4 bytes is the total length of the information for this
216   // compilation unit (not including these 4 bytes for the length).
217   MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *LineEndSym,4),
218                      4);
219
220   // Next 2 bytes is the Version, which is Dwarf 2.
221   MCOS->EmitIntValue(2, 2);
222
223   // Create a symbol for the end of the prologue (to be set when we get there).
224   MCSymbol *ProEndSym = MCOS->getContext().CreateTempSymbol(); // Lprologue_end
225
226   // Length of the prologue, is the next 4 bytes.  Which is the start of the
227   // section to the end of the prologue.  Not including the 4 bytes for the
228   // total length, the 2 bytes for the version, and these 4 bytes for the
229   // length of the prologue.
230   MCOS->EmitAbsValue(MakeStartMinusEndExpr(*MCOS, *LineStartSym, *ProEndSym,
231                                         (4 + 2 + 4)),
232                   4, 0);
233
234   // Parameters of the state machine, are next.
235   MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
236   MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
237   MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
238   MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
239   MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
240
241   // Standard opcode lengths
242   MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
243   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
244   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
245   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
246   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
247   MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
248   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
249   MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
250   MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
251   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
252   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
253   MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
254
255   // Put out the directory and file tables.
256
257   // First the directory table.
258   const std::vector<StringRef> &MCDwarfDirs =
259     MCOS->getContext().getMCDwarfDirs();
260   for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
261     MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
262     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
263   }
264   MCOS->EmitIntValue(0, 1); // Terminate the directory list
265
266   // Second the file table.
267   const std::vector<MCDwarfFile *> &MCDwarfFiles =
268     MCOS->getContext().getMCDwarfFiles();
269   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
270     MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
271     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
272     // the Directory num
273     MCOS->EmitULEB128IntValue(MCDwarfFiles[i]->getDirIndex());
274     MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
275     MCOS->EmitIntValue(0, 1); // filesize (always 0)
276   }
277   MCOS->EmitIntValue(0, 1); // Terminate the file list
278
279   // This is the end of the prologue, so set the value of the symbol at the
280   // end of the prologue (that was used in a previous expression).
281   MCOS->EmitLabel(ProEndSym);
282
283   // Put out the line tables.
284   const DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
285     MCOS->getContext().getMCLineSections();
286   const std::vector<const MCSection *> &MCLineSectionOrder =
287     MCOS->getContext().getMCLineSectionOrder();
288   for (std::vector<const MCSection*>::const_iterator it =
289         MCLineSectionOrder.begin(), ie = MCLineSectionOrder.end(); it != ie;
290        ++it) {
291     const MCSection *Sec = *it;
292     const MCLineSection *Line = MCLineSections.lookup(Sec);
293     EmitDwarfLineTable(MCOS, Sec, Line, DwarfLineSection);
294
295     // Now delete the MCLineSections that were created in MCLineEntry::Make()
296     // and used to emit the line table.
297     delete Line;
298   }
299
300   if (MCOS->getContext().getAsmInfo().getLinkerRequiresNonEmptyDwarfLines()
301       && MCLineSectionOrder.begin() == MCLineSectionOrder.end()) {
302     // The darwin9 linker has a bug (see PR8715). For for 32-bit architectures
303     // it requires:  
304     // total_length >= prologue_length + 10
305     // We are 4 bytes short, since we have total_length = 51 and
306     // prologue_length = 45
307
308     // The regular end_sequence should be sufficient.
309     MCDwarfLineAddr::Emit(MCOS, INT64_MAX, 0);
310   }
311
312   // This is the end of the section, so set the value of the symbol at the end
313   // of this section (that was used in a previous expression).
314   MCOS->EmitLabel(LineEndSym);
315 }
316
317 /// Utility function to write the encoding to an object writer.
318 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
319                             uint64_t AddrDelta) {
320   SmallString<256> Tmp;
321   raw_svector_ostream OS(Tmp);
322   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
323   OW->WriteBytes(OS.str());
324 }
325
326 /// Utility function to emit the encoding to a streamer.
327 void MCDwarfLineAddr::Emit(MCStreamer *MCOS, int64_t LineDelta,
328                            uint64_t AddrDelta) {
329   SmallString<256> Tmp;
330   raw_svector_ostream OS(Tmp);
331   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
332   MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
333 }
334
335 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
336 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
337                              raw_ostream &OS) {
338   uint64_t Temp, Opcode;
339   bool NeedCopy = false;
340
341   // Scale the address delta by the minimum instruction length.
342   AddrDelta = ScaleAddrDelta(AddrDelta);
343
344   // A LineDelta of INT64_MAX is a signal that this is actually a
345   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 
346   // end_sequence to emit the matrix entry.
347   if (LineDelta == INT64_MAX) {
348     if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
349       OS << char(dwarf::DW_LNS_const_add_pc);
350     else {
351       OS << char(dwarf::DW_LNS_advance_pc);
352       SmallString<32> Tmp;
353       raw_svector_ostream OSE(Tmp);
354       MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
355       OS << OSE.str();
356     }
357     OS << char(dwarf::DW_LNS_extended_op);
358     OS << char(1);
359     OS << char(dwarf::DW_LNE_end_sequence);
360     return;
361   }
362
363   // Bias the line delta by the base.
364   Temp = LineDelta - DWARF2_LINE_BASE;
365
366   // If the line increment is out of range of a special opcode, we must encode
367   // it with DW_LNS_advance_line.
368   if (Temp >= DWARF2_LINE_RANGE) {
369     OS << char(dwarf::DW_LNS_advance_line);
370     SmallString<32> Tmp;
371     raw_svector_ostream OSE(Tmp);
372     MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
373     OS << OSE.str();
374
375     LineDelta = 0;
376     Temp = 0 - DWARF2_LINE_BASE;
377     NeedCopy = true;
378   }
379
380   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
381   if (LineDelta == 0 && AddrDelta == 0) {
382     OS << char(dwarf::DW_LNS_copy);
383     return;
384   }
385
386   // Bias the opcode by the special opcode base.
387   Temp += DWARF2_LINE_OPCODE_BASE;
388
389   // Avoid overflow when addr_delta is large.
390   if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
391     // Try using a special opcode.
392     Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
393     if (Opcode <= 255) {
394       OS << char(Opcode);
395       return;
396     }
397
398     // Try using DW_LNS_const_add_pc followed by special op.
399     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
400     if (Opcode <= 255) {
401       OS << char(dwarf::DW_LNS_const_add_pc);
402       OS << char(Opcode);
403       return;
404     }
405   }
406
407   // Otherwise use DW_LNS_advance_pc.
408   OS << char(dwarf::DW_LNS_advance_pc);
409   SmallString<32> Tmp;
410   raw_svector_ostream OSE(Tmp);
411   MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
412   OS << OSE.str();
413
414   if (NeedCopy)
415     OS << char(dwarf::DW_LNS_copy);
416   else
417     OS << char(Temp);
418 }
419
420 void MCDwarfFile::print(raw_ostream &OS) const {
421   OS << '"' << getName() << '"';
422 }
423
424 void MCDwarfFile::dump() const {
425   print(dbgs());
426 }
427