blob: a6aa1b79070e550589895cddf8a5c72436a8e275 [file] [log] [blame]
Daniel Jasper0f778692016-12-08 12:45:29 +00001//===--- unittests/DebugInfo/DWARF/DwarfGenerator.cpp -----------*- C++ -*-===//
Greg Clayton3462a422016-12-08 01:03:48 +00002//
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 "DwarfGenerator.h"
Chandler Carruth9a67b072017-06-06 11:06:56 +000011#include "../lib/CodeGen/AsmPrinter/DwarfStringPool.h"
Greg Clayton3462a422016-12-08 01:03:48 +000012#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000013#include "llvm/BinaryFormat/Dwarf.h"
Greg Clayton3462a422016-12-08 01:03:48 +000014#include "llvm/CodeGen/AsmPrinter.h"
15#include "llvm/CodeGen/DIE.h"
Greg Clayton3462a422016-12-08 01:03:48 +000016#include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
17#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
Greg Clayton3462a422016-12-08 01:03:48 +000018#include "llvm/MC/MCAsmBackend.h"
19#include "llvm/MC/MCAsmInfo.h"
20#include "llvm/MC/MCCodeEmitter.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCDwarf.h"
23#include "llvm/MC/MCInstrInfo.h"
24#include "llvm/MC/MCObjectFileInfo.h"
25#include "llvm/MC/MCRegisterInfo.h"
26#include "llvm/MC/MCStreamer.h"
27#include "llvm/MC/MCSubtargetInfo.h"
David Blaikie4333f972018-04-11 18:49:37 +000028#include "llvm/MC/MCTargetOptionsCommandFlags.inc"
Greg Clayton3462a422016-12-08 01:03:48 +000029#include "llvm/PassAnalysisSupport.h"
Greg Clayton3462a422016-12-08 01:03:48 +000030#include "llvm/Support/TargetRegistry.h"
31#include "llvm/Support/raw_ostream.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetOptions.h"
34
35using namespace llvm;
36using namespace dwarf;
37
38namespace {} // end anonymous namespace
39
40//===----------------------------------------------------------------------===//
41/// dwarfgen::DIE implementation.
42//===----------------------------------------------------------------------===//
43unsigned dwarfgen::DIE::computeSizeAndOffsets(unsigned Offset) {
44 auto &DG = CU->getGenerator();
45 return Die->computeOffsetsAndAbbrevs(DG.getAsmPrinter(), DG.getAbbrevSet(),
46 Offset);
47}
48
49void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form, uint64_t U) {
50 auto &DG = CU->getGenerator();
51 Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form,
52 DIEInteger(U));
53}
54
55void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form,
56 StringRef String) {
57 auto &DG = CU->getGenerator();
58 if (Form == DW_FORM_string) {
59 Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form,
Benjamin Kramereedc4052016-12-09 13:33:41 +000060 new (DG.getAllocator())
61 DIEInlineString(String, DG.getAllocator()));
Greg Clayton3462a422016-12-08 01:03:48 +000062 } else {
63 Die->addValue(
64 DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form,
65 DIEString(DG.getStringPool().getEntry(*DG.getAsmPrinter(), String)));
66 }
67}
68
69void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form,
70 dwarfgen::DIE &RefDie) {
71 auto &DG = CU->getGenerator();
72 Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form,
73 DIEEntry(*RefDie.Die));
74}
75
76void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form, const void *P,
77 size_t S) {
78 auto &DG = CU->getGenerator();
79 DIEBlock *Block = new (DG.getAllocator()) DIEBlock;
80 for (size_t I = 0; I < S; ++I)
Saleem Abdulrasoolecf13bb2016-12-27 18:35:24 +000081 Block->addValue(
82 DG.getAllocator(), (dwarf::Attribute)0, dwarf::DW_FORM_data1,
83 DIEInteger(
84 (const_cast<uint8_t *>(static_cast<const uint8_t *>(P)))[I]));
Greg Clayton3462a422016-12-08 01:03:48 +000085
86 Block->ComputeSize(DG.getAsmPrinter());
87 Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form,
88 Block);
89}
90
91void dwarfgen::DIE::addAttribute(uint16_t A, dwarf::Form Form) {
92 auto &DG = CU->getGenerator();
93 assert(Form == DW_FORM_flag_present);
94 Die->addValue(DG.getAllocator(), static_cast<dwarf::Attribute>(A), Form,
95 DIEInteger(1));
96}
97
98dwarfgen::DIE dwarfgen::DIE::addChild(dwarf::Tag Tag) {
99 auto &DG = CU->getGenerator();
100 return dwarfgen::DIE(CU,
101 &Die->addChild(llvm::DIE::get(DG.getAllocator(), Tag)));
102}
103
104dwarfgen::DIE dwarfgen::CompileUnit::getUnitDIE() {
105 return dwarfgen::DIE(this, &DU.getUnitDie());
106}
107
108//===----------------------------------------------------------------------===//
James Hendersona3acf992018-05-10 10:51:33 +0000109/// dwarfgen::LineTable implementation.
110//===----------------------------------------------------------------------===//
111DWARFDebugLine::Prologue dwarfgen::LineTable::createBasicPrologue() const {
112 DWARFDebugLine::Prologue P;
113 switch (Version) {
114 case 2:
115 case 3:
116 P.TotalLength = 41;
117 P.PrologueLength = 35;
118 break;
119 case 4:
120 P.TotalLength = 42;
121 P.PrologueLength = 36;
122 break;
123 case 5:
124 P.TotalLength = 47;
125 P.PrologueLength = 39;
126 P.FormParams.AddrSize = AddrSize;
127 break;
128 default:
129 llvm_unreachable("unsupported version");
130 }
131 if (Format == DWARF64) {
132 P.TotalLength += 4;
133 P.FormParams.Format = DWARF64;
134 }
135 P.FormParams.Version = Version;
136 P.MinInstLength = 1;
137 P.MaxOpsPerInst = 1;
138 P.DefaultIsStmt = 1;
139 P.LineBase = -5;
140 P.LineRange = 14;
141 P.OpcodeBase = 13;
142 P.StandardOpcodeLengths = {0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1};
143 P.IncludeDirectories.push_back(DWARFFormValue(DW_FORM_string));
144 P.IncludeDirectories.back().setPValue("a dir");
145 P.FileNames.push_back(DWARFDebugLine::FileNameEntry());
146 P.FileNames.back().Name.setPValue("a file");
147 P.FileNames.back().Name.setForm(DW_FORM_string);
148 return P;
149}
150
151void dwarfgen::LineTable::setPrologue(DWARFDebugLine::Prologue NewPrologue) {
152 Prologue = NewPrologue;
153 CustomPrologue.clear();
154}
155
156void dwarfgen::LineTable::setCustomPrologue(
157 ArrayRef<ValueAndLength> NewPrologue) {
158 Prologue.reset();
159 CustomPrologue = NewPrologue;
160}
161
162void dwarfgen::LineTable::addByte(uint8_t Value) {
163 Contents.push_back({Value, Byte});
164}
165
166void dwarfgen::LineTable::addStandardOpcode(uint8_t Opcode,
167 ArrayRef<ValueAndLength> Operands) {
168 Contents.push_back({Opcode, Byte});
169 Contents.insert(Contents.end(), Operands.begin(), Operands.end());
170}
171
172void dwarfgen::LineTable::addExtendedOpcode(uint64_t Length, uint8_t Opcode,
173 ArrayRef<ValueAndLength> Operands) {
174 Contents.push_back({0, Byte});
175 Contents.push_back({Length, ULEB});
176 Contents.push_back({Opcode, Byte});
177 Contents.insert(Contents.end(), Operands.begin(), Operands.end());
178}
179
180void dwarfgen::LineTable::generate(MCContext &MC, AsmPrinter &Asm) const {
181 MC.setDwarfVersion(Version);
182
183 MCSymbol *EndSymbol = nullptr;
184 if (!CustomPrologue.empty()) {
185 writeData(CustomPrologue, Asm);
186 } else if (!Prologue) {
187 EndSymbol = writeDefaultPrologue(Asm);
188 } else {
189 writePrologue(Asm);
190 }
191
192 writeData(Contents, Asm);
193 if (EndSymbol != nullptr)
194 Asm.OutStreamer->EmitLabel(EndSymbol);
195}
196
197void dwarfgen::LineTable::writeData(ArrayRef<ValueAndLength> Data,
198 AsmPrinter &Asm) const {
199 for (auto Entry : Data) {
200 switch (Entry.Length) {
201 case Byte:
202 case Half:
203 case Long:
204 case Quad:
205 Asm.OutStreamer->EmitIntValue(Entry.Value, Entry.Length);
206 break;
207 case ULEB:
208 Asm.EmitULEB128(Entry.Value);
209 break;
210 case SLEB:
211 Asm.EmitSLEB128(Entry.Value);
212 break;
213 default:
214 llvm_unreachable("unsupported ValueAndLength Length value");
215 }
216 }
217}
218
219MCSymbol *dwarfgen::LineTable::writeDefaultPrologue(AsmPrinter &Asm) const {
220 MCSymbol *UnitStart = Asm.createTempSymbol("line_unit_start");
221 MCSymbol *UnitEnd = Asm.createTempSymbol("line_unit_end");
222 if (Format == DwarfFormat::DWARF64) {
223 Asm.emitInt32(0xffffffff);
224 Asm.EmitLabelDifference(UnitEnd, UnitStart, 8);
225 } else {
226 Asm.EmitLabelDifference(UnitEnd, UnitStart, 4);
227 }
228 Asm.OutStreamer->EmitLabel(UnitStart);
229 Asm.emitInt16(Version);
230 if (Version == 5) {
231 Asm.emitInt8(AddrSize);
232 Asm.emitInt8(SegSize);
233 }
234
235 MCSymbol *PrologueStart = Asm.createTempSymbol("line_prologue_start");
236 MCSymbol *PrologueEnd = Asm.createTempSymbol("line_prologue_end");
237 Asm.EmitLabelDifference(PrologueEnd, PrologueStart,
238 Format == DwarfFormat::DWARF64 ? 8 : 4);
239 Asm.OutStreamer->EmitLabel(PrologueStart);
240
241 DWARFDebugLine::Prologue DefaultPrologue = createBasicPrologue();
242 writeProloguePayload(DefaultPrologue, Asm);
243 Asm.OutStreamer->EmitLabel(PrologueEnd);
244 return UnitEnd;
245}
246
247void dwarfgen::LineTable::writePrologue(AsmPrinter &Asm) const {
248 if (Format == DwarfFormat::DWARF64) {
249 Asm.emitInt32(0xffffffff);
250 Asm.emitInt64(Prologue->TotalLength);
251 } else {
252 Asm.emitInt32(Prologue->TotalLength);
253 }
254 Asm.emitInt16(Prologue->getVersion());
255 if (Version == 5) {
256 Asm.emitInt8(Prologue->getAddressSize());
257 Asm.emitInt8(Prologue->SegSelectorSize);
258 }
259 if (Format == DwarfFormat::DWARF64)
260 Asm.emitInt64(Prologue->PrologueLength);
261 else
262 Asm.emitInt32(Prologue->PrologueLength);
263
264 writeProloguePayload(*Prologue, Asm);
265}
266
267static void writeCString(StringRef Str, AsmPrinter &Asm) {
268 Asm.OutStreamer->EmitBytes(Str);
269 Asm.emitInt8(0);
270}
271
272static void writeV2IncludeAndFileTable(const DWARFDebugLine::Prologue &Prologue,
273 AsmPrinter &Asm) {
274 for (auto Include : Prologue.IncludeDirectories) {
275 assert(Include.getAsCString() && "expected a string form for include dir");
276 writeCString(*Include.getAsCString(), Asm);
277 }
278 Asm.emitInt8(0);
279
280 for (auto File : Prologue.FileNames) {
281 assert(File.Name.getAsCString() && "expected a string form for file name");
282 writeCString(*File.Name.getAsCString(), Asm);
283 Asm.EmitULEB128(File.DirIdx);
284 Asm.EmitULEB128(File.ModTime);
285 Asm.EmitULEB128(File.Length);
286 }
287 Asm.emitInt8(0);
288}
289
290static void writeV5IncludeAndFileTable(const DWARFDebugLine::Prologue &Prologue,
291 AsmPrinter &Asm) {
292 Asm.emitInt8(1); // directory_entry_format_count.
293 // TODO: Add support for other content descriptions - we currently only
294 // support a single DW_LNCT_path/DW_FORM_string.
295 Asm.EmitULEB128(DW_LNCT_path);
296 Asm.EmitULEB128(DW_FORM_string);
297 Asm.EmitULEB128(Prologue.IncludeDirectories.size());
298 for (auto Include : Prologue.IncludeDirectories) {
299 assert(Include.getAsCString() && "expected a string form for include dir");
300 writeCString(*Include.getAsCString(), Asm);
301 }
302
303 Asm.emitInt8(1); // file_name_entry_format_count.
304 Asm.EmitULEB128(DW_LNCT_path);
305 Asm.EmitULEB128(DW_FORM_string);
306 Asm.EmitULEB128(Prologue.FileNames.size());
307 for (auto File : Prologue.FileNames) {
308 assert(File.Name.getAsCString() && "expected a string form for file name");
309 writeCString(*File.Name.getAsCString(), Asm);
310 }
311}
312
313void dwarfgen::LineTable::writeProloguePayload(
314 const DWARFDebugLine::Prologue &Prologue, AsmPrinter &Asm) const {
315 Asm.emitInt8(Prologue.MinInstLength);
316 if (Version >= 4)
317 Asm.emitInt8(Prologue.MaxOpsPerInst);
318 Asm.emitInt8(Prologue.DefaultIsStmt);
319 Asm.emitInt8(Prologue.LineBase);
320 Asm.emitInt8(Prologue.LineRange);
321 Asm.emitInt8(Prologue.OpcodeBase);
322 for (auto Length : Prologue.StandardOpcodeLengths) {
323 Asm.emitInt8(Length);
324 }
325
326 if (Version < 5)
327 writeV2IncludeAndFileTable(Prologue, Asm);
328 else
329 writeV5IncludeAndFileTable(Prologue, Asm);
330}
331
332//===----------------------------------------------------------------------===//
Greg Clayton3462a422016-12-08 01:03:48 +0000333/// dwarfgen::Generator implementation.
334//===----------------------------------------------------------------------===//
335
Greg Claytonb9032832016-12-08 16:57:04 +0000336dwarfgen::Generator::Generator()
337 : MAB(nullptr), MCE(nullptr), MS(nullptr), StringPool(nullptr),
338 Abbreviations(Allocator) {}
Greg Clayton3462a422016-12-08 01:03:48 +0000339dwarfgen::Generator::~Generator() = default;
340
341llvm::Expected<std::unique_ptr<dwarfgen::Generator>>
342dwarfgen::Generator::create(Triple TheTriple, uint16_t DwarfVersion) {
343 std::unique_ptr<dwarfgen::Generator> GenUP(new dwarfgen::Generator());
344 llvm::Error error = GenUP->init(TheTriple, DwarfVersion);
345 if (error)
346 return Expected<std::unique_ptr<dwarfgen::Generator>>(std::move(error));
347 return Expected<std::unique_ptr<dwarfgen::Generator>>(std::move(GenUP));
348}
349
350llvm::Error dwarfgen::Generator::init(Triple TheTriple, uint16_t V) {
351 Version = V;
352 std::string ErrorStr;
353 std::string TripleName;
354
355 // Get the target.
356 const Target *TheTarget =
357 TargetRegistry::lookupTarget(TripleName, TheTriple, ErrorStr);
358 if (!TheTarget)
359 return make_error<StringError>(ErrorStr, inconvertibleErrorCode());
360
361 TripleName = TheTriple.getTriple();
362
363 // Create all the MC Objects.
364 MRI.reset(TheTarget->createMCRegInfo(TripleName));
365 if (!MRI)
366 return make_error<StringError>(Twine("no register info for target ") +
367 TripleName,
368 inconvertibleErrorCode());
369
370 MAI.reset(TheTarget->createMCAsmInfo(*MRI, TripleName));
371 if (!MAI)
372 return make_error<StringError>("no asm info for target " + TripleName,
373 inconvertibleErrorCode());
374
375 MOFI.reset(new MCObjectFileInfo);
376 MC.reset(new MCContext(MAI.get(), MRI.get(), MOFI.get()));
Rafael Espindola9f929952017-08-02 20:32:26 +0000377 MOFI->InitMCObjectFileInfo(TheTriple, /*PIC*/ false, *MC);
Greg Clayton3462a422016-12-08 01:03:48 +0000378
Alex Bradburyb22f7512018-01-03 08:53:05 +0000379 MSTI.reset(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
380 if (!MSTI)
381 return make_error<StringError>("no subtarget info for target " + TripleName,
382 inconvertibleErrorCode());
383
David Blaikieeef5c232017-11-27 19:55:16 +0000384 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags();
Alex Bradburyb22f7512018-01-03 08:53:05 +0000385 MAB = TheTarget->createMCAsmBackend(*MSTI, *MRI, MCOptions);
Greg Clayton3462a422016-12-08 01:03:48 +0000386 if (!MAB)
387 return make_error<StringError>("no asm backend for target " + TripleName,
388 inconvertibleErrorCode());
389
390 MII.reset(TheTarget->createMCInstrInfo());
391 if (!MII)
392 return make_error<StringError>("no instr info info for target " +
393 TripleName,
394 inconvertibleErrorCode());
395
Greg Clayton3462a422016-12-08 01:03:48 +0000396 MCE = TheTarget->createMCCodeEmitter(*MII, *MRI, *MC);
397 if (!MCE)
398 return make_error<StringError>("no code emitter for target " + TripleName,
399 inconvertibleErrorCode());
400
401 Stream = make_unique<raw_svector_ostream>(FileBytes);
402
Greg Clayton3462a422016-12-08 01:03:48 +0000403 MS = TheTarget->createMCObjectStreamer(
Lang Hames2241ffa2017-10-11 23:34:47 +0000404 TheTriple, *MC, std::unique_ptr<MCAsmBackend>(MAB), *Stream,
405 std::unique_ptr<MCCodeEmitter>(MCE), *MSTI, MCOptions.MCRelaxAll,
406 MCOptions.MCIncrementalLinkerCompatible,
Greg Clayton3462a422016-12-08 01:03:48 +0000407 /*DWARFMustBeAtTheEnd*/ false);
408 if (!MS)
409 return make_error<StringError>("no object streamer for target " +
410 TripleName,
411 inconvertibleErrorCode());
412
413 // Finally create the AsmPrinter we'll use to emit the DIEs.
414 TM.reset(TheTarget->createTargetMachine(TripleName, "", "", TargetOptions(),
415 None));
416 if (!TM)
417 return make_error<StringError>("no target machine for target " + TripleName,
418 inconvertibleErrorCode());
419
420 Asm.reset(TheTarget->createAsmPrinter(*TM, std::unique_ptr<MCStreamer>(MS)));
421 if (!Asm)
422 return make_error<StringError>("no asm printer for target " + TripleName,
423 inconvertibleErrorCode());
424
425 // Set the DWARF version correctly on all classes that we use.
426 MC->setDwarfVersion(Version);
427 Asm->setDwarfVersion(Version);
428
Benjamin Kramer9fcb7fe2016-12-09 13:12:30 +0000429 StringPool = llvm::make_unique<DwarfStringPool>(Allocator, *Asm, StringRef());
Greg Clayton3462a422016-12-08 01:03:48 +0000430
431 return Error::success();
432}
433
434StringRef dwarfgen::Generator::generate() {
435 // Offset from the first CU in the debug info section is 0 initially.
436 unsigned SecOffset = 0;
437
438 // Iterate over each compile unit and set the size and offsets for each
439 // DIE within each compile unit. All offsets are CU relative.
440 for (auto &CU : CompileUnits) {
441 // Set the absolute .debug_info offset for this compile unit.
442 CU->setOffset(SecOffset);
443 // The DIEs contain compile unit relative offsets.
444 unsigned CUOffset = 11;
445 CUOffset = CU->getUnitDIE().computeSizeAndOffsets(CUOffset);
446 // Update our absolute .debug_info offset.
447 SecOffset += CUOffset;
448 CU->setLength(CUOffset - 4);
449 }
450 Abbreviations.Emit(Asm.get(), MOFI->getDwarfAbbrevSection());
451 StringPool->emit(*Asm, MOFI->getDwarfStrSection());
452 MS->SwitchSection(MOFI->getDwarfInfoSection());
453 for (auto &CU : CompileUnits) {
454 uint16_t Version = CU->getVersion();
455 auto Length = CU->getLength();
456 MC->setDwarfVersion(Version);
457 assert(Length != -1U);
Rafael Espindola4b4d85f2018-03-29 23:32:54 +0000458 Asm->emitInt32(Length);
459 Asm->emitInt16(Version);
Paul Robinsoncddd6042017-02-28 20:24:55 +0000460 if (Version <= 4) {
Rafael Espindola4b4d85f2018-03-29 23:32:54 +0000461 Asm->emitInt32(0);
462 Asm->emitInt8(CU->getAddressSize());
Paul Robinsoncddd6042017-02-28 20:24:55 +0000463 } else {
Rafael Espindola4b4d85f2018-03-29 23:32:54 +0000464 Asm->emitInt8(dwarf::DW_UT_compile);
465 Asm->emitInt8(CU->getAddressSize());
466 Asm->emitInt32(0);
Paul Robinsoncddd6042017-02-28 20:24:55 +0000467 }
Greg Clayton3462a422016-12-08 01:03:48 +0000468 Asm->emitDwarfDIE(*CU->getUnitDIE().Die);
469 }
470
James Hendersona3acf992018-05-10 10:51:33 +0000471 MS->SwitchSection(MOFI->getDwarfLineSection());
472 for (auto &LT : LineTables)
473 LT->generate(*MC, *Asm);
474
Greg Clayton3462a422016-12-08 01:03:48 +0000475 MS->Finish();
476 if (FileBytes.empty())
477 return StringRef();
478 return StringRef(FileBytes.data(), FileBytes.size());
479}
480
481bool dwarfgen::Generator::saveFile(StringRef Path) {
482 if (FileBytes.empty())
483 return false;
484 std::error_code EC;
485 raw_fd_ostream Strm(Path, EC, sys::fs::F_None);
486 if (EC)
487 return false;
488 Strm.write(FileBytes.data(), FileBytes.size());
489 Strm.close();
490 return true;
491}
492
493dwarfgen::CompileUnit &dwarfgen::Generator::addCompileUnit() {
James Hendersona3acf992018-05-10 10:51:33 +0000494 CompileUnits.push_back(
495 make_unique<CompileUnit>(*this, Version, Asm->getPointerSize()));
Greg Clayton3462a422016-12-08 01:03:48 +0000496 return *CompileUnits.back();
497}
James Hendersona3acf992018-05-10 10:51:33 +0000498
499dwarfgen::LineTable &dwarfgen::Generator::addLineTable(DwarfFormat Format) {
500 LineTables.push_back(
501 make_unique<LineTable>(*this, Version, Format, Asm->getPointerSize()));
502 return *LineTables.back();
503}