Rename many DataLayout variables from TD to DL.
[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/Path.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include <algorithm>
16 using namespace llvm;
17 using namespace dwarf;
18
19 void DWARFDebugLine::Prologue::dump(raw_ostream &OS) const {
20   OS << "Line table prologue:\n"
21      << format("   total_length: 0x%8.8x\n", TotalLength)
22      << format("        version: %u\n", Version)
23      << format("prologue_length: 0x%8.8x\n", PrologueLength)
24      << format("min_inst_length: %u\n", MinInstLength)
25      << format("default_is_stmt: %u\n", DefaultIsStmt)
26      << format("      line_base: %i\n", LineBase)
27      << format("     line_range: %u\n", LineRange)
28      << format("    opcode_base: %u\n", OpcodeBase);
29
30   for (uint32_t i = 0; i < StandardOpcodeLengths.size(); ++i)
31     OS << format("standard_opcode_lengths[%s] = %u\n", LNStandardString(i+1),
32                  StandardOpcodeLengths[i]);
33
34   if (!IncludeDirectories.empty())
35     for (uint32_t i = 0; i < IncludeDirectories.size(); ++i)
36       OS << format("include_directories[%3u] = '", i+1)
37          << IncludeDirectories[i] << "'\n";
38
39   if (!FileNames.empty()) {
40     OS << "                Dir  Mod Time   File Len   File Name\n"
41        << "                ---- ---------- ---------- -----------"
42           "----------------\n";
43     for (uint32_t i = 0; i < FileNames.size(); ++i) {
44       const FileNameEntry& fileEntry = FileNames[i];
45       OS << format("file_names[%3u] %4" PRIu64 " ", i+1, fileEntry.DirIdx)
46          << format("0x%8.8" PRIx64 " 0x%8.8" PRIx64 " ",
47                    fileEntry.ModTime, fileEntry.Length)
48          << fileEntry.Name << '\n';
49     }
50   }
51 }
52
53 void DWARFDebugLine::Row::postAppend() {
54   BasicBlock = false;
55   PrologueEnd = false;
56   EpilogueBegin = false;
57 }
58
59 void DWARFDebugLine::Row::reset(bool default_is_stmt) {
60   Address = 0;
61   Line = 1;
62   Column = 0;
63   File = 1;
64   Isa = 0;
65   Discriminator = 0;
66   IsStmt = default_is_stmt;
67   BasicBlock = false;
68   EndSequence = false;
69   PrologueEnd = false;
70   EpilogueBegin = false;
71 }
72
73 void DWARFDebugLine::Row::dump(raw_ostream &OS) const {
74   OS << format("0x%16.16" PRIx64 " %6u %6u", Address, Line, Column)
75      << format(" %6u %3u %13u ", File, Isa, Discriminator)
76      << (IsStmt ? " is_stmt" : "")
77      << (BasicBlock ? " basic_block" : "")
78      << (PrologueEnd ? " prologue_end" : "")
79      << (EpilogueBegin ? " epilogue_begin" : "")
80      << (EndSequence ? " end_sequence" : "")
81      << '\n';
82 }
83
84 void DWARFDebugLine::LineTable::dump(raw_ostream &OS) const {
85   Prologue.dump(OS);
86   OS << '\n';
87
88   if (!Rows.empty()) {
89     OS << "Address            Line   Column File   ISA Discriminator Flags\n"
90        << "------------------ ------ ------ ------ --- ------------- "
91           "-------------\n";
92     for (std::vector<Row>::const_iterator pos = Rows.begin(),
93          end = Rows.end(); pos != end; ++pos)
94       pos->dump(OS);
95   }
96 }
97
98 DWARFDebugLine::State::~State() {}
99
100 void DWARFDebugLine::State::appendRowToMatrix(uint32_t offset) {
101   if (Sequence::Empty) {
102     // Record the beginning of instruction sequence.
103     Sequence::Empty = false;
104     Sequence::LowPC = Address;
105     Sequence::FirstRowIndex = row;
106   }
107   ++row;  // Increase the row number.
108   LineTable::appendRow(*this);
109   if (EndSequence) {
110     // Record the end of instruction sequence.
111     Sequence::HighPC = Address;
112     Sequence::LastRowIndex = row;
113     if (Sequence::isValid())
114       LineTable::appendSequence(*this);
115     Sequence::reset();
116   }
117   Row::postAppend();
118 }
119
120 void DWARFDebugLine::State::finalize() {
121   row = DoneParsingLineTable;
122   if (!Sequence::Empty) {
123     fprintf(stderr, "warning: last sequence in debug line table is not"
124                     "terminated!\n");
125   }
126   // Sort all sequences so that address lookup will work faster.
127   if (!Sequences.empty()) {
128     std::sort(Sequences.begin(), Sequences.end(), Sequence::orderByLowPC);
129     // Note: actually, instruction address ranges of sequences should not
130     // overlap (in shared objects and executables). If they do, the address
131     // lookup would still work, though, but result would be ambiguous.
132     // We don't report warning in this case. For example,
133     // sometimes .so compiled from multiple object files contains a few
134     // rudimentary sequences for address ranges [0x0, 0xsomething).
135   }
136 }
137
138 DWARFDebugLine::DumpingState::~DumpingState() {}
139
140 void DWARFDebugLine::DumpingState::finalize() {
141   LineTable::dump(OS);
142 }
143
144 const DWARFDebugLine::LineTable *
145 DWARFDebugLine::getLineTable(uint32_t offset) const {
146   LineTableConstIter pos = LineTableMap.find(offset);
147   if (pos != LineTableMap.end())
148     return &pos->second;
149   return 0;
150 }
151
152 const DWARFDebugLine::LineTable *
153 DWARFDebugLine::getOrParseLineTable(DataExtractor debug_line_data,
154                                     uint32_t offset) {
155   std::pair<LineTableIter, bool> pos =
156     LineTableMap.insert(LineTableMapTy::value_type(offset, LineTable()));
157   if (pos.second) {
158     // Parse and cache the line table for at this offset.
159     State state;
160     if (!parseStatementTable(debug_line_data, RelocMap, &offset, state))
161       return 0;
162     pos.first->second = state;
163   }
164   return &pos.first->second;
165 }
166
167 bool
168 DWARFDebugLine::parsePrologue(DataExtractor debug_line_data,
169                               uint32_t *offset_ptr, Prologue *prologue) {
170   const uint32_t prologue_offset = *offset_ptr;
171
172   prologue->clear();
173   prologue->TotalLength = debug_line_data.getU32(offset_ptr);
174   prologue->Version = debug_line_data.getU16(offset_ptr);
175   if (prologue->Version != 2)
176     return false;
177
178   prologue->PrologueLength = debug_line_data.getU32(offset_ptr);
179   const uint32_t end_prologue_offset = prologue->PrologueLength + *offset_ptr;
180   prologue->MinInstLength = debug_line_data.getU8(offset_ptr);
181   prologue->DefaultIsStmt = debug_line_data.getU8(offset_ptr);
182   prologue->LineBase = debug_line_data.getU8(offset_ptr);
183   prologue->LineRange = debug_line_data.getU8(offset_ptr);
184   prologue->OpcodeBase = debug_line_data.getU8(offset_ptr);
185
186   prologue->StandardOpcodeLengths.reserve(prologue->OpcodeBase-1);
187   for (uint32_t i = 1; i < prologue->OpcodeBase; ++i) {
188     uint8_t op_len = debug_line_data.getU8(offset_ptr);
189     prologue->StandardOpcodeLengths.push_back(op_len);
190   }
191
192   while (*offset_ptr < end_prologue_offset) {
193     const char *s = debug_line_data.getCStr(offset_ptr);
194     if (s && s[0])
195       prologue->IncludeDirectories.push_back(s);
196     else
197       break;
198   }
199
200   while (*offset_ptr < end_prologue_offset) {
201     const char *name = debug_line_data.getCStr(offset_ptr);
202     if (name && name[0]) {
203       FileNameEntry fileEntry;
204       fileEntry.Name = name;
205       fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
206       fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
207       fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
208       prologue->FileNames.push_back(fileEntry);
209     } else {
210       break;
211     }
212   }
213
214   if (*offset_ptr != end_prologue_offset) {
215     fprintf(stderr, "warning: parsing line table prologue at 0x%8.8x should"
216                     " have ended at 0x%8.8x but it ended at 0x%8.8x\n",
217             prologue_offset, end_prologue_offset, *offset_ptr);
218     return false;
219   }
220   return true;
221 }
222
223 bool
224 DWARFDebugLine::parseStatementTable(DataExtractor debug_line_data, 
225                                     const RelocAddrMap *RMap,
226                                     uint32_t *offset_ptr, State &state) {
227   const uint32_t debug_line_offset = *offset_ptr;
228
229   Prologue *prologue = &state.Prologue;
230
231   if (!parsePrologue(debug_line_data, offset_ptr, prologue)) {
232     // Restore our offset and return false to indicate failure!
233     *offset_ptr = debug_line_offset;
234     return false;
235   }
236
237   const uint32_t end_offset = debug_line_offset + prologue->TotalLength +
238                               sizeof(prologue->TotalLength);
239
240   state.reset();
241
242   while (*offset_ptr < end_offset) {
243     uint8_t opcode = debug_line_data.getU8(offset_ptr);
244
245     if (opcode == 0) {
246       // Extended Opcodes always start with a zero opcode followed by
247       // a uleb128 length so you can skip ones you don't know about
248       uint32_t ext_offset = *offset_ptr;
249       uint64_t len = debug_line_data.getULEB128(offset_ptr);
250       uint32_t arg_size = len - (*offset_ptr - ext_offset);
251
252       uint8_t sub_opcode = debug_line_data.getU8(offset_ptr);
253       switch (sub_opcode) {
254       case DW_LNE_end_sequence:
255         // Set the end_sequence register of the state machine to true and
256         // append a row to the matrix using the current values of the
257         // state-machine registers. Then reset the registers to the initial
258         // values specified above. Every statement program sequence must end
259         // with a DW_LNE_end_sequence instruction which creates a row whose
260         // address is that of the byte after the last target machine instruction
261         // of the sequence.
262         state.EndSequence = true;
263         state.appendRowToMatrix(*offset_ptr);
264         state.reset();
265         break;
266
267       case DW_LNE_set_address:
268         // Takes a single relocatable address as an operand. The size of the
269         // operand is the size appropriate to hold an address on the target
270         // machine. Set the address register to the value given by the
271         // relocatable address. All of the other statement program opcodes
272         // that affect the address register add a delta to it. This instruction
273         // stores a relocatable value into it instead.
274         {
275           // If this address is in our relocation map, apply the relocation.
276           RelocAddrMap::const_iterator AI = RMap->find(*offset_ptr);
277           if (AI != RMap->end()) {
278              const std::pair<uint8_t, int64_t> &R = AI->second;
279              state.Address = debug_line_data.getAddress(offset_ptr) + R.second;
280           } else
281             state.Address = debug_line_data.getAddress(offset_ptr);
282         }
283         break;
284
285       case DW_LNE_define_file:
286         // Takes 4 arguments. The first is a null terminated string containing
287         // a source file name. The second is an unsigned LEB128 number
288         // representing the directory index of the directory in which the file
289         // was found. The third is an unsigned LEB128 number representing the
290         // time of last modification of the file. The fourth is an unsigned
291         // LEB128 number representing the length in bytes of the file. The time
292         // and length fields may contain LEB128(0) if the information is not
293         // available.
294         //
295         // The directory index represents an entry in the include_directories
296         // section of the statement program prologue. The index is LEB128(0)
297         // if the file was found in the current directory of the compilation,
298         // LEB128(1) if it was found in the first directory in the
299         // include_directories section, and so on. The directory index is
300         // ignored for file names that represent full path names.
301         //
302         // The files are numbered, starting at 1, in the order in which they
303         // appear; the names in the prologue come before names defined by
304         // the DW_LNE_define_file instruction. These numbers are used in the
305         // the file register of the state machine.
306         {
307           FileNameEntry fileEntry;
308           fileEntry.Name = debug_line_data.getCStr(offset_ptr);
309           fileEntry.DirIdx = debug_line_data.getULEB128(offset_ptr);
310           fileEntry.ModTime = debug_line_data.getULEB128(offset_ptr);
311           fileEntry.Length = debug_line_data.getULEB128(offset_ptr);
312           prologue->FileNames.push_back(fileEntry);
313         }
314         break;
315
316       case DW_LNE_set_discriminator:
317         state.Discriminator = debug_line_data.getULEB128(offset_ptr);
318         break;
319
320       default:
321         // Length doesn't include the zero opcode byte or the length itself, but
322         // it does include the sub_opcode, so we have to adjust for that below
323         (*offset_ptr) += arg_size;
324         break;
325       }
326     } else if (opcode < prologue->OpcodeBase) {
327       switch (opcode) {
328       // Standard Opcodes
329       case DW_LNS_copy:
330         // Takes no arguments. Append a row to the matrix using the
331         // current values of the state-machine registers. Then set
332         // the basic_block register to false.
333         state.appendRowToMatrix(*offset_ptr);
334         break;
335
336       case DW_LNS_advance_pc:
337         // Takes a single unsigned LEB128 operand, multiplies it by the
338         // min_inst_length field of the prologue, and adds the
339         // result to the address register of the state machine.
340         state.Address += debug_line_data.getULEB128(offset_ptr) *
341                          prologue->MinInstLength;
342         break;
343
344       case DW_LNS_advance_line:
345         // Takes a single signed LEB128 operand and adds that value to
346         // the line register of the state machine.
347         state.Line += debug_line_data.getSLEB128(offset_ptr);
348         break;
349
350       case DW_LNS_set_file:
351         // Takes a single unsigned LEB128 operand and stores it in the file
352         // register of the state machine.
353         state.File = debug_line_data.getULEB128(offset_ptr);
354         break;
355
356       case DW_LNS_set_column:
357         // Takes a single unsigned LEB128 operand and stores it in the
358         // column register of the state machine.
359         state.Column = debug_line_data.getULEB128(offset_ptr);
360         break;
361
362       case DW_LNS_negate_stmt:
363         // Takes no arguments. Set the is_stmt register of the state
364         // machine to the logical negation of its current value.
365         state.IsStmt = !state.IsStmt;
366         break;
367
368       case DW_LNS_set_basic_block:
369         // Takes no arguments. Set the basic_block register of the
370         // state machine to true
371         state.BasicBlock = true;
372         break;
373
374       case DW_LNS_const_add_pc:
375         // Takes no arguments. Add to the address register of the state
376         // machine the address increment value corresponding to special
377         // opcode 255. The motivation for DW_LNS_const_add_pc is this:
378         // when the statement program needs to advance the address by a
379         // small amount, it can use a single special opcode, which occupies
380         // a single byte. When it needs to advance the address by up to
381         // twice the range of the last special opcode, it can use
382         // DW_LNS_const_add_pc followed by a special opcode, for a total
383         // of two bytes. Only if it needs to advance the address by more
384         // than twice that range will it need to use both DW_LNS_advance_pc
385         // and a special opcode, requiring three or more bytes.
386         {
387           uint8_t adjust_opcode = 255 - prologue->OpcodeBase;
388           uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
389                                  prologue->MinInstLength;
390           state.Address += addr_offset;
391         }
392         break;
393
394       case DW_LNS_fixed_advance_pc:
395         // Takes a single uhalf operand. Add to the address register of
396         // the state machine the value of the (unencoded) operand. This
397         // is the only extended opcode that takes an argument that is not
398         // a variable length number. The motivation for DW_LNS_fixed_advance_pc
399         // is this: existing assemblers cannot emit DW_LNS_advance_pc or
400         // special opcodes because they cannot encode LEB128 numbers or
401         // judge when the computation of a special opcode overflows and
402         // requires the use of DW_LNS_advance_pc. Such assemblers, however,
403         // can use DW_LNS_fixed_advance_pc instead, sacrificing compression.
404         state.Address += debug_line_data.getU16(offset_ptr);
405         break;
406
407       case DW_LNS_set_prologue_end:
408         // Takes no arguments. Set the prologue_end register of the
409         // state machine to true
410         state.PrologueEnd = true;
411         break;
412
413       case DW_LNS_set_epilogue_begin:
414         // Takes no arguments. Set the basic_block register of the
415         // state machine to true
416         state.EpilogueBegin = true;
417         break;
418
419       case DW_LNS_set_isa:
420         // Takes a single unsigned LEB128 operand and stores it in the
421         // column register of the state machine.
422         state.Isa = debug_line_data.getULEB128(offset_ptr);
423         break;
424
425       default:
426         // Handle any unknown standard opcodes here. We know the lengths
427         // of such opcodes because they are specified in the prologue
428         // as a multiple of LEB128 operands for each opcode.
429         {
430           assert(opcode - 1U < prologue->StandardOpcodeLengths.size());
431           uint8_t opcode_length = prologue->StandardOpcodeLengths[opcode - 1];
432           for (uint8_t i=0; i<opcode_length; ++i)
433             debug_line_data.getULEB128(offset_ptr);
434         }
435         break;
436       }
437     } else {
438       // Special Opcodes
439
440       // A special opcode value is chosen based on the amount that needs
441       // to be added to the line and address registers. The maximum line
442       // increment for a special opcode is the value of the line_base
443       // field in the header, plus the value of the line_range field,
444       // minus 1 (line base + line range - 1). If the desired line
445       // increment is greater than the maximum line increment, a standard
446       // opcode must be used instead of a special opcode. The "address
447       // advance" is calculated by dividing the desired address increment
448       // by the minimum_instruction_length field from the header. The
449       // special opcode is then calculated using the following formula:
450       //
451       //  opcode = (desired line increment - line_base) +
452       //           (line_range * address advance) + opcode_base
453       //
454       // If the resulting opcode is greater than 255, a standard opcode
455       // must be used instead.
456       //
457       // To decode a special opcode, subtract the opcode_base from the
458       // opcode itself to give the adjusted opcode. The amount to
459       // increment the address register is the result of the adjusted
460       // opcode divided by the line_range multiplied by the
461       // minimum_instruction_length field from the header. That is:
462       //
463       //  address increment = (adjusted opcode / line_range) *
464       //                      minimum_instruction_length
465       //
466       // The amount to increment the line register is the line_base plus
467       // the result of the adjusted opcode modulo the line_range. That is:
468       //
469       // line increment = line_base + (adjusted opcode % line_range)
470
471       uint8_t adjust_opcode = opcode - prologue->OpcodeBase;
472       uint64_t addr_offset = (adjust_opcode / prologue->LineRange) *
473                              prologue->MinInstLength;
474       int32_t line_offset = prologue->LineBase +
475                             (adjust_opcode % prologue->LineRange);
476       state.Line += line_offset;
477       state.Address += addr_offset;
478       state.appendRowToMatrix(*offset_ptr);
479     }
480   }
481
482   state.finalize();
483
484   return end_offset;
485 }
486
487 uint32_t
488 DWARFDebugLine::LineTable::lookupAddress(uint64_t address) const {
489   uint32_t unknown_index = UINT32_MAX;
490   if (Sequences.empty())
491     return unknown_index;
492   // First, find an instruction sequence containing the given address.
493   DWARFDebugLine::Sequence sequence;
494   sequence.LowPC = address;
495   SequenceIter first_seq = Sequences.begin();
496   SequenceIter last_seq = Sequences.end();
497   SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
498       DWARFDebugLine::Sequence::orderByLowPC);
499   DWARFDebugLine::Sequence found_seq;
500   if (seq_pos == last_seq) {
501     found_seq = Sequences.back();
502   } else if (seq_pos->LowPC == address) {
503     found_seq = *seq_pos;
504   } else {
505     if (seq_pos == first_seq)
506       return unknown_index;
507     found_seq = *(seq_pos - 1);
508   }
509   if (!found_seq.containsPC(address))
510     return unknown_index;
511   // Search for instruction address in the rows describing the sequence.
512   // Rows are stored in a vector, so we may use arithmetical operations with
513   // iterators.
514   DWARFDebugLine::Row row;
515   row.Address = address;
516   RowIter first_row = Rows.begin() + found_seq.FirstRowIndex;
517   RowIter last_row = Rows.begin() + found_seq.LastRowIndex;
518   RowIter row_pos = std::lower_bound(first_row, last_row, row,
519       DWARFDebugLine::Row::orderByAddress);
520   if (row_pos == last_row) {
521     return found_seq.LastRowIndex - 1;
522   }
523   uint32_t index = found_seq.FirstRowIndex + (row_pos - first_row);
524   if (row_pos->Address > address) {
525     if (row_pos == first_row)
526       return unknown_index;
527     else
528       index--;
529   }
530   return index;
531 }
532
533 bool
534 DWARFDebugLine::LineTable::lookupAddressRange(uint64_t address,
535                                        uint64_t size, 
536                                        std::vector<uint32_t>& result) const {
537   if (Sequences.empty())
538     return false;
539   uint64_t end_addr = address + size;
540   // First, find an instruction sequence containing the given address.
541   DWARFDebugLine::Sequence sequence;
542   sequence.LowPC = address;
543   SequenceIter first_seq = Sequences.begin();
544   SequenceIter last_seq = Sequences.end();
545   SequenceIter seq_pos = std::lower_bound(first_seq, last_seq, sequence,
546       DWARFDebugLine::Sequence::orderByLowPC);
547   if (seq_pos == last_seq || seq_pos->LowPC != address) {
548     if (seq_pos == first_seq)
549       return false;
550     seq_pos--;
551   }
552   if (!seq_pos->containsPC(address))
553     return false;
554
555   SequenceIter start_pos = seq_pos;
556
557   // Add the rows from the first sequence to the vector, starting with the
558   // index we just calculated
559
560   while (seq_pos != last_seq && seq_pos->LowPC < end_addr) {
561     DWARFDebugLine::Sequence cur_seq = *seq_pos;
562     uint32_t first_row_index;
563     uint32_t last_row_index;
564     if (seq_pos == start_pos) {
565       // For the first sequence, we need to find which row in the sequence is the
566       // first in our range. Rows are stored in a vector, so we may use
567       // arithmetical operations with iterators.
568       DWARFDebugLine::Row row;
569       row.Address = address;
570       RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
571       RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
572       RowIter row_pos = std::upper_bound(first_row, last_row, row,
573                                          DWARFDebugLine::Row::orderByAddress);
574       // The 'row_pos' iterator references the first row that is greater than
575       // our start address. Unless that's the first row, we want to start at
576       // the row before that.
577       first_row_index = cur_seq.FirstRowIndex + (row_pos - first_row);
578       if (row_pos != first_row)
579         --first_row_index;
580     } else
581       first_row_index = cur_seq.FirstRowIndex;
582
583     // For the last sequence in our range, we need to figure out the last row in
584     // range.  For all other sequences we can go to the end of the sequence.
585     if (cur_seq.HighPC > end_addr) {
586       DWARFDebugLine::Row row;
587       row.Address = end_addr;
588       RowIter first_row = Rows.begin() + cur_seq.FirstRowIndex;
589       RowIter last_row = Rows.begin() + cur_seq.LastRowIndex;
590       RowIter row_pos = std::upper_bound(first_row, last_row, row,
591                                          DWARFDebugLine::Row::orderByAddress);
592       // The 'row_pos' iterator references the first row that is greater than
593       // our end address.  The row before that is the last row we want.
594       last_row_index = cur_seq.FirstRowIndex + (row_pos - first_row) - 1;
595     } else
596       // Contrary to what you might expect, DWARFDebugLine::SequenceLastRowIndex
597       // isn't a valid index within the current sequence.  It's that plus one.
598       last_row_index = cur_seq.LastRowIndex - 1;
599
600     for (uint32_t i = first_row_index; i <= last_row_index; ++i) {
601       result.push_back(i);
602     }
603
604     ++seq_pos;
605   }
606
607   return true;
608 }
609
610 bool
611 DWARFDebugLine::LineTable::getFileNameByIndex(uint64_t FileIndex,
612                                               bool NeedsAbsoluteFilePath,
613                                               std::string &Result) const {
614   if (FileIndex == 0 || FileIndex > Prologue.FileNames.size())
615     return false;
616   const FileNameEntry &Entry = Prologue.FileNames[FileIndex - 1];
617   const char *FileName = Entry.Name;
618   if (!NeedsAbsoluteFilePath ||
619       sys::path::is_absolute(FileName)) {
620     Result = FileName;
621     return true;
622   }
623   SmallString<16> FilePath;
624   uint64_t IncludeDirIndex = Entry.DirIdx;
625   // Be defensive about the contents of Entry.
626   if (IncludeDirIndex > 0 &&
627       IncludeDirIndex <= Prologue.IncludeDirectories.size()) {
628     const char *IncludeDir = Prologue.IncludeDirectories[IncludeDirIndex - 1];
629     sys::path::append(FilePath, IncludeDir);
630   }
631   sys::path::append(FilePath, FileName);
632   Result = FilePath.str();
633   return true;
634 }