DWARF: Add basic support for line tables.
[oota-llvm.git] / lib / DebugInfo / DWARFDebugLine.cpp
1 //===-- DWARFDebugLine.cpp ------------------------------------------------===//
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 "DWARFDebugLine.h"
11 #include "llvm/Support/Dwarf.h"
12 #include "llvm/Support/Format.h"
13 #include "llvm/Support/raw_ostream.h"
14 using namespace llvm;
15 using namespace dwarf;
16
17 void DWARFDebugLine::Prologue::dump(raw_ostream &OS) const {
18   OS << "Line table prologue:\n"
19      << format("   total_length: 0x%8.8x\n", TotalLength)
20      << format("        version: %u\n", Version)
21      << format("prologue_length: 0x%8.8x\n", PrologueLength)
22      << format("min_inst_length: %u\n", MinInstLength)
23      << format("default_is_stmt: %u\n", DefaultIsStmt)
24      << format("      line_base: %i\n", LineBase)
25      << format("     line_range: %u\n", LineRange)
26      << format("    opcode_base: %u\n", OpcodeBase);
27
28   for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
29     OS << format("standard_opcode_lengths[%s] = %u\n", LNStandardString(i+1),
30                  StandardOpcodeLengths[i]);
31
32   if (!IncludeDirectories.empty())
33     for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
34       OS << format("include_directories[%3u] = '", i+1)
35          << IncludeDirectories[i] << "'\n";
36
37   if (!FileNames.empty()) {
38     OS << "                Dir  Mod Time   File Len   File Name\n"
39        << "                ---- ---------- ---------- -----------"
40           "----------------\n";
41     for (uint32_t i = 0; i < FileNames.size(); ++i) {
42       const FileNameEntry& fileEntry = FileNames[i];
43       OS << format("file_names[%3u] %4u ", i+1, fileEntry.DirIdx)
44          << format("0x%8.8x 0x%8.8x ", fileEntry.ModTime, fileEntry.Length)
45          << fileEntry.Name << '\n';
46     }
47   }
48 }
49
50 void DWARFDebugLine::Row::postAppend() {
51   BasicBlock = false;
52   PrologueEnd = false;
53   EpilogueBegin = false;
54 }
55
56 void DWARFDebugLine::Row::reset(bool default_is_stmt) {
57   Address = 0;
58   Line = 1;
59   Column = 0;
60   File = 1;
61   Isa = 0;
62   IsStmt = default_is_stmt;
63   BasicBlock = false;
64   EndSequence = false;
65   PrologueEnd = false;
66   EpilogueBegin = false;
67 }
68
69 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
70   OS << format("0x%16.16llx %6u %6u", Address, Line, Column)
71      << format(" %6u %3u ", File, Isa)
72      << (IsStmt ? " is_stmt" : "")
73      << (BasicBlock ? " basic_block" : "")
74      << (PrologueEnd ? " prologue_end" : "")
75      << (EpilogueBegin ? " epilogue_begin" : "")
76      << (EndSequence ? " end_sequence" : "")
77      << '\n';
78 }
79
80 void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
81   Prologue.dump(OS);
82   OS << '\n';
83
84   if (!Rows.empty()) {
85     OS << "Address            Line   Column File   ISA Flags\n"
86        << "------------------ ------ ------ ------ --- -------------\n";
87     for (std::vector<Row>::const_iterator pos = Rows.begin(),
88          end = Rows.end(); pos != end; ++pos)
89       pos->dump(OS);
90   }
91 }
92
93 void DWARFDebugLine::State::appendRowToMatrix(uint32_t offset) {
94   ++row;  // Increase the row number.
95   LineTable::appendRow(*this);
96   Row::postAppend();
97 }
98
99 void DWARFDebugLine::parse(const DataExtractor debug_line_data) {
100   LineTableMap.clear();
101   uint32_t offset = 0;
102   State state;
103   while (debug_line_data.isValidOffset(offset)) {
104     const uint32_t debug_line_offset = offset;
105
106     if (parseStatementTable(debug_line_data, &offset, state)) {
107       // Make sure we don't don't loop infinitely
108       if (offset <= debug_line_offset)
109         break;
110
111       LineTableMap[debug_line_offset] = state;
112       state.reset();
113     }
114     else
115       ++offset; // Try next byte in line table
116   }
117 }
118
119 void DWARFDebugLine::DumpingState::finalize(uint32_t offset) {
120   LineTable::dump(OS);
121 }
122
123 void DWARFDebugLine::dump(const DataExtractor debug_line_data, raw_ostream &OS){
124   uint32_t offset = 0;
125   DumpingState state(OS);
126     while (debug_line_data.isValidOffset(offset)) {
127     const uint32_t debug_line_offset = offset;
128
129     if (parseStatementTable(debug_line_data, &offset, state)) {
130       // Make sure we don't don't loop infinitely
131       if (offset <= debug_line_offset)
132         break;
133
134       state.reset();
135     }
136     else
137       ++offset; // Try next byte in line table
138   }
139 }
140
141 const DWARFDebugLine::LineTable *
142 DWARFDebugLine::getLineTable(uint32_t offset) const {
143   LineTableConstIter pos = LineTableMap.find(offset);
144   if (pos != LineTableMap.end())
145     return &pos->second;
146   return 0;
147 }
148
149 bool
150 DWARFDebugLine::parsePrologue(DataExtractor debug_line_data,
151                               uint32_t *offset_ptr, Prologue *prologue) {
152   const uint32_t prologue_offset = *offset_ptr;
153
154   prologue->clear();
155   prologue->TotalLength = debug_line_data.getU32(offset_ptr);
156   prologue->Version = debug_line_data.getU16(offset_ptr);
157   if (prologue->Version != 2)
158     return false;
159
160   prologue->PrologueLength = debug_line_data.getU32(offset_ptr);
161   const uint32_t end_prologue_offset = prologue->PrologueLength + *offset_ptr;
162   prologue->MinInstLength = debug_line_data.getU8(offset_ptr);
163   prologue->DefaultIsStmt = debug_line_data.getU8(offset_ptr);
164   prologue->LineBase = debug_line_data.getU8(offset_ptr);
165   prologue->LineRange = debug_line_data.getU8(offset_ptr);
166   prologue->OpcodeBase = debug_line_data.getU8(offset_ptr);
167
168   prologue->StandardOpcodeLengths.reserve(prologue->OpcodeBase-1);
169   for (uint32_t i = 1; i < prologue->OpcodeBase; ++i) {
170     uint8_t op_len = debug_line_data.getU8(offset_ptr);
171     prologue->StandardOpcodeLengths.push_back(op_len);
172   }
173
174   while (*offset_ptr < end_prologue_offset) {
175     const char *s = debug_line_data.getCStr(offset_ptr);
176     if (s && s[0])
177       prologue->IncludeDirectories.push_back(s);
178     else
179       break;
180   }
181
182   while (*offset_ptr < end_prologue_offset) {
183     const char *name = debug_line_data.getCStr(offset_ptr);
184     if (name && name[0]) {
185       FileNameEntry fileEntry;
186       fileEntry.Name = name;
187       fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
188       fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
189       fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
190       prologue->FileNames.push_back(fileEntry);
191     } else {
192       break;
193     }
194   }
195
196   if (*offset_ptr != end_prologue_offset) {
197     fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
198                     " have ended at 0x%8.8x but it ended ad 0x%8.8x\n", 
199             prologue_offset, end_prologue_offset, *offset_ptr);
200   }
201   return end_prologue_offset;
202 }
203
204 bool
205 DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data,
206                                     uint32_t *offset_ptr, State &state) {
207   const uint32_t debug_line_offset = *offset_ptr;
208
209   Prologue *prologue = &state.Prologue;
210
211   if (!parsePrologue(debug_line_data, offset_ptr, prologue)) {
212     // Restore our offset and return false to indicate failure!
213     *offset_ptr = debug_line_offset;
214     return false;
215   }
216
217   const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
218                               sizeof(prologue->TotalLength);
219
220   while (*offset_ptr < end_offset) {
221     uint8_t opcode = debug_line_data.getU8(offset_ptr);
222
223     if (opcode == 0) {
224       // Extended Opcodes always start with a zero opcode followed by
225       // a uleb128 length so you can skip ones you don't know about
226       uint32_t ext_offset = *offset_ptr;
227       uint64_t len = debug_line_data.getULEB128(offset_ptr);
228       uint32_t arg_size = len - (*offset_ptr - ext_offset);
229
230       uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
231       switch (sub_opcode) {
232       case DW_LNE_end_sequence:
233         // Set the end_sequence register of the state machine to true and
234         // append a row to the matrix using the current values of the
235         // state-machine registers. Then reset the registers to the initial
236         // values specified above. Every statement program sequence must end
237         // with a DW_LNE_end_sequence instruction which creates a row whose
238         // address is that of the byte after the last target machine instruction
239         // of the sequence.
240         state.EndSequence = true;
241         state.appendRowToMatrix(*offset_ptr);
242         state.reset();
243         break;
244
245       case DW_LNE_set_address:
246         // Takes a single relocatable address as an operand. The size of the
247         // operand is the size appropriate to hold an address on the target
248         // machine. Set the address register to the value given by the
249         // relocatable address. All of the other statement program opcodes
250         // that affect the address register add a delta to it. This instruction
251         // stores a relocatable value into it instead.
252         state.Address = debug_line_data.getAddress(offset_ptr);
253         break;
254
255       case DW_LNE_define_file:
256         // Takes 4 arguments. The first is a null terminated string containing
257         // a source file name. The second is an unsigned LEB128 number
258         // representing the directory index of the directory in which the file
259         // was found. The third is an unsigned LEB128 number representing the
260         // time of last modification of the file. The fourth is an unsigned
261         // LEB128 number representing the length in bytes of the file. The time
262         // and length fields may contain LEB128(0) if the information is not
263         // available.
264         //
265         // The directory index represents an entry in the include_directories
266         // section of the statement program prologue. The index is LEB128(0)
267         // if the file was found in the current directory of the compilation,
268         // LEB128(1) if it was found in the first directory in the
269         // include_directories section, and so on. The directory index is
270         // ignored for file names that represent full path names.
271         //
272         // The files are numbered, starting at 1, in the order in which they
273         // appear; the names in the prologue come before names defined by
274         // the DW_LNE_define_file instruction. These numbers are used in the
275         // the file register of the state machine.
276         {
277           FileNameEntry fileEntry;
278           fileEntry.Name = debug_line_data.getCStr(offset_ptr);
279           fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
280           fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
281           fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
282           prologue->FileNames.push_back(fileEntry);
283         }
284         break;
285
286       default:
287         // Length doesn't include the zero opcode byte or the length itself, but
288         // it does include the sub_opcode, so we have to adjust for that below
289         (*offset_ptr) += arg_size;
290         break;
291       }
292     } else if (opcode < prologue->OpcodeBase) {
293       switch (opcode) {
294       // Standard Opcodes
295       case DW_LNS_copy:
296         // Takes no arguments. Append a row to the matrix using the
297         // current values of the state-machine registers. Then set
298         // the basic_block register to false.
299         state.appendRowToMatrix(*offset_ptr);
300         break;
301
302       case DW_LNS_advance_pc:
303         // Takes a single unsigned LEB128 operand, multiplies it by the
304         // min_inst_length field of the prologue, and adds the
305         // result to the address register of the state machine.
306         state.Address += debug_line_data.getULEB128(offset_ptr) *
307                          prologue->MinInstLength;
308         break;
309
310       case DW_LNS_advance_line:
311         // Takes a single signed LEB128 operand and adds that value to
312         // the line register of the state machine.
313         state.Line += debug_line_data.getSLEB128(offset_ptr);
314         break;
315
316       case DW_LNS_set_file:
317         // Takes a single unsigned LEB128 operand and stores it in the file
318         // register of the state machine.
319         state.File = debug_line_data.getULEB128(offset_ptr);
320         break;
321
322       case DW_LNS_set_column:
323         // Takes a single unsigned LEB128 operand and stores it in the
324         // column register of the state machine.
325         state.Column = debug_line_data.getULEB128(offset_ptr);
326         break;
327
328       case DW_LNS_negate_stmt:
329         // Takes no arguments. Set the is_stmt register of the state
330         // machine to the logical negation of its current value.
331         state.IsStmt = !state.IsStmt;
332         break;
333
334       case DW_LNS_set_basic_block:
335         // Takes no arguments. Set the basic_block register of the
336         // state machine to true
337         state.BasicBlock = true;
338         break;
339
340       case DW_LNS_const_add_pc:
341         // Takes no arguments. Add to the address register of the state
342         // machine the address increment value corresponding to special
343         // opcode 255. The motivation for DW_LNS_const_add_pc is this:
344         // when the statement program needs to advance the address by a
345         // small amount, it can use a single special opcode, which occupies
346         // a single byte. When it needs to advance the address by up to
347         // twice the range of the last special opcode, it can use
348         // DW_LNS_const_add_pc followed by a special opcode, for a total
349         // of two bytes. Only if it needs to advance the address by more
350         // than twice that range will it need to use both DW_LNS_advance_pc
351         // and a special opcode, requiring three or more bytes.
352         {
353           uint8_t adjust_opcode = 255 - prologue->OpcodeBase;
354           uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
355                                  prologue->MinInstLength;
356           state.Address += addr_offset;
357         }
358         break;
359
360       case DW_LNS_fixed_advance_pc:
361         // Takes a single uhalf operand. Add to the address register of
362         // the state machine the value of the (unencoded) operand. This
363         // is the only extended opcode that takes an argument that is not
364         // a variable length number. The motivation for DW_LNS_fixed_advance_pc
365         // is this: existing assemblers cannot emit DW_LNS_advance_pc or
366         // special opcodes because they cannot encode LEB128 numbers or
367         // judge when the computation of a special opcode overflows and
368         // requires the use of DW_LNS_advance_pc. Such assemblers, however,
369         // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
370         state.Address += debug_line_data.getU16(offset_ptr);
371         break;
372
373       case DW_LNS_set_prologue_end:
374         // Takes no arguments. Set the prologue_end register of the
375         // state machine to true
376         state.PrologueEnd = true;
377         break;
378
379       case DW_LNS_set_epilogue_begin:
380         // Takes no arguments. Set the basic_block register of the
381         // state machine to true
382         state.EpilogueBegin = true;
383         break;
384
385       case DW_LNS_set_isa:
386         // Takes a single unsigned LEB128 operand and stores it in the
387         // column register of the state machine.
388         state.Isa = debug_line_data.getULEB128(offset_ptr);
389         break;
390
391       default:
392         // Handle any unknown standard opcodes here. We know the lengths
393         // of such opcodes because they are specified in the prologue
394         // as a multiple of LEB128 operands for each opcode.
395         {
396           assert(opcode - 1 < prologue->StandardOpcodeLengths.size());
397           uint8_t opcode_length = prologue->StandardOpcodeLengths[opcode - 1];
398           for (uint8_t i=0; i<opcode_length; ++i)
399             debug_line_data.getULEB128(offset_ptr);
400         }
401         break;
402       }
403     } else {
404       // Special Opcodes
405
406       // A special opcode value is chosen based on the amount that needs
407       // to be added to the line and address registers. The maximum line
408       // increment for a special opcode is the value of the line_base
409       // field in the header, plus the value of the line_range field,
410       // minus 1 (line base + line range - 1). If the desired line
411       // increment is greater than the maximum line increment, a standard
412       // opcode must be used instead of a special opcode. The “address
413       // advance” is calculated by dividing the desired address increment
414       // by the minimum_instruction_length field from the header. The
415       // special opcode is then calculated using the following formula:
416       //
417       //  opcode = (desired line increment - line_base) +
418       //           (line_range * address advance) + opcode_base
419       //
420       // If the resulting opcode is greater than 255, a standard opcode
421       // must be used instead.
422       //
423       // To decode a special opcode, subtract the opcode_base from the
424       // opcode itself to give the adjusted opcode. The amount to
425       // increment the address register is the result of the adjusted
426       // opcode divided by the line_range multiplied by the
427       // minimum_instruction_length field from the header. That is:
428       //
429       //  address increment = (adjusted opcode / line_range) *
430       //                      minimum_instruction_length
431       //
432       // The amount to increment the line register is the line_base plus
433       // the result of the adjusted opcode modulo the line_range. That is:
434       //
435       // line increment = line_base + (adjusted opcode % line_range)
436
437       uint8_t adjust_opcode = opcode - prologue->OpcodeBase;
438       uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
439                              prologue->MinInstLength;
440       int32_t line_offset = prologue->LineBase +
441                             (adjust_opcode % prologue->LineRange);
442       state.Line += line_offset;
443       state.Address += addr_offset;
444       state.appendRowToMatrix(*offset_ptr);
445     }
446   }
447
448   state.finalize(*offset_ptr);
449
450   return end_offset;
451 }
452
453 static bool findMatchingAddress(const DWARFDebugLine::Row& row1,
454                                 const DWARFDebugLine::Row& row2) {
455   return row1.Address < row2.Address;
456 }
457
458 uint32_t
459 DWARFDebugLine::LineTable::lookupAddress(uint64_t address,
460                                          uint64_t cu_high_pc) const {
461   uint32_t index = UINT32_MAX;
462   if (!Rows.empty()) {
463     // Use the lower_bound algorithm to perform a binary search since we know
464     // that our line table data is ordered by address.
465     DWARFDebugLine::Row row;
466     row.Address = address;
467     typedef std::vector<Row>::const_iterator iterator;
468     iterator begin_pos = Rows.begin();
469     iterator end_pos = Rows.end();
470     iterator pos = std::lower_bound(begin_pos, end_pos, row,
471                                     findMatchingAddress);
472     if (pos == end_pos) {
473       if (address < cu_high_pc)
474         return Rows.size()-1;
475     } else {
476       // Rely on fact that we are using a std::vector and we can do
477       // pointer arithmetic to find the row index (which will be one less
478       // that what we found since it will find the first position after
479       // the current address) since std::vector iterators are just
480       // pointers to the container type.
481       index = pos - begin_pos;
482       if (pos->Address > address) {
483         if (index > 0)
484           --index;
485         else
486           index = UINT32_MAX;
487       }
488     }
489   }
490   return index; // Failed to find address.
491 }