InstCombine: Modernize a bunch of cast combines.
[oota-llvm.git] / lib / DebugInfo / DWARFContext.cpp
1 //===-- DWARFContext.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 "DWARFContext.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/Support/Compression.h"
15 #include "llvm/Support/Dwarf.h"
16 #include "llvm/Support/Format.h"
17 #include "llvm/Support/Path.h"
18 #include "llvm/Support/raw_ostream.h"
19 #include <algorithm>
20 using namespace llvm;
21 using namespace dwarf;
22 using namespace object;
23
24 typedef DWARFDebugLine::LineTable DWARFLineTable;
25
26 DWARFContext::~DWARFContext() {
27   DeleteContainerPointers(CUs);
28   DeleteContainerPointers(TUs);
29   DeleteContainerPointers(DWOCUs);
30 }
31
32 static void dumpPubSection(raw_ostream &OS, StringRef Name, StringRef Data,
33                            bool LittleEndian, bool GnuStyle) {
34   OS << "\n." << Name << " contents:\n";
35   DataExtractor pubNames(Data, LittleEndian, 0);
36   uint32_t offset = 0;
37   while (pubNames.isValidOffset(offset)) {
38     OS << "length = " << format("0x%08x", pubNames.getU32(&offset));
39     OS << " version = " << format("0x%04x", pubNames.getU16(&offset));
40     OS << " unit_offset = " << format("0x%08x", pubNames.getU32(&offset));
41     OS << " unit_size = " << format("0x%08x", pubNames.getU32(&offset)) << '\n';
42     if (GnuStyle)
43       OS << "Offset     Linkage  Kind     Name\n";
44     else
45       OS << "Offset     Name\n";
46
47     while (offset < Data.size()) {
48       uint32_t dieRef = pubNames.getU32(&offset);
49       if (dieRef == 0)
50         break;
51       OS << format("0x%8.8x ", dieRef);
52       if (GnuStyle) {
53         PubIndexEntryDescriptor desc(pubNames.getU8(&offset));
54         OS << format("%-8s", dwarf::GDBIndexEntryLinkageString(desc.Linkage))
55            << ' ' << format("%-8s", dwarf::GDBIndexEntryKindString(desc.Kind))
56            << ' ';
57       }
58       OS << '\"' << pubNames.getCStr(&offset) << "\"\n";
59     }
60   }
61 }
62
63 void DWARFContext::dump(raw_ostream &OS, DIDumpType DumpType) {
64   if (DumpType == DIDT_All || DumpType == DIDT_Abbrev) {
65     OS << ".debug_abbrev contents:\n";
66     getDebugAbbrev()->dump(OS);
67   }
68
69   if (DumpType == DIDT_All || DumpType == DIDT_AbbrevDwo)
70     if (const DWARFDebugAbbrev *D = getDebugAbbrevDWO()) {
71       OS << "\n.debug_abbrev.dwo contents:\n";
72       D->dump(OS);
73     }
74
75   if (DumpType == DIDT_All || DumpType == DIDT_Info) {
76     OS << "\n.debug_info contents:\n";
77     for (unsigned i = 0, e = getNumCompileUnits(); i != e; ++i)
78       getCompileUnitAtIndex(i)->dump(OS);
79   }
80
81   if ((DumpType == DIDT_All || DumpType == DIDT_InfoDwo) &&
82       getNumDWOCompileUnits()) {
83     OS << "\n.debug_info.dwo contents:\n";
84     for (unsigned i = 0, e = getNumDWOCompileUnits(); i != e; ++i)
85       getDWOCompileUnitAtIndex(i)->dump(OS);
86   }
87
88   if ((DumpType == DIDT_All || DumpType == DIDT_Types) && getNumTypeUnits()) {
89     OS << "\n.debug_types contents:\n";
90     for (unsigned i = 0, e = getNumTypeUnits(); i != e; ++i)
91       getTypeUnitAtIndex(i)->dump(OS);
92   }
93
94   if (DumpType == DIDT_All || DumpType == DIDT_TypesDwo)
95     if (getNumDWOTypeUnits()) {
96       OS << "\n.debug_types.dwo contents:\n";
97       for (unsigned i = 0, e = getNumDWOTypeUnits(); i != e; ++i)
98         getDWOTypeUnitAtIndex(i)->dump(OS);
99     }
100
101   if (DumpType == DIDT_All || DumpType == DIDT_Loc) {
102     OS << "\n.debug_loc contents:\n";
103     getDebugLoc()->dump(OS);
104   }
105
106   if (DumpType == DIDT_All || DumpType == DIDT_Frames) {
107     OS << "\n.debug_frame contents:\n";
108     getDebugFrame()->dump(OS);
109   }
110
111   uint32_t offset = 0;
112   if (DumpType == DIDT_All || DumpType == DIDT_Aranges) {
113     OS << "\n.debug_aranges contents:\n";
114     DataExtractor arangesData(getARangeSection(), isLittleEndian(), 0);
115     DWARFDebugArangeSet set;
116     while (set.extract(arangesData, &offset))
117       set.dump(OS);
118   }
119
120   uint8_t savedAddressByteSize = 0;
121   if (DumpType == DIDT_All || DumpType == DIDT_Line) {
122     OS << "\n.debug_line contents:\n";
123     for (unsigned i = 0, e = getNumCompileUnits(); i != e; ++i) {
124       DWARFCompileUnit *cu = getCompileUnitAtIndex(i);
125       savedAddressByteSize = cu->getAddressByteSize();
126       unsigned stmtOffset =
127           cu->getCompileUnitDIE()->getAttributeValueAsSectionOffset(
128               cu, DW_AT_stmt_list, -1U);
129       if (stmtOffset != -1U) {
130         DataExtractor lineData(getLineSection().Data, isLittleEndian(),
131                                savedAddressByteSize);
132         DWARFDebugLine::DumpingState state(OS);
133         DWARFDebugLine::parseStatementTable(lineData, &getLineSection().Relocs, &stmtOffset, state);
134       }
135     }
136   }
137
138   if (DumpType == DIDT_All || DumpType == DIDT_Str) {
139     OS << "\n.debug_str contents:\n";
140     DataExtractor strData(getStringSection(), isLittleEndian(), 0);
141     offset = 0;
142     uint32_t strOffset = 0;
143     while (const char *s = strData.getCStr(&offset)) {
144       OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
145       strOffset = offset;
146     }
147   }
148
149   if ((DumpType == DIDT_All || DumpType == DIDT_StrDwo) &&
150       !getStringDWOSection().empty()) {
151     OS << "\n.debug_str.dwo contents:\n";
152     DataExtractor strDWOData(getStringDWOSection(), isLittleEndian(), 0);
153     offset = 0;
154     uint32_t strDWOOffset = 0;
155     while (const char *s = strDWOData.getCStr(&offset)) {
156       OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
157       strDWOOffset = offset;
158     }
159   }
160
161   if (DumpType == DIDT_All || DumpType == DIDT_Ranges) {
162     OS << "\n.debug_ranges contents:\n";
163     // In fact, different compile units may have different address byte
164     // sizes, but for simplicity we just use the address byte size of the last
165     // compile unit (there is no easy and fast way to associate address range
166     // list and the compile unit it describes).
167     DataExtractor rangesData(getRangeSection(), isLittleEndian(),
168                              savedAddressByteSize);
169     offset = 0;
170     DWARFDebugRangeList rangeList;
171     while (rangeList.extract(rangesData, &offset))
172       rangeList.dump(OS);
173   }
174
175   if (DumpType == DIDT_All || DumpType == DIDT_Pubnames)
176     dumpPubSection(OS, "debug_pubnames", getPubNamesSection(),
177                    isLittleEndian(), false);
178
179   if (DumpType == DIDT_All || DumpType == DIDT_Pubtypes)
180     dumpPubSection(OS, "debug_pubtypes", getPubTypesSection(),
181                    isLittleEndian(), false);
182
183   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubnames)
184     dumpPubSection(OS, "debug_gnu_pubnames", getGnuPubNamesSection(),
185                    isLittleEndian(), true /* GnuStyle */);
186
187   if (DumpType == DIDT_All || DumpType == DIDT_GnuPubtypes)
188     dumpPubSection(OS, "debug_gnu_pubtypes", getGnuPubTypesSection(),
189                    isLittleEndian(), true /* GnuStyle */);
190
191   if ((DumpType == DIDT_All || DumpType == DIDT_StrOffsetsDwo) &&
192       !getStringOffsetDWOSection().empty()) {
193     OS << "\n.debug_str_offsets.dwo contents:\n";
194     DataExtractor strOffsetExt(getStringOffsetDWOSection(), isLittleEndian(),
195                                0);
196     offset = 0;
197     uint64_t size = getStringOffsetDWOSection().size();
198     while (offset < size) {
199       OS << format("0x%8.8x: ", offset);
200       OS << format("%8.8x\n", strOffsetExt.getU32(&offset));
201     }
202   }
203 }
204
205 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrev() {
206   if (Abbrev)
207     return Abbrev.get();
208
209   DataExtractor abbrData(getAbbrevSection(), isLittleEndian(), 0);
210
211   Abbrev.reset(new DWARFDebugAbbrev());
212   Abbrev->parse(abbrData);
213   return Abbrev.get();
214 }
215
216 const DWARFDebugAbbrev *DWARFContext::getDebugAbbrevDWO() {
217   if (AbbrevDWO)
218     return AbbrevDWO.get();
219
220   DataExtractor abbrData(getAbbrevDWOSection(), isLittleEndian(), 0);
221   AbbrevDWO.reset(new DWARFDebugAbbrev());
222   AbbrevDWO->parse(abbrData);
223   return AbbrevDWO.get();
224 }
225
226 const DWARFDebugLoc *DWARFContext::getDebugLoc() {
227   if (Loc)
228     return Loc.get();
229
230   DataExtractor LocData(getLocSection().Data, isLittleEndian(), 0);
231   Loc.reset(new DWARFDebugLoc(getLocSection().Relocs));
232   // assume all compile units have the same address byte size
233   if (getNumCompileUnits())
234     Loc->parse(LocData, getCompileUnitAtIndex(0)->getAddressByteSize());
235   return Loc.get();
236 }
237
238 const DWARFDebugAranges *DWARFContext::getDebugAranges() {
239   if (Aranges)
240     return Aranges.get();
241
242   Aranges.reset(new DWARFDebugAranges());
243   Aranges->generate(this);
244   return Aranges.get();
245 }
246
247 const DWARFDebugFrame *DWARFContext::getDebugFrame() {
248   if (DebugFrame)
249     return DebugFrame.get();
250
251   // There's a "bug" in the DWARFv3 standard with respect to the target address
252   // size within debug frame sections. While DWARF is supposed to be independent
253   // of its container, FDEs have fields with size being "target address size",
254   // which isn't specified in DWARF in general. It's only specified for CUs, but
255   // .eh_frame can appear without a .debug_info section. Follow the example of
256   // other tools (libdwarf) and extract this from the container (ObjectFile
257   // provides this information). This problem is fixed in DWARFv4
258   // See this dwarf-discuss discussion for more details:
259   // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
260   DataExtractor debugFrameData(getDebugFrameSection(), isLittleEndian(),
261                                getAddressSize());
262   DebugFrame.reset(new DWARFDebugFrame());
263   DebugFrame->parse(debugFrameData);
264   return DebugFrame.get();
265 }
266
267 const DWARFLineTable *
268 DWARFContext::getLineTableForCompileUnit(DWARFCompileUnit *cu) {
269   if (!Line)
270     Line.reset(new DWARFDebugLine(&getLineSection().Relocs));
271
272   unsigned stmtOffset =
273       cu->getCompileUnitDIE()->getAttributeValueAsSectionOffset(
274           cu, DW_AT_stmt_list, -1U);
275   if (stmtOffset == -1U)
276     return 0; // No line table for this compile unit.
277
278   // See if the line table is cached.
279   if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
280     return lt;
281
282   // We have to parse it first.
283   DataExtractor lineData(getLineSection().Data, isLittleEndian(),
284                          cu->getAddressByteSize());
285   return Line->getOrParseLineTable(lineData, stmtOffset);
286 }
287
288 void DWARFContext::parseCompileUnits() {
289   uint32_t offset = 0;
290   const DataExtractor &DIData = DataExtractor(getInfoSection().Data,
291                                               isLittleEndian(), 0);
292   while (DIData.isValidOffset(offset)) {
293     OwningPtr<DWARFCompileUnit> CU(new DWARFCompileUnit(
294         getDebugAbbrev(), getInfoSection().Data, getAbbrevSection(),
295         getRangeSection(), getStringSection(), StringRef(), getAddrSection(),
296         &getInfoSection().Relocs, isLittleEndian()));
297     if (!CU->extract(DIData, &offset)) {
298       break;
299     }
300     CUs.push_back(CU.take());
301     offset = CUs.back()->getNextUnitOffset();
302   }
303 }
304
305 void DWARFContext::parseTypeUnits() {
306   const TypeSectionMap &Sections = getTypesSections();
307   for (TypeSectionMap::const_iterator I = Sections.begin(), E = Sections.end();
308        I != E; ++I) {
309     uint32_t offset = 0;
310     const DataExtractor &DIData =
311         DataExtractor(I->second.Data, isLittleEndian(), 0);
312     while (DIData.isValidOffset(offset)) {
313       OwningPtr<DWARFTypeUnit> TU(new DWARFTypeUnit(
314           getDebugAbbrev(), I->second.Data, getAbbrevSection(),
315           getRangeSection(), getStringSection(), StringRef(), getAddrSection(),
316           &I->second.Relocs, isLittleEndian()));
317       if (!TU->extract(DIData, &offset))
318         break;
319       TUs.push_back(TU.take());
320       offset = TUs.back()->getNextUnitOffset();
321     }
322   }
323 }
324
325 void DWARFContext::parseDWOCompileUnits() {
326   uint32_t offset = 0;
327   const DataExtractor &DIData =
328       DataExtractor(getInfoDWOSection().Data, isLittleEndian(), 0);
329   while (DIData.isValidOffset(offset)) {
330     OwningPtr<DWARFCompileUnit> DWOCU(new DWARFCompileUnit(
331         getDebugAbbrevDWO(), getInfoDWOSection().Data, getAbbrevDWOSection(),
332         getRangeDWOSection(), getStringDWOSection(),
333         getStringOffsetDWOSection(), getAddrSection(),
334         &getInfoDWOSection().Relocs, isLittleEndian()));
335     if (!DWOCU->extract(DIData, &offset)) {
336       break;
337     }
338     DWOCUs.push_back(DWOCU.take());
339     offset = DWOCUs.back()->getNextUnitOffset();
340   }
341 }
342
343 void DWARFContext::parseDWOTypeUnits() {
344   const TypeSectionMap &Sections = getTypesDWOSections();
345   for (TypeSectionMap::const_iterator I = Sections.begin(), E = Sections.end();
346        I != E; ++I) {
347     uint32_t offset = 0;
348     const DataExtractor &DIData =
349         DataExtractor(I->second.Data, isLittleEndian(), 0);
350     while (DIData.isValidOffset(offset)) {
351       OwningPtr<DWARFTypeUnit> TU(new DWARFTypeUnit(
352           getDebugAbbrevDWO(), I->second.Data, getAbbrevDWOSection(),
353           getRangeDWOSection(), getStringDWOSection(),
354           getStringOffsetDWOSection(), getAddrSection(), &I->second.Relocs,
355           isLittleEndian()));
356       if (!TU->extract(DIData, &offset))
357         break;
358       DWOTUs.push_back(TU.take());
359       offset = DWOTUs.back()->getNextUnitOffset();
360     }
361   }
362 }
363
364 namespace {
365   struct OffsetComparator {
366     bool operator()(const DWARFCompileUnit *LHS,
367                     const DWARFCompileUnit *RHS) const {
368       return LHS->getOffset() < RHS->getOffset();
369     }
370     bool operator()(const DWARFCompileUnit *LHS, uint32_t RHS) const {
371       return LHS->getOffset() < RHS;
372     }
373     bool operator()(uint32_t LHS, const DWARFCompileUnit *RHS) const {
374       return LHS < RHS->getOffset();
375     }
376   };
377 }
378
379 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
380   if (CUs.empty())
381     parseCompileUnits();
382
383   DWARFCompileUnit **CU =
384       std::lower_bound(CUs.begin(), CUs.end(), Offset, OffsetComparator());
385   if (CU != CUs.end()) {
386     return *CU;
387   }
388   return 0;
389 }
390
391 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
392   // First, get the offset of the compile unit.
393   uint32_t CUOffset = getDebugAranges()->findAddress(Address);
394   // Retrieve the compile unit.
395   return getCompileUnitForOffset(CUOffset);
396 }
397
398 static bool getFileNameForCompileUnit(DWARFCompileUnit *CU,
399                                       const DWARFLineTable *LineTable,
400                                       uint64_t FileIndex,
401                                       bool NeedsAbsoluteFilePath,
402                                       std::string &FileName) {
403   if (CU == 0 ||
404       LineTable == 0 ||
405       !LineTable->getFileNameByIndex(FileIndex, NeedsAbsoluteFilePath,
406                                      FileName))
407     return false;
408   if (NeedsAbsoluteFilePath && sys::path::is_relative(FileName)) {
409     // We may still need to append compilation directory of compile unit.
410     SmallString<16> AbsolutePath;
411     if (const char *CompilationDir = CU->getCompilationDir()) {
412       sys::path::append(AbsolutePath, CompilationDir);
413     }
414     sys::path::append(AbsolutePath, FileName);
415     FileName = AbsolutePath.str();
416   }
417   return true;
418 }
419
420 static bool getFileLineInfoForCompileUnit(DWARFCompileUnit *CU,
421                                           const DWARFLineTable *LineTable,
422                                           uint64_t Address,
423                                           bool NeedsAbsoluteFilePath,
424                                           std::string &FileName,
425                                           uint32_t &Line, uint32_t &Column) {
426   if (CU == 0 || LineTable == 0)
427     return false;
428   // Get the index of row we're looking for in the line table.
429   uint32_t RowIndex = LineTable->lookupAddress(Address);
430   if (RowIndex == -1U)
431     return false;
432   // Take file number and line/column from the row.
433   const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
434   if (!getFileNameForCompileUnit(CU, LineTable, Row.File,
435                                  NeedsAbsoluteFilePath, FileName))
436     return false;
437   Line = Row.Line;
438   Column = Row.Column;
439   return true;
440 }
441
442 DILineInfo DWARFContext::getLineInfoForAddress(uint64_t Address,
443     DILineInfoSpecifier Specifier) {
444   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
445   if (!CU)
446     return DILineInfo();
447   std::string FileName = "<invalid>";
448   std::string FunctionName = "<invalid>";
449   uint32_t Line = 0;
450   uint32_t Column = 0;
451   if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
452     // The address may correspond to instruction in some inlined function,
453     // so we have to build the chain of inlined functions and take the
454     // name of the topmost function in it.
455     const DWARFDebugInfoEntryInlinedChain &InlinedChain =
456         CU->getInlinedChainForAddress(Address);
457     if (InlinedChain.DIEs.size() > 0) {
458       const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
459       if (const char *Name = TopFunctionDIE.getSubroutineName(InlinedChain.U))
460         FunctionName = Name;
461     }
462   }
463   if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
464     const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
465     const bool NeedsAbsoluteFilePath =
466         Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
467     getFileLineInfoForCompileUnit(CU, LineTable, Address,
468                                   NeedsAbsoluteFilePath,
469                                   FileName, Line, Column);
470   }
471   return DILineInfo(StringRef(FileName), StringRef(FunctionName),
472                     Line, Column);
473 }
474
475 DILineInfoTable DWARFContext::getLineInfoForAddressRange(uint64_t Address,
476     uint64_t Size,
477     DILineInfoSpecifier Specifier) {
478   DILineInfoTable  Lines;
479   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
480   if (!CU)
481     return Lines;
482
483   std::string FunctionName = "<invalid>";
484   if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
485     // The address may correspond to instruction in some inlined function,
486     // so we have to build the chain of inlined functions and take the
487     // name of the topmost function in it.
488     const DWARFDebugInfoEntryInlinedChain &InlinedChain =
489         CU->getInlinedChainForAddress(Address);
490     if (InlinedChain.DIEs.size() > 0) {
491       const DWARFDebugInfoEntryMinimal &TopFunctionDIE = InlinedChain.DIEs[0];
492       if (const char *Name = TopFunctionDIE.getSubroutineName(InlinedChain.U))
493         FunctionName = Name;
494     }
495   }
496
497   // If the Specifier says we don't need FileLineInfo, just
498   // return the top-most function at the starting address.
499   if (!Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
500     Lines.push_back(
501         std::make_pair(Address, DILineInfo("<invalid>", FunctionName, 0, 0)));
502     return Lines;
503   }
504
505   const DWARFLineTable *LineTable = getLineTableForCompileUnit(CU);
506   const bool NeedsAbsoluteFilePath =
507       Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
508
509   // Get the index of row we're looking for in the line table.
510   std::vector<uint32_t> RowVector;
511   if (!LineTable->lookupAddressRange(Address, Size, RowVector))
512     return Lines;
513
514   uint32_t NumRows = RowVector.size();
515   for (uint32_t i = 0; i < NumRows; ++i) {
516     uint32_t RowIndex = RowVector[i];
517     // Take file number and line/column from the row.
518     const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
519     std::string FileName = "<invalid>";
520     getFileNameForCompileUnit(CU, LineTable, Row.File,
521                               NeedsAbsoluteFilePath, FileName);
522     Lines.push_back(std::make_pair(
523         Row.Address, DILineInfo(FileName, FunctionName, Row.Line, Row.Column)));
524   }
525
526   return Lines;
527 }
528
529 DIInliningInfo DWARFContext::getInliningInfoForAddress(uint64_t Address,
530     DILineInfoSpecifier Specifier) {
531   DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
532   if (!CU)
533     return DIInliningInfo();
534
535   const DWARFDebugInfoEntryInlinedChain &InlinedChain =
536       CU->getInlinedChainForAddress(Address);
537   if (InlinedChain.DIEs.size() == 0)
538     return DIInliningInfo();
539
540   DIInliningInfo InliningInfo;
541   uint32_t CallFile = 0, CallLine = 0, CallColumn = 0;
542   const DWARFLineTable *LineTable = 0;
543   for (uint32_t i = 0, n = InlinedChain.DIEs.size(); i != n; i++) {
544     const DWARFDebugInfoEntryMinimal &FunctionDIE = InlinedChain.DIEs[i];
545     std::string FileName = "<invalid>";
546     std::string FunctionName = "<invalid>";
547     uint32_t Line = 0;
548     uint32_t Column = 0;
549     // Get function name if necessary.
550     if (Specifier.needs(DILineInfoSpecifier::FunctionName)) {
551       if (const char *Name = FunctionDIE.getSubroutineName(InlinedChain.U))
552         FunctionName = Name;
553     }
554     if (Specifier.needs(DILineInfoSpecifier::FileLineInfo)) {
555       const bool NeedsAbsoluteFilePath =
556           Specifier.needs(DILineInfoSpecifier::AbsoluteFilePath);
557       if (i == 0) {
558         // For the topmost frame, initialize the line table of this
559         // compile unit and fetch file/line info from it.
560         LineTable = getLineTableForCompileUnit(CU);
561         // For the topmost routine, get file/line info from line table.
562         getFileLineInfoForCompileUnit(CU, LineTable, Address,
563                                       NeedsAbsoluteFilePath,
564                                       FileName, Line, Column);
565       } else {
566         // Otherwise, use call file, call line and call column from
567         // previous DIE in inlined chain.
568         getFileNameForCompileUnit(CU, LineTable, CallFile,
569                                   NeedsAbsoluteFilePath, FileName);
570         Line = CallLine;
571         Column = CallColumn;
572       }
573       // Get call file/line/column of a current DIE.
574       if (i + 1 < n) {
575         FunctionDIE.getCallerFrame(InlinedChain.U, CallFile, CallLine,
576                                    CallColumn);
577       }
578     }
579     DILineInfo Frame(StringRef(FileName), StringRef(FunctionName),
580                      Line, Column);
581     InliningInfo.addFrame(Frame);
582   }
583   return InliningInfo;
584 }
585
586 static bool consumeCompressedDebugSectionHeader(StringRef &data,
587                                                 uint64_t &OriginalSize) {
588   // Consume "ZLIB" prefix.
589   if (!data.startswith("ZLIB"))
590     return false;
591   data = data.substr(4);
592   // Consume uncompressed section size (big-endian 8 bytes).
593   DataExtractor extractor(data, false, 8);
594   uint32_t Offset = 0;
595   OriginalSize = extractor.getU64(&Offset);
596   if (Offset == 0)
597     return false;
598   data = data.substr(Offset);
599   return true;
600 }
601
602 DWARFContextInMemory::DWARFContextInMemory(object::ObjectFile *Obj) :
603   IsLittleEndian(Obj->isLittleEndian()),
604   AddressSize(Obj->getBytesInAddress()) {
605   error_code ec;
606   for (object::section_iterator i = Obj->begin_sections(),
607          e = Obj->end_sections();
608        i != e; i.increment(ec)) {
609     StringRef name;
610     i->getName(name);
611     StringRef data;
612     i->getContents(data);
613
614     name = name.substr(name.find_first_not_of("._")); // Skip . and _ prefixes.
615
616     // Check if debug info section is compressed with zlib.
617     if (name.startswith("zdebug_")) {
618       uint64_t OriginalSize;
619       if (!zlib::isAvailable() ||
620           !consumeCompressedDebugSectionHeader(data, OriginalSize))
621         continue;
622       OwningPtr<MemoryBuffer> UncompressedSection;
623       if (zlib::uncompress(data, UncompressedSection, OriginalSize) !=
624           zlib::StatusOK)
625         continue;
626       // Make data point to uncompressed section contents and save its contents.
627       name = name.substr(1);
628       data = UncompressedSection->getBuffer();
629       UncompressedSections.push_back(UncompressedSection.take());
630     }
631
632     StringRef *Section =
633         StringSwitch<StringRef *>(name)
634             .Case("debug_info", &InfoSection.Data)
635             .Case("debug_abbrev", &AbbrevSection)
636             .Case("debug_loc", &LocSection.Data)
637             .Case("debug_line", &LineSection.Data)
638             .Case("debug_aranges", &ARangeSection)
639             .Case("debug_frame", &DebugFrameSection)
640             .Case("debug_str", &StringSection)
641             .Case("debug_ranges", &RangeSection)
642             .Case("debug_pubnames", &PubNamesSection)
643             .Case("debug_pubtypes", &PubTypesSection)
644             .Case("debug_gnu_pubnames", &GnuPubNamesSection)
645             .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
646             .Case("debug_info.dwo", &InfoDWOSection.Data)
647             .Case("debug_abbrev.dwo", &AbbrevDWOSection)
648             .Case("debug_str.dwo", &StringDWOSection)
649             .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
650             .Case("debug_addr", &AddrSection)
651             // Any more debug info sections go here.
652             .Default(0);
653     if (Section) {
654       *Section = data;
655       if (name == "debug_ranges") {
656         // FIXME: Use the other dwo range section when we emit it.
657         RangeDWOSection = data;
658       }
659     } else if (name == "debug_types") {
660       // Find debug_types data by section rather than name as there are
661       // multiple, comdat grouped, debug_types sections.
662       TypesSections[*i].Data = data;
663     } else if (name == "debug_types.dwo") {
664       TypesDWOSections[*i].Data = data;
665     }
666
667     section_iterator RelocatedSection = i->getRelocatedSection();
668     if (RelocatedSection == Obj->end_sections())
669       continue;
670
671     StringRef RelSecName;
672     RelocatedSection->getName(RelSecName);
673     RelSecName = RelSecName.substr(
674         RelSecName.find_first_not_of("._")); // Skip . and _ prefixes.
675
676     // TODO: Add support for relocations in other sections as needed.
677     // Record relocations for the debug_info and debug_line sections.
678     RelocAddrMap *Map = StringSwitch<RelocAddrMap*>(RelSecName)
679         .Case("debug_info", &InfoSection.Relocs)
680         .Case("debug_loc", &LocSection.Relocs)
681         .Case("debug_info.dwo", &InfoDWOSection.Relocs)
682         .Case("debug_line", &LineSection.Relocs)
683         .Default(0);
684     if (!Map) {
685       // Find debug_types relocs by section rather than name as there are
686       // multiple, comdat grouped, debug_types sections.
687       if (RelSecName == "debug_types")
688         Map = &TypesSections[*RelocatedSection].Relocs;
689       else if (RelSecName == "debug_types.dwo")
690         Map = &TypesDWOSections[*RelocatedSection].Relocs;
691       else
692         continue;
693     }
694
695     if (i->begin_relocations() != i->end_relocations()) {
696       uint64_t SectionSize;
697       RelocatedSection->getSize(SectionSize);
698       for (object::relocation_iterator reloc_i = i->begin_relocations(),
699              reloc_e = i->end_relocations();
700            reloc_i != reloc_e; reloc_i.increment(ec)) {
701         uint64_t Address;
702         reloc_i->getOffset(Address);
703         uint64_t Type;
704         reloc_i->getType(Type);
705         uint64_t SymAddr = 0;
706         // ELF relocations may need the symbol address
707         if (Obj->isELF()) {
708           object::symbol_iterator Sym = reloc_i->getSymbol();
709           Sym->getAddress(SymAddr);
710         }
711
712         object::RelocVisitor V(Obj->getFileFormatName());
713         // The section address is always 0 for debug sections.
714         object::RelocToApply R(V.visit(Type, *reloc_i, 0, SymAddr));
715         if (V.error()) {
716           SmallString<32> Name;
717           error_code ec(reloc_i->getTypeName(Name));
718           if (ec) {
719             errs() << "Aaaaaa! Nameless relocation! Aaaaaa!\n";
720           }
721           errs() << "error: failed to compute relocation: "
722                  << Name << "\n";
723           continue;
724         }
725
726         if (Address + R.Width > SectionSize) {
727           errs() << "error: " << R.Width << "-byte relocation starting "
728                  << Address << " bytes into section " << name << " which is "
729                  << SectionSize << " bytes long.\n";
730           continue;
731         }
732         if (R.Width > 8) {
733           errs() << "error: can't handle a relocation of more than 8 bytes at "
734                     "a time.\n";
735           continue;
736         }
737         DEBUG(dbgs() << "Writing " << format("%p", R.Value)
738                      << " at " << format("%p", Address)
739                      << " with width " << format("%d", R.Width)
740                      << "\n");
741         Map->insert(std::make_pair(Address, std::make_pair(R.Width, R.Value)));
742       }
743     }
744   }
745 }
746
747 DWARFContextInMemory::~DWARFContextInMemory() {
748   DeleteContainerPointers(UncompressedSections);
749 }
750
751 void DWARFContextInMemory::anchor() { }