Incorporate suggestions by Daniel Dunbar after his review. Thanks Daniel!
[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/MCAssembler.h"
12 #include "llvm/MC/MCSymbol.h"
13 #include "llvm/MC/MCExpr.h"
14 #include "llvm/MC/MCContext.h"
15 #include "llvm/MC/MCObjectWriter.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include "llvm/Target/TargetAsmBackend.h"
20 using namespace llvm;
21
22 // Given a special op, return the address skip amount (in units of
23 // DWARF2_LINE_MIN_INSN_LENGTH.
24 #define SPECIAL_ADDR(op) (((op) - DWARF2_LINE_OPCODE_BASE)/DWARF2_LINE_RANGE)
25
26 // The maximum address skip amount that can be encoded with a special op.
27 #define MAX_SPECIAL_ADDR_DELTA          SPECIAL_ADDR(255)
28
29 // First special line opcode - leave room for the standard opcodes.
30 // Note: If you want to change this, you'll have to update the
31 // "standard_opcode_lengths" table that is emitted in DwarfFileTable::Emit().  
32 #define DWARF2_LINE_OPCODE_BASE         13
33
34 // Minimum line offset in a special line info. opcode.  This value
35 // was chosen to give a reasonable range of values.
36 #define DWARF2_LINE_BASE                -5
37
38 // Range of line offsets in a special line info. opcode.
39 # define DWARF2_LINE_RANGE              14
40
41 // Define the architecture-dependent minimum instruction length (in bytes).
42 // This value should be rather too small than too big.
43 # define DWARF2_LINE_MIN_INSN_LENGTH    1
44
45 // Note: when DWARF2_LINE_MIN_INSN_LENGTH == 1 which is the current setting,
46 // this routine is a nop and will be optimized away.
47 static inline uint64_t ScaleAddrDelta(uint64_t AddrDelta)
48 {
49   if (DWARF2_LINE_MIN_INSN_LENGTH == 1)
50     return AddrDelta;
51   if (AddrDelta % DWARF2_LINE_MIN_INSN_LENGTH != 0) {
52     // TODO: report this error, but really only once.
53     ;
54   }
55   return AddrDelta / DWARF2_LINE_MIN_INSN_LENGTH;
56 }
57
58 //
59 // This is called when an instruction is assembled into the specified section
60 // and if there is information from the last .loc directive that has yet to have
61 // a line entry made for it is made.
62 //
63 void MCLineEntry::Make(MCObjectStreamer *MCOS, const MCSection *Section) {
64   if (!MCOS->getContext().getDwarfLocSeen())
65     return;
66
67   // Create a symbol at in the current section for use in the line entry.
68   MCSymbol *LineSym = MCOS->getContext().CreateTempSymbol();
69   // Set the value of the symbol to use for the MCLineEntry.
70   MCOS->EmitLabel(LineSym);
71
72   // Get the current .loc info saved in the context.
73   const MCDwarfLoc &DwarfLoc = MCOS->getContext().getCurrentDwarfLoc();
74
75   // Create a (local) line entry with the symbol and the current .loc info.
76   MCLineEntry LineEntry(LineSym, DwarfLoc);
77
78   // clear DwarfLocSeen saying the current .loc info is now used.
79   MCOS->getContext().ClearDwarfLocSeen();
80
81   // Get the MCLineSection for this section, if one does not exist for this
82   // section create it.
83   DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
84     MCOS->getContext().getMCLineSections();
85   MCLineSection *LineSection = MCLineSections[Section];
86   if (!LineSection) {
87     // Create a new MCLineSection.  This will be deleted after the dwarf line
88     // table is created using it by iterating through the MCLineSections
89     // DenseMap.
90     LineSection = new MCLineSection;
91     // Save a pointer to the new LineSection into the MCLineSections DenseMap.
92     MCLineSections[Section] = LineSection;
93   }
94
95   // Add the line entry to this section's entries.
96   LineSection->addLineEntry(LineEntry);
97 }
98
99 //
100 // This helper routine returns an expression of End - Start + IntVal .
101 // 
102 static inline const MCExpr *MakeStartMinusEndExpr(MCObjectStreamer *MCOS,
103                                                   MCSymbol *Start,
104                                                   MCSymbol *End, int IntVal) {
105   MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
106   const MCExpr *Res =
107     MCSymbolRefExpr::Create(End, Variant, MCOS->getContext());
108   const MCExpr *RHS =
109     MCSymbolRefExpr::Create(Start, Variant, MCOS->getContext());
110   const MCExpr *Res1 =
111     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res, RHS, MCOS->getContext());
112   const MCExpr *Res2 =
113     MCConstantExpr::Create(IntVal, MCOS->getContext());
114   const MCExpr *Res3 =
115     MCBinaryExpr::Create(MCBinaryExpr::Sub, Res1, Res2, MCOS->getContext());
116   return Res3;
117 }
118
119 // 
120 // This emits an "absolute" address used in the start of a dwarf line number
121 // table.  This will result in a relocatation entry for the address.
122 //
123 static inline void EmitDwarfSetAddress(MCObjectStreamer *MCOS,
124                                        MCSymbol *Symbol) {
125   MCOS->EmitIntValue(dwarf::DW_LNS_extended_op, 1);
126
127   int sizeof_address = MCOS->getAssembler().getBackend().getPointerSize();
128   MCOS->EmitULEB128Value(sizeof_address + 1);
129
130   MCOS->EmitIntValue(dwarf::DW_LNE_set_address, 1);
131   MCOS->EmitSymbolValue(Symbol, sizeof_address);
132 }
133
134 //
135 // This emits the Dwarf line table for the specified section from the entries
136 // in the LineSection.
137 //
138 static inline bool EmitDwarfLineTable(MCObjectStreamer *MCOS,
139                                       const MCSection *Section,
140                                       MCLineSection *LineSection,
141                                       const MCSection *DwarfLineSection) {
142   unsigned FileNum = 1;
143   unsigned LastLine = 1;
144   unsigned Column = 0;
145   unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0;
146   unsigned Isa = 0;
147   bool EmittedLineTable = false;
148   MCSymbol *LastLabel = NULL;
149   MCSectionData &DLS =
150     MCOS->getAssembler().getOrCreateSectionData(*DwarfLineSection);
151
152   // Loop through each MCLineEntry and encode the dwarf line number table.
153   for (MCLineSection::iterator
154          it = LineSection->getMCLineEntries()->begin(),
155          ie = LineSection->getMCLineEntries()->end(); it != ie; ++it) {
156
157     if (FileNum != it->getFileNum()) {
158       FileNum = it->getFileNum();
159       MCOS->EmitIntValue(dwarf::DW_LNS_set_file, 1);
160       MCOS->EmitULEB128Value(FileNum);
161     }
162     if (Column != it->getColumn()) {
163       Column = it->getColumn();
164       MCOS->EmitIntValue(dwarf::DW_LNS_set_column, 1);
165       MCOS->EmitULEB128Value(Column);
166     }
167     if (Isa != it->getIsa()) {
168       Isa = it->getIsa();
169       MCOS->EmitIntValue(dwarf::DW_LNS_set_isa, 1);
170       MCOS->EmitULEB128Value(Isa);
171     }
172     if ((it->getFlags() ^ Flags) & DWARF2_FLAG_IS_STMT) {
173       Flags = it->getFlags();
174       MCOS->EmitIntValue(dwarf::DW_LNS_negate_stmt, 1);
175     }
176     if (it->getFlags() & DWARF2_FLAG_BASIC_BLOCK)
177       MCOS->EmitIntValue(dwarf::DW_LNS_set_basic_block, 1);
178     if (it->getFlags() & DWARF2_FLAG_PROLOGUE_END)
179       MCOS->EmitIntValue(dwarf::DW_LNS_set_prologue_end, 1);
180     if (it->getFlags() & DWARF2_FLAG_EPILOGUE_BEGIN)
181       MCOS->EmitIntValue(dwarf::DW_LNS_set_epilogue_begin, 1);
182
183     int64_t LineDelta = it->getLine() - LastLine;
184     MCSymbol *Label = it->getLabel();
185
186     // At this point we want to emit/create the sequence to encode the delta in
187     // line numbers and the increment of the address from the previous Label
188     // and the current Label.
189     if (LastLabel == NULL) {
190       // emit the sequence to set the address
191       EmitDwarfSetAddress(MCOS, Label);
192       // emit the sequence for the LineDelta (from 1) and a zero address delta.
193       MCDwarfLineAddr::Emit(MCOS, LineDelta, 0);
194     }
195     else {
196       // Create an expression for the address delta from the LastLabel and
197       // this Label (plus 0).
198       const MCExpr *AddrDelta = MakeStartMinusEndExpr(MCOS, LastLabel, Label,0);
199       // Create a Dwarf Line fragment for the LineDelta and AddrDelta.
200       new MCDwarfLineAddrFragment(LineDelta, *AddrDelta, &DLS);
201     }
202
203     LastLine = it->getLine();
204     LastLabel = Label;
205     EmittedLineTable = true;
206   }
207
208   // Emit a DW_LNE_end_sequence for the end of the section.
209   // Using the pointer Section create a temporary label at the end of the
210   // section and use that and the LastLabel to compute the address delta
211   // and use INT64_MAX as the line delta which is the signal that this is
212   // actually a DW_LNE_end_sequence.
213
214   // Switch to the section to be able to create a symbol at its end.
215   MCOS->SwitchSection(Section);
216   // Create a symbol at the end of the section.
217   MCSymbol *SectionEnd = MCOS->getContext().CreateTempSymbol();
218   // Set the value of the symbol, as we are at the end of the section.
219   MCOS->EmitLabel(SectionEnd);
220
221   // Switch back the the dwarf line section.
222   MCOS->SwitchSection(DwarfLineSection);
223   // Create an expression for the address delta from the LastLabel and this
224   // SectionEnd label.
225   const MCExpr *AddrDelta = MakeStartMinusEndExpr(MCOS, LastLabel, SectionEnd,
226                                                   0);
227   // Create a Dwarf Line fragment for the LineDelta and AddrDelta.
228   new MCDwarfLineAddrFragment(INT64_MAX, *AddrDelta, &DLS);
229
230   return EmittedLineTable;
231 }
232
233 //
234 // This emits the Dwarf file and the line tables.
235 //
236 void MCDwarfFileTable::Emit(MCObjectStreamer *MCOS,
237                             const MCSection *DwarfLineSection) {
238   // Switch to the section where the table will be emitted into.
239   MCOS->SwitchSection(DwarfLineSection);
240
241   // Create a symbol at the beginning of this section.
242   MCSymbol *LineStartSym = MCOS->getContext().CreateTempSymbol();
243   // Set the value of the symbol, as we are at the start of the section.
244   MCOS->EmitLabel(LineStartSym);
245
246   // Create a symbol for the end of the section (to be set when we get there).
247   MCSymbol *LineEndSym = MCOS->getContext().CreateTempSymbol();
248
249   // The first 4 bytes is the total length of the information for this
250   // compilation unit (not including these 4 bytes for the length).
251   MCOS->EmitValue(MakeStartMinusEndExpr(MCOS, LineStartSym, LineEndSym, 4),
252                   4, 0);
253
254   // Next 2 bytes is the Version, which is Dwarf 2.
255   MCOS->EmitIntValue(2, 2);
256
257   // Create a symbol for the end of the prologue (to be set when we get there).
258   MCSymbol *ProEndSym = MCOS->getContext().CreateTempSymbol(); // Lprologue_end
259
260   // Length of the prologue, is the next 4 bytes.  Which is the start of the
261   // section to the end of the prologue.  Not including the 4 bytes for the
262   // total length, the 2 bytes for the version, and these 4 bytes for the
263   // length of the prologue.
264   MCOS->EmitValue(MakeStartMinusEndExpr(MCOS, LineStartSym, ProEndSym,
265                                         (4 + 2 + 4)),
266                   4, 0);
267
268   // Parameters of the state machine, are next.
269   MCOS->EmitIntValue(DWARF2_LINE_MIN_INSN_LENGTH, 1);
270   MCOS->EmitIntValue(DWARF2_LINE_DEFAULT_IS_STMT, 1);
271   MCOS->EmitIntValue(DWARF2_LINE_BASE, 1);
272   MCOS->EmitIntValue(DWARF2_LINE_RANGE, 1);
273   MCOS->EmitIntValue(DWARF2_LINE_OPCODE_BASE, 1);
274
275   // Standard opcode lengths
276   MCOS->EmitIntValue(0, 1); // length of DW_LNS_copy
277   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_pc
278   MCOS->EmitIntValue(1, 1); // length of DW_LNS_advance_line
279   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_file
280   MCOS->EmitIntValue(1, 1); // length of DW_LNS_set_column
281   MCOS->EmitIntValue(0, 1); // length of DW_LNS_negate_stmt
282   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_basic_block
283   MCOS->EmitIntValue(0, 1); // length of DW_LNS_const_add_pc
284   MCOS->EmitIntValue(1, 1); // length of DW_LNS_fixed_advance_pc
285   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_prologue_end
286   MCOS->EmitIntValue(0, 1); // length of DW_LNS_set_epilogue_begin
287   MCOS->EmitIntValue(1, 1); // DW_LNS_set_isa
288
289   // Put out the directory and file tables.
290
291   // First the directory table.
292   const std::vector<StringRef> &MCDwarfDirs =
293     MCOS->getContext().getMCDwarfDirs();
294   for (unsigned i = 0; i < MCDwarfDirs.size(); i++) {
295     MCOS->EmitBytes(MCDwarfDirs[i], 0); // the DirectoryName
296     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
297   }
298   MCOS->EmitIntValue(0, 1); // Terminate the directory list
299
300   // Second the file table.
301   const std::vector<MCDwarfFile *> &MCDwarfFiles =
302     MCOS->getContext().getMCDwarfFiles();
303   for (unsigned i = 1; i < MCDwarfFiles.size(); i++) {
304     MCOS->EmitBytes(MCDwarfFiles[i]->getName(), 0); // FileName
305     MCOS->EmitBytes(StringRef("\0", 1), 0); // the null term. of the string
306     MCOS->EmitULEB128Value(MCDwarfFiles[i]->getDirIndex()); // the Directory num
307     MCOS->EmitIntValue(0, 1); // last modification timestamp (always 0)
308     MCOS->EmitIntValue(0, 1); // filesize (always 0)
309   }
310   MCOS->EmitIntValue(0, 1); // Terminate the file list
311
312   // This is the end of the prologue, so set the value of the symbol at the
313   // end of the prologue (that was used in a previous expression).
314   MCOS->EmitLabel(ProEndSym);
315
316   // Put out the line tables.
317   bool EmittedLineTable = false;
318   DenseMap<const MCSection *, MCLineSection *> &MCLineSections =
319     MCOS->getContext().getMCLineSections();
320   for (DenseMap<const MCSection *, MCLineSection *>::iterator it =
321         MCLineSections.begin(), ie = MCLineSections.end(); it != ie; ++it) {
322     EmittedLineTable = EmitDwarfLineTable(MCOS, it->first, it->second,
323                                           DwarfLineSection);
324
325     // Now delete the MCLineSections that were created in MCLineEntry::Make()
326     // and used to emit the line table.
327     delete it->second;
328   }
329
330   // If there are no line tables emited then we emit:
331   // The following DW_LNE_set_address sequence to set the address to zero and
332   // the DW_LNE_end_sequence.
333   if (EmittedLineTable == false) {
334     if (MCOS->getAssembler().getBackend().getPointerSize() == 8) {
335       // This is the DW_LNE_set_address sequence for 64-bit code.
336       MCOS->EmitIntValue(0, 1);
337       MCOS->EmitIntValue(9, 1);
338       MCOS->EmitIntValue(2, 1);
339       MCOS->EmitIntValue(0, 1);
340       MCOS->EmitIntValue(0, 1);
341       MCOS->EmitIntValue(0, 1);
342       MCOS->EmitIntValue(0, 1);
343       MCOS->EmitIntValue(0, 1);
344       MCOS->EmitIntValue(0, 1);
345       MCOS->EmitIntValue(0, 1);
346       MCOS->EmitIntValue(0, 1);
347     }
348     else {
349       // This is the DW_LNE_set_address sequence for 32-bit code.
350       MCOS->EmitIntValue(0, 1);
351       MCOS->EmitIntValue(5, 1);
352       MCOS->EmitIntValue(2, 1);
353       MCOS->EmitIntValue(0, 1);
354       MCOS->EmitIntValue(0, 1);
355       MCOS->EmitIntValue(0, 1);
356       MCOS->EmitIntValue(0, 1);
357     }
358
359     // Lastly emit the DW_LNE_end_sequence which consists of 3 bytes '00 01 01'
360     // (00 is the code for extended opcodes, followed by a ULEB128 length of the
361     // extended opcode (01), and the DW_LNE_end_sequence (01).
362     MCOS->EmitIntValue(0, 1); // DW_LNS_extended_op
363     MCOS->EmitIntValue(1, 1); // ULEB128 length of the extended opcode
364     MCOS->EmitIntValue(1, 1); // DW_LNE_end_sequence
365   }
366
367   // This is the end of the section, so set the value of the symbol at the end
368   // of this section (that was used in a previous expression).
369   MCOS->EmitLabel(LineEndSym);
370 }
371
372 /// Utility function to compute the size of the encoding.
373 uint64_t MCDwarfLineAddr::ComputeSize(int64_t LineDelta, uint64_t AddrDelta) {
374   SmallString<256> Tmp;
375   raw_svector_ostream OS(Tmp);
376   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
377   return OS.GetNumBytesInBuffer();
378 }
379
380 /// Utility function to write the encoding to an object writer.
381 void MCDwarfLineAddr::Write(MCObjectWriter *OW, int64_t LineDelta,
382                             uint64_t AddrDelta) {
383   SmallString<256> Tmp;
384   raw_svector_ostream OS(Tmp);
385   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
386   OW->WriteBytes(OS.str());
387 }
388
389 /// Utility function to emit the encoding to a streamer.
390 void MCDwarfLineAddr::Emit(MCObjectStreamer *MCOS, int64_t LineDelta,
391                            uint64_t AddrDelta) {
392   SmallString<256> Tmp;
393   raw_svector_ostream OS(Tmp);
394   MCDwarfLineAddr::Encode(LineDelta, AddrDelta, OS);
395   MCOS->EmitBytes(OS.str(), /*AddrSpace=*/0);
396 }
397
398 /// Utility function to encode a Dwarf pair of LineDelta and AddrDeltas.
399 void MCDwarfLineAddr::Encode(int64_t LineDelta, uint64_t AddrDelta,
400                              raw_ostream &OS) {
401   uint64_t Temp, Opcode;
402   bool NeedCopy = false;
403
404   // Scale the address delta by the minimum instruction length.
405   AddrDelta = ScaleAddrDelta(AddrDelta);
406
407   // A LineDelta of INT64_MAX is a signal that this is actually a
408   // DW_LNE_end_sequence. We cannot use special opcodes here, since we want the 
409   // end_sequence to emit the matrix entry.
410   if (LineDelta == INT64_MAX) {
411     if (AddrDelta == MAX_SPECIAL_ADDR_DELTA)
412       OS << char(dwarf::DW_LNS_const_add_pc);
413     else {
414       OS << char(dwarf::DW_LNS_advance_pc);
415       SmallString<32> Tmp;
416       raw_svector_ostream OSE(Tmp);
417       MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
418       OS << OSE.str();
419     }
420     OS << char(dwarf::DW_LNS_extended_op);
421     OS << char(1);
422     OS << char(dwarf::DW_LNE_end_sequence);
423     return;
424   }
425
426   // Bias the line delta by the base.
427   Temp = LineDelta - DWARF2_LINE_BASE;
428
429   // If the line increment is out of range of a special opcode, we must encode
430   // it with DW_LNS_advance_line.
431   if (Temp >= DWARF2_LINE_RANGE) {
432     OS << char(dwarf::DW_LNS_advance_line);
433     SmallString<32> Tmp;
434     raw_svector_ostream OSE(Tmp);
435     MCObjectWriter::EncodeSLEB128(LineDelta, OSE);
436     OS << OSE.str();
437
438     LineDelta = 0;
439     Temp = 0 - DWARF2_LINE_BASE;
440     NeedCopy = true;
441   }
442
443   // Use DW_LNS_copy instead of a "line +0, addr +0" special opcode.
444   if (LineDelta == 0 && AddrDelta == 0) {
445     OS << char(dwarf::DW_LNS_copy);
446     return;
447   }
448
449   // Bias the opcode by the special opcode base.
450   Temp += DWARF2_LINE_OPCODE_BASE;
451
452   // Avoid overflow when addr_delta is large.
453   if (AddrDelta < 256 + MAX_SPECIAL_ADDR_DELTA) {
454     // Try using a special opcode.
455     Opcode = Temp + AddrDelta * DWARF2_LINE_RANGE;
456     if (Opcode <= 255) {
457       OS << char(Opcode);
458       return;
459     }
460
461     // Try using DW_LNS_const_add_pc followed by special op.
462     Opcode = Temp + (AddrDelta - MAX_SPECIAL_ADDR_DELTA) * DWARF2_LINE_RANGE;
463     if (Opcode <= 255) {
464       OS << char(dwarf::DW_LNS_const_add_pc);
465       OS << char(Opcode);
466       return;
467     }
468   }
469
470   // Otherwise use DW_LNS_advance_pc.
471   OS << char(dwarf::DW_LNS_advance_pc);
472   SmallString<32> Tmp;
473   raw_svector_ostream OSE(Tmp);
474   MCObjectWriter::EncodeULEB128(AddrDelta, OSE);
475   OS << OSE.str();
476
477   if (NeedCopy)
478     OS << char(dwarf::DW_LNS_copy);
479   else
480     OS << char(Temp);
481 }
482
483 void MCDwarfFile::print(raw_ostream &OS) const {
484   OS << '"' << getName() << '"';
485 }
486
487 void MCDwarfFile::dump() const {
488   print(dbgs());
489 }
490