1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
15 #include "ByteStreamer.h"
17 #include "DebugLocEntry.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/DIE.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Dwarf.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/MD5.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Target/TargetFrameLowering.h"
51 #include "llvm/Target/TargetLoweringObjectFile.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "llvm/Target/TargetRegisterInfo.h"
55 #include "llvm/Target/TargetSubtargetInfo.h"
58 #define DEBUG_TYPE "dwarfdebug"
61 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
62 cl::desc("Disable debug info printing"));
64 static cl::opt<bool> UnknownLocations(
65 "use-unknown-locations", cl::Hidden,
66 cl::desc("Make an absence of debug location information explicit."),
70 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
71 cl::desc("Generate GNU-style pubnames and pubtypes"),
74 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
76 cl::desc("Generate dwarf aranges"),
79 static cl::opt<DebuggerKind>
80 DebuggerTuningOpt("debugger-tune",
81 cl::desc("Tune debug info for a particular debugger"),
82 cl::init(DebuggerKind::Default),
84 clEnumValN(DebuggerKind::GDB, "gdb", "gdb"),
85 clEnumValN(DebuggerKind::LLDB, "lldb", "lldb"),
86 clEnumValN(DebuggerKind::SCE, "sce",
87 "SCE targets (e.g. PS4)"),
91 enum DefaultOnOff { Default, Enable, Disable };
94 static cl::opt<DefaultOnOff>
95 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
96 cl::desc("Output prototype dwarf accelerator tables."),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<DefaultOnOff>
103 SplitDwarf("split-dwarf", cl::Hidden,
104 cl::desc("Output DWARF5 split debug info."),
105 cl::values(clEnumVal(Default, "Default for platform"),
106 clEnumVal(Enable, "Enabled"),
107 clEnumVal(Disable, "Disabled"), clEnumValEnd),
110 static cl::opt<DefaultOnOff>
111 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
112 cl::desc("Generate DWARF pubnames and pubtypes sections"),
113 cl::values(clEnumVal(Default, "Default for platform"),
114 clEnumVal(Enable, "Enabled"),
115 clEnumVal(Disable, "Disabled"), clEnumValEnd),
118 static const char *const DWARFGroupName = "DWARF Emission";
119 static const char *const DbgTimerName = "DWARF Debug Writer";
121 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
123 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
124 : dwarf::OperationEncodingString(Op));
127 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
128 BS.EmitSLEB128(Value, Twine(Value));
131 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
132 BS.EmitULEB128(Value, Twine(Value));
135 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
136 // This information is not available while emitting .debug_loc entries.
140 //===----------------------------------------------------------------------===//
142 /// resolve - Look in the DwarfDebug map for the MDNode that
143 /// corresponds to the reference.
144 template <typename T> T *DbgVariable::resolve(TypedDINodeRef<T> Ref) const {
145 return DD->resolve(Ref);
148 bool DbgVariable::isBlockByrefVariable() const {
149 assert(Var && "Invalid complex DbgVariable!");
150 return Var->getType()
151 .resolve(DD->getTypeIdentifierMap())
152 ->isBlockByrefStruct();
155 const DIType *DbgVariable::getType() const {
156 DIType *Ty = Var->getType().resolve(DD->getTypeIdentifierMap());
157 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
158 // addresses instead.
159 if (Ty->isBlockByrefStruct()) {
160 /* Byref variables, in Blocks, are declared by the programmer as
161 "SomeType VarName;", but the compiler creates a
162 __Block_byref_x_VarName struct, and gives the variable VarName
163 either the struct, or a pointer to the struct, as its type. This
164 is necessary for various behind-the-scenes things the compiler
165 needs to do with by-reference variables in blocks.
167 However, as far as the original *programmer* is concerned, the
168 variable should still have type 'SomeType', as originally declared.
170 The following function dives into the __Block_byref_x_VarName
171 struct to find the original type of the variable. This will be
172 passed back to the code generating the type for the Debug
173 Information Entry for the variable 'VarName'. 'VarName' will then
174 have the original type 'SomeType' in its debug information.
176 The original type 'SomeType' will be the type of the field named
177 'VarName' inside the __Block_byref_x_VarName struct.
179 NOTE: In order for this to not completely fail on the debugger
180 side, the Debug Information Entry for the variable VarName needs to
181 have a DW_AT_location that tells the debugger how to unwind through
182 the pointers and __Block_byref_x_VarName struct to find the actual
183 value of the variable. The function addBlockByrefType does this. */
184 DIType *subType = Ty;
185 uint16_t tag = Ty->getTag();
187 if (tag == dwarf::DW_TAG_pointer_type)
188 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
190 auto Elements = cast<DICompositeType>(subType)->getElements();
191 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
192 auto *DT = cast<DIDerivedType>(Elements[i]);
193 if (getName() == DT->getName())
194 return resolve(DT->getBaseType());
200 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
201 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
202 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
203 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
205 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
206 : Asm(A), MMI(Asm->MMI), DebugLocs(A->OutStreamer->isVerboseAsm()),
207 PrevLabel(nullptr), InfoHolder(A, "info_string", DIEValueAllocator),
208 UsedNonDefaultText(false),
209 SkeletonHolder(A, "skel_string", DIEValueAllocator),
210 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
211 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
212 dwarf::DW_FORM_data4)),
213 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
214 dwarf::DW_FORM_data4)),
215 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
216 dwarf::DW_FORM_data4)),
217 AccelTypes(TypeAtoms), DebuggerTuning(DebuggerKind::Default) {
221 Triple TT(Asm->getTargetTriple());
223 // Make sure we know our "debugger tuning." The command-line option takes
224 // precedence; fall back to triple-based defaults.
225 if (DebuggerTuningOpt != DebuggerKind::Default)
226 DebuggerTuning = DebuggerTuningOpt;
227 else if (IsDarwin || TT.isOSFreeBSD())
228 DebuggerTuning = DebuggerKind::LLDB;
229 else if (TT.isPS4CPU())
230 DebuggerTuning = DebuggerKind::SCE;
232 DebuggerTuning = DebuggerKind::GDB;
234 // Turn on accelerator tables for LLDB by default.
235 if (DwarfAccelTables == Default)
236 HasDwarfAccelTables = tuneForLLDB();
238 HasDwarfAccelTables = DwarfAccelTables == Enable;
240 // Handle split DWARF. Off by default for now.
241 if (SplitDwarf == Default)
242 HasSplitDwarf = false;
244 HasSplitDwarf = SplitDwarf == Enable;
246 // Pubnames/pubtypes on by default for GDB.
247 if (DwarfPubSections == Default)
248 HasDwarfPubSections = tuneForGDB();
250 HasDwarfPubSections = DwarfPubSections == Enable;
252 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
253 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
254 : MMI->getModule()->getDwarfVersion();
256 // Work around a GDB bug. GDB doesn't support the standard opcode;
257 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
258 // is defined as of DWARF 3.
259 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
260 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
261 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
263 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
266 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
271 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
272 DwarfDebug::~DwarfDebug() { }
274 static bool isObjCClass(StringRef Name) {
275 return Name.startswith("+") || Name.startswith("-");
278 static bool hasObjCCategory(StringRef Name) {
279 if (!isObjCClass(Name))
282 return Name.find(") ") != StringRef::npos;
285 static void getObjCClassCategory(StringRef In, StringRef &Class,
286 StringRef &Category) {
287 if (!hasObjCCategory(In)) {
288 Class = In.slice(In.find('[') + 1, In.find(' '));
293 Class = In.slice(In.find('[') + 1, In.find('('));
294 Category = In.slice(In.find('[') + 1, In.find(' '));
298 static StringRef getObjCMethodName(StringRef In) {
299 return In.slice(In.find(' ') + 1, In.find(']'));
302 // Add the various names to the Dwarf accelerator table names.
303 // TODO: Determine whether or not we should add names for programs
304 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
305 // is only slightly different than the lookup of non-standard ObjC names.
306 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
307 if (!SP->isDefinition())
309 addAccelName(SP->getName(), Die);
311 // If the linkage name is different than the name, go ahead and output
312 // that as well into the name table.
313 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
314 addAccelName(SP->getLinkageName(), Die);
316 // If this is an Objective-C selector name add it to the ObjC accelerator
318 if (isObjCClass(SP->getName())) {
319 StringRef Class, Category;
320 getObjCClassCategory(SP->getName(), Class, Category);
321 addAccelObjC(Class, Die);
323 addAccelObjC(Category, Die);
324 // Also add the base method name to the name table.
325 addAccelName(getObjCMethodName(SP->getName()), Die);
329 /// isSubprogramContext - Return true if Context is either a subprogram
330 /// or another context nested inside a subprogram.
331 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
334 if (isa<DISubprogram>(Context))
336 if (auto *T = dyn_cast<DIType>(Context))
337 return isSubprogramContext(resolve(T->getScope()));
341 /// Check whether we should create a DIE for the given Scope, return true
342 /// if we don't create a DIE (the corresponding DIE is null).
343 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
344 if (Scope->isAbstractScope())
347 // We don't create a DIE if there is no Range.
348 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
352 if (Ranges.size() > 1)
355 // We don't create a DIE if we have a single Range and the end label
357 return !getLabelAfterInsn(Ranges.front().second);
360 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
362 if (auto *SkelCU = CU.getSkeleton())
366 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
367 assert(Scope && Scope->getScopeNode());
368 assert(Scope->isAbstractScope());
369 assert(!Scope->getInlinedAt());
371 const MDNode *SP = Scope->getScopeNode();
373 ProcessedSPNodes.insert(SP);
375 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
376 // was inlined from another compile unit.
377 auto &CU = SPMap[SP];
378 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
379 CU.constructAbstractSubprogramScopeDIE(Scope);
383 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
384 if (!GenerateGnuPubSections)
387 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
390 // Create new DwarfCompileUnit for the given metadata node with tag
391 // DW_TAG_compile_unit.
393 DwarfDebug::constructDwarfCompileUnit(const DICompileUnit *DIUnit) {
394 StringRef FN = DIUnit->getFilename();
395 CompilationDir = DIUnit->getDirectory();
397 auto OwnedUnit = make_unique<DwarfCompileUnit>(
398 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
399 DwarfCompileUnit &NewCU = *OwnedUnit;
400 DIE &Die = NewCU.getUnitDie();
401 InfoHolder.addUnit(std::move(OwnedUnit));
403 NewCU.setSkeleton(constructSkeletonCU(NewCU));
405 // LTO with assembly output shares a single line table amongst multiple CUs.
406 // To avoid the compilation directory being ambiguous, let the line table
407 // explicitly describe the directory of all files, never relying on the
408 // compilation directory.
409 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
410 Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
411 NewCU.getUniqueID(), CompilationDir);
413 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit->getProducer());
414 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
415 DIUnit->getSourceLanguage());
416 NewCU.addString(Die, dwarf::DW_AT_name, FN);
418 if (!useSplitDwarf()) {
419 NewCU.initStmtList();
421 // If we're using split dwarf the compilation dir is going to be in the
422 // skeleton CU and so we don't need to duplicate it here.
423 if (!CompilationDir.empty())
424 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
426 addGnuPubAttributes(NewCU, Die);
429 if (DIUnit->isOptimized())
430 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
432 StringRef Flags = DIUnit->getFlags();
434 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
436 if (unsigned RVer = DIUnit->getRuntimeVersion())
437 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
438 dwarf::DW_FORM_data1, RVer);
441 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
443 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
445 CUMap.insert(std::make_pair(DIUnit, &NewCU));
446 CUDieMap.insert(std::make_pair(&Die, &NewCU));
450 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
451 const DIImportedEntity *N) {
452 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
453 D->addChild(TheCU.constructImportedEntityDIE(N));
456 // Emit all Dwarf sections that should come prior to the content. Create
457 // global DIEs and emit initial debug info sections. This is invoked by
458 // the target AsmPrinter.
459 void DwarfDebug::beginModule() {
460 if (DisableDebugInfoPrinting)
463 const Module *M = MMI->getModule();
465 FunctionDIs = makeSubprogramMap(*M);
467 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
470 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
472 SingleCU = CU_Nodes->getNumOperands() == 1;
474 for (MDNode *N : CU_Nodes->operands()) {
475 auto *CUNode = cast<DICompileUnit>(N);
476 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
477 for (auto *IE : CUNode->getImportedEntities())
478 ScopesWithImportedEntities.push_back(std::make_pair(IE->getScope(), IE));
479 // Stable sort to preserve the order of appearance of imported entities.
480 // This is to avoid out-of-order processing of interdependent declarations
481 // within the same scope, e.g. { namespace A = base; namespace B = A; }
482 std::stable_sort(ScopesWithImportedEntities.begin(),
483 ScopesWithImportedEntities.end(), less_first());
484 for (auto *GV : CUNode->getGlobalVariables())
485 CU.getOrCreateGlobalVariableDIE(GV);
486 for (auto *SP : CUNode->getSubprograms())
487 SPMap.insert(std::make_pair(SP, &CU));
488 for (auto *Ty : CUNode->getEnumTypes()) {
489 // The enum types array by design contains pointers to
490 // MDNodes rather than DIRefs. Unique them here.
491 CU.getOrCreateTypeDIE(cast<DIType>(resolve(Ty->getRef())));
493 for (auto *Ty : CUNode->getRetainedTypes()) {
494 // The retained types array by design contains pointers to
495 // MDNodes rather than DIRefs. Unique them here.
496 DIType *RT = cast<DIType>(resolve(Ty->getRef()));
497 if (!RT->isExternalTypeRef())
498 // There is no point in force-emitting a forward declaration.
499 CU.getOrCreateTypeDIE(RT);
501 // Emit imported_modules last so that the relevant context is already
503 for (auto *IE : CUNode->getImportedEntities())
504 constructAndAddImportedEntityDIE(CU, IE);
507 // Tell MMI that we have debug info.
508 MMI->setDebugInfoAvailability(true);
511 void DwarfDebug::finishVariableDefinitions() {
512 for (const auto &Var : ConcreteVariables) {
513 DIE *VariableDie = Var->getDIE();
515 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
516 // in the ConcreteVariables list, rather than looking it up again here.
517 // DIE::getUnit isn't simple - it walks parent pointers, etc.
518 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
520 DbgVariable *AbsVar = getExistingAbstractVariable(
521 InlinedVariable(Var->getVariable(), Var->getInlinedAt()));
522 if (AbsVar && AbsVar->getDIE()) {
523 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
526 Unit->applyVariableAttributes(*Var, *VariableDie);
530 void DwarfDebug::finishSubprogramDefinitions() {
531 for (const auto &P : SPMap)
532 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
533 CU.finishSubprogramDefinition(cast<DISubprogram>(P.first));
538 // Collect info for variables that were optimized out.
539 void DwarfDebug::collectDeadVariables() {
540 const Module *M = MMI->getModule();
542 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
543 for (MDNode *N : CU_Nodes->operands()) {
544 auto *TheCU = cast<DICompileUnit>(N);
545 // Construct subprogram DIE and add variables DIEs.
546 DwarfCompileUnit *SPCU =
547 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
548 assert(SPCU && "Unable to find Compile Unit!");
549 for (auto *SP : TheCU->getSubprograms()) {
550 if (ProcessedSPNodes.count(SP) != 0)
552 SPCU->collectDeadVariables(SP);
558 void DwarfDebug::finalizeModuleInfo() {
559 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
561 finishSubprogramDefinitions();
563 finishVariableDefinitions();
565 // Collect info for variables that were optimized out.
566 collectDeadVariables();
568 // Handle anything that needs to be done on a per-unit basis after
569 // all other generation.
570 for (const auto &P : CUMap) {
571 auto &TheCU = *P.second;
572 // Emit DW_AT_containing_type attribute to connect types with their
573 // vtable holding type.
574 TheCU.constructContainingTypeDIEs();
576 // Add CU specific attributes if we need to add any.
577 // If we're splitting the dwarf out now that we've got the entire
578 // CU then add the dwo id to it.
579 auto *SkCU = TheCU.getSkeleton();
580 if (useSplitDwarf()) {
581 // Emit a unique identifier for this CU.
582 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
583 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
584 dwarf::DW_FORM_data8, ID);
585 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
586 dwarf::DW_FORM_data8, ID);
588 // We don't keep track of which addresses are used in which CU so this
589 // is a bit pessimistic under LTO.
590 if (!AddrPool.isEmpty()) {
591 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
592 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
595 if (!SkCU->getRangeLists().empty()) {
596 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
597 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
602 // If we have code split among multiple sections or non-contiguous
603 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
604 // remain in the .o file, otherwise add a DW_AT_low_pc.
605 // FIXME: We should use ranges allow reordering of code ala
606 // .subsections_via_symbols in mach-o. This would mean turning on
607 // ranges for all subprogram DIEs for mach-o.
608 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
609 if (unsigned NumRanges = TheCU.getRanges().size()) {
611 // A DW_AT_low_pc attribute may also be specified in combination with
612 // DW_AT_ranges to specify the default base address for use in
613 // location lists (see Section 2.6.2) and range lists (see Section
615 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
617 U.setBaseAddress(TheCU.getRanges().front().getStart());
618 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
622 // Compute DIE offsets and sizes.
623 InfoHolder.computeSizeAndOffsets();
625 SkeletonHolder.computeSizeAndOffsets();
628 // Emit all Dwarf sections that should come after the content.
629 void DwarfDebug::endModule() {
630 assert(CurFn == nullptr);
631 assert(CurMI == nullptr);
633 // If we aren't actually generating debug info (check beginModule -
634 // conditionalized on !DisableDebugInfoPrinting and the presence of the
635 // llvm.dbg.cu metadata node)
636 if (!MMI->hasDebugInfo())
639 // Finalize the debug info for the module.
640 finalizeModuleInfo();
647 // Emit info into a debug loc section.
650 // Corresponding abbreviations into a abbrev section.
653 // Emit all the DIEs into a debug info section.
656 // Emit info into a debug aranges section.
657 if (GenerateARangeSection)
660 // Emit info into a debug ranges section.
663 if (useSplitDwarf()) {
666 emitDebugAbbrevDWO();
668 // Emit DWO addresses.
669 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
672 // Emit info into the dwarf accelerator table sections.
673 if (useDwarfAccelTables()) {
676 emitAccelNamespaces();
680 // Emit the pubnames and pubtypes sections if requested.
681 if (HasDwarfPubSections) {
682 emitDebugPubNames(GenerateGnuPubSections);
683 emitDebugPubTypes(GenerateGnuPubSections);
688 AbstractVariables.clear();
691 // Find abstract variable, if any, associated with Var.
693 DwarfDebug::getExistingAbstractVariable(InlinedVariable IV,
694 const DILocalVariable *&Cleansed) {
695 // More then one inlined variable corresponds to one abstract variable.
697 auto I = AbstractVariables.find(Cleansed);
698 if (I != AbstractVariables.end())
699 return I->second.get();
703 DbgVariable *DwarfDebug::getExistingAbstractVariable(InlinedVariable IV) {
704 const DILocalVariable *Cleansed;
705 return getExistingAbstractVariable(IV, Cleansed);
708 void DwarfDebug::createAbstractVariable(const DILocalVariable *Var,
709 LexicalScope *Scope) {
710 auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr, this);
711 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
712 AbstractVariables[Var] = std::move(AbsDbgVariable);
715 void DwarfDebug::ensureAbstractVariableIsCreated(InlinedVariable IV,
716 const MDNode *ScopeNode) {
717 const DILocalVariable *Cleansed = nullptr;
718 if (getExistingAbstractVariable(IV, Cleansed))
721 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
722 cast<DILocalScope>(ScopeNode)));
725 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(
726 InlinedVariable IV, const MDNode *ScopeNode) {
727 const DILocalVariable *Cleansed = nullptr;
728 if (getExistingAbstractVariable(IV, Cleansed))
731 if (LexicalScope *Scope =
732 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
733 createAbstractVariable(Cleansed, Scope);
736 // Collect variable information from side table maintained by MMI.
737 void DwarfDebug::collectVariableInfoFromMMITable(
738 DenseSet<InlinedVariable> &Processed) {
739 for (const auto &VI : MMI->getVariableDbgInfo()) {
742 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
743 "Expected inlined-at fields to agree");
745 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
746 Processed.insert(Var);
747 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
749 // If variable scope is not found then skip this variable.
753 ensureAbstractVariableIsCreatedIfScoped(Var, Scope->getScopeNode());
754 auto RegVar = make_unique<DbgVariable>(Var.first, Var.second, this);
755 RegVar->initializeMMI(VI.Expr, VI.Slot);
756 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
757 ConcreteVariables.push_back(std::move(RegVar));
761 // Get .debug_loc entry for the instruction range starting at MI.
762 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
763 const DIExpression *Expr = MI->getDebugExpression();
765 assert(MI->getNumOperands() == 4);
766 if (MI->getOperand(0).isReg()) {
767 MachineLocation MLoc;
768 // If the second operand is an immediate, this is a
769 // register-indirect address.
770 if (!MI->getOperand(1).isImm())
771 MLoc.set(MI->getOperand(0).getReg());
773 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
774 return DebugLocEntry::Value(Expr, MLoc);
776 if (MI->getOperand(0).isImm())
777 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
778 if (MI->getOperand(0).isFPImm())
779 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
780 if (MI->getOperand(0).isCImm())
781 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
783 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
786 /// Determine whether two variable pieces overlap.
787 static bool piecesOverlap(const DIExpression *P1, const DIExpression *P2) {
788 if (!P1->isBitPiece() || !P2->isBitPiece())
790 unsigned l1 = P1->getBitPieceOffset();
791 unsigned l2 = P2->getBitPieceOffset();
792 unsigned r1 = l1 + P1->getBitPieceSize();
793 unsigned r2 = l2 + P2->getBitPieceSize();
794 // True where [l1,r1[ and [r1,r2[ overlap.
795 return (l1 < r2) && (l2 < r1);
798 /// Build the location list for all DBG_VALUEs in the function that
799 /// describe the same variable. If the ranges of several independent
800 /// pieces of the same variable overlap partially, split them up and
801 /// combine the ranges. The resulting DebugLocEntries are will have
802 /// strict monotonically increasing begin addresses and will never
807 // Ranges History [var, loc, piece ofs size]
808 // 0 | [x, (reg0, piece 0, 32)]
809 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
811 // 3 | [clobber reg0]
812 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
817 // [0-1] [x, (reg0, piece 0, 32)]
818 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
819 // [3-4] [x, (reg1, piece 32, 32)]
820 // [4- ] [x, (mem, piece 0, 64)]
822 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
823 const DbgValueHistoryMap::InstrRanges &Ranges) {
824 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
826 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
827 const MachineInstr *Begin = I->first;
828 const MachineInstr *End = I->second;
829 assert(Begin->isDebugValue() && "Invalid History entry");
831 // Check if a variable is inaccessible in this range.
832 if (Begin->getNumOperands() > 1 &&
833 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
838 // If this piece overlaps with any open ranges, truncate them.
839 const DIExpression *DIExpr = Begin->getDebugExpression();
840 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
841 [&](DebugLocEntry::Value R) {
842 return piecesOverlap(DIExpr, R.getExpression());
844 OpenRanges.erase(Last, OpenRanges.end());
846 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
847 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
849 const MCSymbol *EndLabel;
851 EndLabel = getLabelAfterInsn(End);
852 else if (std::next(I) == Ranges.end())
853 EndLabel = Asm->getFunctionEnd();
855 EndLabel = getLabelBeforeInsn(std::next(I)->first);
856 assert(EndLabel && "Forgot label after instruction ending a range!");
858 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
860 auto Value = getDebugLocValue(Begin);
861 DebugLocEntry Loc(StartLabel, EndLabel, Value);
862 bool couldMerge = false;
864 // If this is a piece, it may belong to the current DebugLocEntry.
865 if (DIExpr->isBitPiece()) {
866 // Add this value to the list of open ranges.
867 OpenRanges.push_back(Value);
869 // Attempt to add the piece to the last entry.
870 if (!DebugLoc.empty())
871 if (DebugLoc.back().MergeValues(Loc))
876 // Need to add a new DebugLocEntry. Add all values from still
877 // valid non-overlapping pieces.
878 if (OpenRanges.size())
879 Loc.addValues(OpenRanges);
881 DebugLoc.push_back(std::move(Loc));
884 // Attempt to coalesce the ranges of two otherwise identical
886 auto CurEntry = DebugLoc.rbegin();
888 dbgs() << CurEntry->getValues().size() << " Values:\n";
889 for (auto &Value : CurEntry->getValues())
890 Value.getExpression()->dump();
894 auto PrevEntry = std::next(CurEntry);
895 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
900 DbgVariable *DwarfDebug::createConcreteVariable(LexicalScope &Scope,
901 InlinedVariable IV) {
902 ensureAbstractVariableIsCreatedIfScoped(IV, Scope.getScopeNode());
903 ConcreteVariables.push_back(
904 make_unique<DbgVariable>(IV.first, IV.second, this));
905 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
906 return ConcreteVariables.back().get();
909 // Find variables for each lexical scope.
910 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
911 const DISubprogram *SP,
912 DenseSet<InlinedVariable> &Processed) {
913 // Grab the variable info that was squirreled away in the MMI side-table.
914 collectVariableInfoFromMMITable(Processed);
916 for (const auto &I : DbgValues) {
917 InlinedVariable IV = I.first;
918 if (Processed.count(IV))
921 // Instruction ranges, specifying where IV is accessible.
922 const auto &Ranges = I.second;
926 LexicalScope *Scope = nullptr;
927 if (const DILocation *IA = IV.second)
928 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
930 Scope = LScopes.findLexicalScope(IV.first->getScope());
931 // If variable scope is not found then skip this variable.
935 Processed.insert(IV);
936 DbgVariable *RegVar = createConcreteVariable(*Scope, IV);
938 const MachineInstr *MInsn = Ranges.front().first;
939 assert(MInsn->isDebugValue() && "History must begin with debug value");
941 // Check if the first DBG_VALUE is valid for the rest of the function.
942 if (Ranges.size() == 1 && Ranges.front().second == nullptr) {
943 RegVar->initializeDbgValue(MInsn);
947 // Handle multiple DBG_VALUE instructions describing one variable.
948 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
950 // Build the location list for this variable.
951 SmallVector<DebugLocEntry, 8> Entries;
952 buildLocationList(Entries, Ranges);
954 // If the variable has an DIBasicType, extract it. Basic types cannot have
955 // unique identifiers, so don't bother resolving the type with the
957 const DIBasicType *BT = dyn_cast<DIBasicType>(
958 static_cast<const Metadata *>(IV.first->getType()));
960 // Finalize the entry by lowering it into a DWARF bytestream.
961 for (auto &Entry : Entries)
962 Entry.finalize(*Asm, List, BT);
965 // Collect info for variables that were optimized out.
966 for (const DILocalVariable *DV : SP->getVariables()) {
967 if (Processed.insert(InlinedVariable(DV, nullptr)).second)
968 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
969 createConcreteVariable(*Scope, InlinedVariable(DV, nullptr));
973 // Return Label preceding the instruction.
974 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
975 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
976 assert(Label && "Didn't insert label before instruction");
980 // Return Label immediately following the instruction.
981 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
982 return LabelsAfterInsn.lookup(MI);
985 // Process beginning of an instruction.
986 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
987 assert(CurMI == nullptr);
989 // Check if source location changes, but ignore DBG_VALUE locations.
990 if (!MI->isDebugValue()) {
991 DebugLoc DL = MI->getDebugLoc();
992 if (DL != PrevInstLoc) {
996 if (DL == PrologEndLoc) {
997 Flags |= DWARF2_FLAG_PROLOGUE_END;
998 PrologEndLoc = DebugLoc();
999 Flags |= DWARF2_FLAG_IS_STMT;
1002 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine())
1003 Flags |= DWARF2_FLAG_IS_STMT;
1005 const MDNode *Scope = DL.getScope();
1006 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1007 } else if (UnknownLocations) {
1009 recordSourceLine(0, 0, nullptr, 0);
1014 // Insert labels where requested.
1015 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1016 LabelsBeforeInsn.find(MI);
1019 if (I == LabelsBeforeInsn.end())
1022 // Label already assigned.
1027 PrevLabel = MMI->getContext().createTempSymbol();
1028 Asm->OutStreamer->EmitLabel(PrevLabel);
1030 I->second = PrevLabel;
1033 // Process end of an instruction.
1034 void DwarfDebug::endInstruction() {
1035 assert(CurMI != nullptr);
1036 // Don't create a new label after DBG_VALUE instructions.
1037 // They don't generate code.
1038 if (!CurMI->isDebugValue())
1039 PrevLabel = nullptr;
1041 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1042 LabelsAfterInsn.find(CurMI);
1046 if (I == LabelsAfterInsn.end())
1049 // Label already assigned.
1053 // We need a label after this instruction.
1055 PrevLabel = MMI->getContext().createTempSymbol();
1056 Asm->OutStreamer->EmitLabel(PrevLabel);
1058 I->second = PrevLabel;
1061 // Each LexicalScope has first instruction and last instruction to mark
1062 // beginning and end of a scope respectively. Create an inverse map that list
1063 // scopes starts (and ends) with an instruction. One instruction may start (or
1064 // end) multiple scopes. Ignore scopes that are not reachable.
1065 void DwarfDebug::identifyScopeMarkers() {
1066 SmallVector<LexicalScope *, 4> WorkList;
1067 WorkList.push_back(LScopes.getCurrentFunctionScope());
1068 while (!WorkList.empty()) {
1069 LexicalScope *S = WorkList.pop_back_val();
1071 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1072 if (!Children.empty())
1073 WorkList.append(Children.begin(), Children.end());
1075 if (S->isAbstractScope())
1078 for (const InsnRange &R : S->getRanges()) {
1079 assert(R.first && "InsnRange does not have first instruction!");
1080 assert(R.second && "InsnRange does not have second instruction!");
1081 requestLabelBeforeInsn(R.first);
1082 requestLabelAfterInsn(R.second);
1087 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1088 // First known non-DBG_VALUE and non-frame setup location marks
1089 // the beginning of the function body.
1090 for (const auto &MBB : *MF)
1091 for (const auto &MI : MBB)
1092 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1094 // Did the target forget to set the FrameSetup flag for CFI insns?
1095 assert(!MI.isCFIInstruction() &&
1096 "First non-frame-setup instruction is a CFI instruction.");
1097 return MI.getDebugLoc();
1102 // Gather pre-function debug information. Assumes being called immediately
1103 // after the function entry point has been emitted.
1104 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1107 // If there's no debug info for the function we're not going to do anything.
1108 if (!MMI->hasDebugInfo())
1111 auto DI = FunctionDIs.find(MF->getFunction());
1112 if (DI == FunctionDIs.end())
1115 // Grab the lexical scopes for the function, if we don't have any of those
1116 // then we're not going to be able to do anything.
1117 LScopes.initialize(*MF);
1118 if (LScopes.empty())
1121 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1123 // Make sure that each lexical scope will have a begin/end label.
1124 identifyScopeMarkers();
1126 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1127 // belongs to so that we add to the correct per-cu line table in the
1129 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1130 // FnScope->getScopeNode() and DI->second should represent the same function,
1131 // though they may not be the same MDNode due to inline functions merged in
1132 // LTO where the debug info metadata still differs (either due to distinct
1133 // written differences - two versions of a linkonce_odr function
1134 // written/copied into two separate files, or some sub-optimal metadata that
1135 // isn't structurally identical (see: file path/name info from clang, which
1136 // includes the directory of the cpp file being built, even when the file name
1137 // is absolute (such as an <> lookup header)))
1138 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1139 assert(TheCU && "Unable to find compile unit!");
1140 if (Asm->OutStreamer->hasRawTextSupport())
1141 // Use a single line table if we are generating assembly.
1142 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1144 Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1146 // Calculate history for local variables.
1147 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1150 // Request labels for the full history.
1151 for (const auto &I : DbgValues) {
1152 const auto &Ranges = I.second;
1156 // The first mention of a function argument gets the CurrentFnBegin
1157 // label, so arguments are visible when breaking at function entry.
1158 const DILocalVariable *DIVar = Ranges.front().first->getDebugVariable();
1159 if (DIVar->isParameter() &&
1160 getDISubprogram(DIVar->getScope())->describes(MF->getFunction())) {
1161 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1162 if (Ranges.front().first->getDebugExpression()->isBitPiece()) {
1163 // Mark all non-overlapping initial pieces.
1164 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1165 const DIExpression *Piece = I->first->getDebugExpression();
1166 if (std::all_of(Ranges.begin(), I,
1167 [&](DbgValueHistoryMap::InstrRange Pred) {
1168 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1170 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1177 for (const auto &Range : Ranges) {
1178 requestLabelBeforeInsn(Range.first);
1180 requestLabelAfterInsn(Range.second);
1184 PrevInstLoc = DebugLoc();
1185 PrevLabel = Asm->getFunctionBegin();
1187 // Record beginning of function.
1188 PrologEndLoc = findPrologueEndLoc(MF);
1189 if (DILocation *L = PrologEndLoc) {
1190 // We'd like to list the prologue as "not statements" but GDB behaves
1191 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1192 auto *SP = L->getInlinedAtScope()->getSubprogram();
1193 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1197 // Gather and emit post-function debug information.
1198 void DwarfDebug::endFunction(const MachineFunction *MF) {
1199 assert(CurFn == MF &&
1200 "endFunction should be called with the same function as beginFunction");
1202 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1203 !FunctionDIs.count(MF->getFunction())) {
1204 // If we don't have a lexical scope for this function then there will
1205 // be a hole in the range information. Keep note of this by setting the
1206 // previously used section to nullptr.
1212 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1213 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1215 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1216 auto *SP = cast<DISubprogram>(FnScope->getScopeNode());
1217 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1219 DenseSet<InlinedVariable> ProcessedVars;
1220 collectVariableInfo(TheCU, SP, ProcessedVars);
1222 // Add the range of this function to the list of ranges for the CU.
1223 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1225 // Under -gmlt, skip building the subprogram if there are no inlined
1226 // subroutines inside it.
1227 if (TheCU.getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly &&
1228 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1229 assert(InfoHolder.getScopeVariables().empty());
1230 assert(DbgValues.empty());
1231 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1232 // by a -gmlt CU. Add a test and remove this assertion.
1233 assert(AbstractVariables.empty());
1234 LabelsBeforeInsn.clear();
1235 LabelsAfterInsn.clear();
1236 PrevLabel = nullptr;
1242 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1244 // Construct abstract scopes.
1245 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1246 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1247 // Collect info for variables that were optimized out.
1248 for (const DILocalVariable *DV : SP->getVariables()) {
1249 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1251 ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr),
1253 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1254 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1256 constructAbstractSubprogramScopeDIE(AScope);
1259 TheCU.constructSubprogramScopeDIE(FnScope);
1260 if (auto *SkelCU = TheCU.getSkeleton())
1261 if (!LScopes.getAbstractScopesList().empty())
1262 SkelCU->constructSubprogramScopeDIE(FnScope);
1265 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1266 // DbgVariables except those that are also in AbstractVariables (since they
1267 // can be used cross-function)
1268 InfoHolder.getScopeVariables().clear();
1270 LabelsBeforeInsn.clear();
1271 LabelsAfterInsn.clear();
1272 PrevLabel = nullptr;
1276 // Register a source line with debug info. Returns the unique label that was
1277 // emitted and which provides correspondence to the source line list.
1278 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1283 unsigned Discriminator = 0;
1284 if (auto *Scope = cast_or_null<DIScope>(S)) {
1285 Fn = Scope->getFilename();
1286 Dir = Scope->getDirectory();
1287 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1288 Discriminator = LBF->getDiscriminator();
1290 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1291 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1292 .getOrCreateSourceID(Fn, Dir);
1294 Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1298 //===----------------------------------------------------------------------===//
1300 //===----------------------------------------------------------------------===//
1302 // Emit the debug info section.
1303 void DwarfDebug::emitDebugInfo() {
1304 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1305 Holder.emitUnits(/* UseOffsets */ false);
1308 // Emit the abbreviation section.
1309 void DwarfDebug::emitAbbreviations() {
1310 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1312 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1315 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
1316 StringRef TableName) {
1317 Accel.FinalizeTable(Asm, TableName);
1318 Asm->OutStreamer->SwitchSection(Section);
1320 // Emit the full data.
1321 Accel.emit(Asm, Section->getBeginSymbol(), this);
1324 // Emit visible names into a hashed accelerator table section.
1325 void DwarfDebug::emitAccelNames() {
1326 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1330 // Emit objective C classes and categories into a hashed accelerator table
1332 void DwarfDebug::emitAccelObjC() {
1333 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1337 // Emit namespace dies into a hashed accelerator table.
1338 void DwarfDebug::emitAccelNamespaces() {
1339 emitAccel(AccelNamespace,
1340 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1344 // Emit type dies into a hashed accelerator table.
1345 void DwarfDebug::emitAccelTypes() {
1346 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1350 // Public name handling.
1351 // The format for the various pubnames:
1353 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1354 // for the DIE that is named.
1356 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1357 // into the CU and the index value is computed according to the type of value
1358 // for the DIE that is named.
1360 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1361 // it's the offset within the debug_info/debug_types dwo section, however, the
1362 // reference in the pubname header doesn't change.
1364 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1365 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1367 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1369 // We could have a specification DIE that has our most of our knowledge,
1370 // look for that now.
1371 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1372 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1373 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1374 Linkage = dwarf::GIEL_EXTERNAL;
1375 } else if (Die->findAttribute(dwarf::DW_AT_external))
1376 Linkage = dwarf::GIEL_EXTERNAL;
1378 switch (Die->getTag()) {
1379 case dwarf::DW_TAG_class_type:
1380 case dwarf::DW_TAG_structure_type:
1381 case dwarf::DW_TAG_union_type:
1382 case dwarf::DW_TAG_enumeration_type:
1383 return dwarf::PubIndexEntryDescriptor(
1384 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1385 ? dwarf::GIEL_STATIC
1386 : dwarf::GIEL_EXTERNAL);
1387 case dwarf::DW_TAG_typedef:
1388 case dwarf::DW_TAG_base_type:
1389 case dwarf::DW_TAG_subrange_type:
1390 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1391 case dwarf::DW_TAG_namespace:
1392 return dwarf::GIEK_TYPE;
1393 case dwarf::DW_TAG_subprogram:
1394 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1395 case dwarf::DW_TAG_variable:
1396 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1397 case dwarf::DW_TAG_enumerator:
1398 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1399 dwarf::GIEL_STATIC);
1401 return dwarf::GIEK_NONE;
1405 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1407 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1408 MCSection *PSec = GnuStyle
1409 ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1410 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1412 emitDebugPubSection(GnuStyle, PSec, "Names",
1413 &DwarfCompileUnit::getGlobalNames);
1416 void DwarfDebug::emitDebugPubSection(
1417 bool GnuStyle, MCSection *PSec, StringRef Name,
1418 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1419 for (const auto &NU : CUMap) {
1420 DwarfCompileUnit *TheU = NU.second;
1422 const auto &Globals = (TheU->*Accessor)();
1424 if (Globals.empty())
1427 if (auto *Skeleton = TheU->getSkeleton())
1430 // Start the dwarf pubnames section.
1431 Asm->OutStreamer->SwitchSection(PSec);
1434 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1435 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1436 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1437 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1439 Asm->OutStreamer->EmitLabel(BeginLabel);
1441 Asm->OutStreamer->AddComment("DWARF Version");
1442 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1444 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1445 Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1447 Asm->OutStreamer->AddComment("Compilation Unit Length");
1448 Asm->EmitInt32(TheU->getLength());
1450 // Emit the pubnames for this compilation unit.
1451 for (const auto &GI : Globals) {
1452 const char *Name = GI.getKeyData();
1453 const DIE *Entity = GI.second;
1455 Asm->OutStreamer->AddComment("DIE offset");
1456 Asm->EmitInt32(Entity->getOffset());
1459 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1460 Asm->OutStreamer->AddComment(
1461 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1462 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1463 Asm->EmitInt8(Desc.toBits());
1466 Asm->OutStreamer->AddComment("External Name");
1467 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1470 Asm->OutStreamer->AddComment("End Mark");
1472 Asm->OutStreamer->EmitLabel(EndLabel);
1476 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1477 MCSection *PSec = GnuStyle
1478 ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1479 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1481 emitDebugPubSection(GnuStyle, PSec, "Types",
1482 &DwarfCompileUnit::getGlobalTypes);
1485 // Emit visible names into a debug str section.
1486 void DwarfDebug::emitDebugStr() {
1487 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1488 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1491 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1492 const DebugLocStream::Entry &Entry) {
1493 auto &&Comments = DebugLocs.getComments(Entry);
1494 auto Comment = Comments.begin();
1495 auto End = Comments.end();
1496 for (uint8_t Byte : DebugLocs.getBytes(Entry))
1497 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1500 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1501 ByteStreamer &Streamer,
1502 const DebugLocEntry::Value &Value,
1503 unsigned PieceOffsetInBits) {
1504 DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1505 AP.getDwarfDebug()->getDwarfVersion(),
1508 if (Value.isInt()) {
1509 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1510 BT->getEncoding() == dwarf::DW_ATE_signed_char))
1511 DwarfExpr.AddSignedConstant(Value.getInt());
1513 DwarfExpr.AddUnsignedConstant(Value.getInt());
1514 } else if (Value.isLocation()) {
1515 MachineLocation Loc = Value.getLoc();
1516 const DIExpression *Expr = Value.getExpression();
1517 if (!Expr || !Expr->getNumElements())
1519 AP.EmitDwarfRegOp(Streamer, Loc);
1521 // Complex address entry.
1522 if (Loc.getOffset()) {
1523 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1524 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(),
1527 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1531 // else ... ignore constant fp. There is not any good way to
1532 // to represent them here in dwarf.
1536 void DebugLocEntry::finalize(const AsmPrinter &AP,
1537 DebugLocStream::ListBuilder &List,
1538 const DIBasicType *BT) {
1539 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1540 BufferByteStreamer Streamer = Entry.getStreamer();
1541 const DebugLocEntry::Value &Value = Values[0];
1542 if (Value.isBitPiece()) {
1543 // Emit all pieces that belong to the same variable and range.
1544 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1545 return P.isBitPiece();
1546 }) && "all values are expected to be pieces");
1547 assert(std::is_sorted(Values.begin(), Values.end()) &&
1548 "pieces are expected to be sorted");
1550 unsigned Offset = 0;
1551 for (auto Piece : Values) {
1552 const DIExpression *Expr = Piece.getExpression();
1553 unsigned PieceOffset = Expr->getBitPieceOffset();
1554 unsigned PieceSize = Expr->getBitPieceSize();
1555 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1556 if (Offset < PieceOffset) {
1557 // The DWARF spec seriously mandates pieces with no locations for gaps.
1558 DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1559 AP.getDwarfDebug()->getDwarfVersion(),
1561 Expr.AddOpPiece(PieceOffset-Offset, 0);
1562 Offset += PieceOffset-Offset;
1564 Offset += PieceSize;
1566 emitDebugLocValue(AP, BT, Streamer, Piece, PieceOffset);
1569 assert(Values.size() == 1 && "only pieces may have >1 value");
1570 emitDebugLocValue(AP, BT, Streamer, Value, 0);
1574 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1576 Asm->OutStreamer->AddComment("Loc expr size");
1577 Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1580 APByteStreamer Streamer(*Asm);
1581 emitDebugLocEntry(Streamer, Entry);
1584 // Emit locations into the debug loc section.
1585 void DwarfDebug::emitDebugLoc() {
1586 // Start the dwarf loc section.
1587 Asm->OutStreamer->SwitchSection(
1588 Asm->getObjFileLowering().getDwarfLocSection());
1589 unsigned char Size = Asm->getDataLayout().getPointerSize();
1590 for (const auto &List : DebugLocs.getLists()) {
1591 Asm->OutStreamer->EmitLabel(List.Label);
1592 const DwarfCompileUnit *CU = List.CU;
1593 for (const auto &Entry : DebugLocs.getEntries(List)) {
1594 // Set up the range. This range is relative to the entry point of the
1595 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1596 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1597 if (auto *Base = CU->getBaseAddress()) {
1598 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1599 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1601 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1602 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1605 emitDebugLocEntryLocation(Entry);
1607 Asm->OutStreamer->EmitIntValue(0, Size);
1608 Asm->OutStreamer->EmitIntValue(0, Size);
1612 void DwarfDebug::emitDebugLocDWO() {
1613 Asm->OutStreamer->SwitchSection(
1614 Asm->getObjFileLowering().getDwarfLocDWOSection());
1615 for (const auto &List : DebugLocs.getLists()) {
1616 Asm->OutStreamer->EmitLabel(List.Label);
1617 for (const auto &Entry : DebugLocs.getEntries(List)) {
1618 // Just always use start_length for now - at least that's one address
1619 // rather than two. We could get fancier and try to, say, reuse an
1620 // address we know we've emitted elsewhere (the start of the function?
1621 // The start of the CU or CU subrange that encloses this range?)
1622 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1623 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1624 Asm->EmitULEB128(idx);
1625 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1627 emitDebugLocEntryLocation(Entry);
1629 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1634 const MCSymbol *Start, *End;
1637 // Emit a debug aranges section, containing a CU lookup for any
1638 // address we can tie back to a CU.
1639 void DwarfDebug::emitDebugARanges() {
1640 // Provides a unique id per text section.
1641 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1643 // Filter labels by section.
1644 for (const SymbolCU &SCU : ArangeLabels) {
1645 if (SCU.Sym->isInSection()) {
1646 // Make a note of this symbol and it's section.
1647 MCSection *Section = &SCU.Sym->getSection();
1648 if (!Section->getKind().isMetadata())
1649 SectionMap[Section].push_back(SCU);
1651 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1652 // appear in the output. This sucks as we rely on sections to build
1653 // arange spans. We can do it without, but it's icky.
1654 SectionMap[nullptr].push_back(SCU);
1658 // Add terminating symbols for each section.
1659 for (const auto &I : SectionMap) {
1660 MCSection *Section = I.first;
1661 MCSymbol *Sym = nullptr;
1664 Sym = Asm->OutStreamer->endSection(Section);
1666 // Insert a final terminator.
1667 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1670 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1672 for (auto &I : SectionMap) {
1673 const MCSection *Section = I.first;
1674 SmallVector<SymbolCU, 8> &List = I.second;
1675 if (List.size() < 2)
1678 // If we have no section (e.g. common), just write out
1679 // individual spans for each symbol.
1681 for (const SymbolCU &Cur : List) {
1683 Span.Start = Cur.Sym;
1686 Spans[Cur.CU].push_back(Span);
1691 // Sort the symbols by offset within the section.
1692 std::sort(List.begin(), List.end(),
1693 [&](const SymbolCU &A, const SymbolCU &B) {
1694 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1695 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1697 // Symbols with no order assigned should be placed at the end.
1698 // (e.g. section end labels)
1706 // Build spans between each label.
1707 const MCSymbol *StartSym = List[0].Sym;
1708 for (size_t n = 1, e = List.size(); n < e; n++) {
1709 const SymbolCU &Prev = List[n - 1];
1710 const SymbolCU &Cur = List[n];
1712 // Try and build the longest span we can within the same CU.
1713 if (Cur.CU != Prev.CU) {
1715 Span.Start = StartSym;
1717 Spans[Prev.CU].push_back(Span);
1723 // Start the dwarf aranges section.
1724 Asm->OutStreamer->SwitchSection(
1725 Asm->getObjFileLowering().getDwarfARangesSection());
1727 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1729 // Build a list of CUs used.
1730 std::vector<DwarfCompileUnit *> CUs;
1731 for (const auto &it : Spans) {
1732 DwarfCompileUnit *CU = it.first;
1736 // Sort the CU list (again, to ensure consistent output order).
1737 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1738 return A->getUniqueID() < B->getUniqueID();
1741 // Emit an arange table for each CU we used.
1742 for (DwarfCompileUnit *CU : CUs) {
1743 std::vector<ArangeSpan> &List = Spans[CU];
1745 // Describe the skeleton CU's offset and length, not the dwo file's.
1746 if (auto *Skel = CU->getSkeleton())
1749 // Emit size of content not including length itself.
1750 unsigned ContentSize =
1751 sizeof(int16_t) + // DWARF ARange version number
1752 sizeof(int32_t) + // Offset of CU in the .debug_info section
1753 sizeof(int8_t) + // Pointer Size (in bytes)
1754 sizeof(int8_t); // Segment Size (in bytes)
1756 unsigned TupleSize = PtrSize * 2;
1758 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1760 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1762 ContentSize += Padding;
1763 ContentSize += (List.size() + 1) * TupleSize;
1765 // For each compile unit, write the list of spans it covers.
1766 Asm->OutStreamer->AddComment("Length of ARange Set");
1767 Asm->EmitInt32(ContentSize);
1768 Asm->OutStreamer->AddComment("DWARF Arange version number");
1769 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1770 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1771 Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1772 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1773 Asm->EmitInt8(PtrSize);
1774 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1777 Asm->OutStreamer->EmitFill(Padding, 0xff);
1779 for (const ArangeSpan &Span : List) {
1780 Asm->EmitLabelReference(Span.Start, PtrSize);
1782 // Calculate the size as being from the span start to it's end.
1784 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1786 // For symbols without an end marker (e.g. common), we
1787 // write a single arange entry containing just that one symbol.
1788 uint64_t Size = SymSize[Span.Start];
1792 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1796 Asm->OutStreamer->AddComment("ARange terminator");
1797 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1798 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1802 // Emit visible names into a debug ranges section.
1803 void DwarfDebug::emitDebugRanges() {
1804 // Start the dwarf ranges section.
1805 Asm->OutStreamer->SwitchSection(
1806 Asm->getObjFileLowering().getDwarfRangesSection());
1808 // Size for our labels.
1809 unsigned char Size = Asm->getDataLayout().getPointerSize();
1811 // Grab the specific ranges for the compile units in the module.
1812 for (const auto &I : CUMap) {
1813 DwarfCompileUnit *TheCU = I.second;
1815 if (auto *Skel = TheCU->getSkeleton())
1818 // Iterate over the misc ranges for the compile units in the module.
1819 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1820 // Emit our symbol so we can find the beginning of the range.
1821 Asm->OutStreamer->EmitLabel(List.getSym());
1823 for (const RangeSpan &Range : List.getRanges()) {
1824 const MCSymbol *Begin = Range.getStart();
1825 const MCSymbol *End = Range.getEnd();
1826 assert(Begin && "Range without a begin symbol?");
1827 assert(End && "Range without an end symbol?");
1828 if (auto *Base = TheCU->getBaseAddress()) {
1829 Asm->EmitLabelDifference(Begin, Base, Size);
1830 Asm->EmitLabelDifference(End, Base, Size);
1832 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1833 Asm->OutStreamer->EmitSymbolValue(End, Size);
1837 // And terminate the list with two 0 values.
1838 Asm->OutStreamer->EmitIntValue(0, Size);
1839 Asm->OutStreamer->EmitIntValue(0, Size);
1844 // DWARF5 Experimental Separate Dwarf emitters.
1846 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1847 std::unique_ptr<DwarfUnit> NewU) {
1848 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1849 U.getCUNode()->getSplitDebugFilename());
1851 if (!CompilationDir.empty())
1852 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1854 addGnuPubAttributes(*NewU, Die);
1856 SkeletonHolder.addUnit(std::move(NewU));
1859 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1860 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1861 // DW_AT_addr_base, DW_AT_ranges_base.
1862 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1864 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1865 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1866 DwarfCompileUnit &NewCU = *OwnedUnit;
1867 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1869 NewCU.initStmtList();
1871 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1876 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1877 // compile units that would normally be in debug_info.
1878 void DwarfDebug::emitDebugInfoDWO() {
1879 assert(useSplitDwarf() && "No split dwarf debug info?");
1880 // Don't emit relocations into the dwo file.
1881 InfoHolder.emitUnits(/* UseOffsets */ true);
1884 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1885 // abbreviations for the .debug_info.dwo section.
1886 void DwarfDebug::emitDebugAbbrevDWO() {
1887 assert(useSplitDwarf() && "No split dwarf?");
1888 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1891 void DwarfDebug::emitDebugLineDWO() {
1892 assert(useSplitDwarf() && "No split dwarf?");
1893 Asm->OutStreamer->SwitchSection(
1894 Asm->getObjFileLowering().getDwarfLineDWOSection());
1895 SplitTypeUnitFileTable.Emit(*Asm->OutStreamer);
1898 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1899 // string section and is identical in format to traditional .debug_str
1901 void DwarfDebug::emitDebugStrDWO() {
1902 assert(useSplitDwarf() && "No split dwarf?");
1903 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1904 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1908 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1909 if (!useSplitDwarf())
1912 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
1913 return &SplitTypeUnitFileTable;
1916 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
1918 Hash.update(Identifier);
1919 // ... take the least significant 8 bytes and return those. Our MD5
1920 // implementation always returns its results in little endian, swap bytes
1922 MD5::MD5Result Result;
1924 return support::endian::read64le(Result + 8);
1927 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1928 StringRef Identifier, DIE &RefDie,
1929 const DICompositeType *CTy) {
1930 // Fast path if we're building some type units and one has already used the
1931 // address pool we know we're going to throw away all this work anyway, so
1932 // don't bother building dependent types.
1933 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1936 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
1938 CU.addDIETypeSignature(RefDie, *TU);
1942 bool TopLevelType = TypeUnitsUnderConstruction.empty();
1943 AddrPool.resetUsedFlag();
1945 auto OwnedUnit = make_unique<DwarfTypeUnit>(
1946 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
1947 this, &InfoHolder, getDwoLineTable(CU));
1948 DwarfTypeUnit &NewTU = *OwnedUnit;
1949 DIE &UnitDie = NewTU.getUnitDie();
1951 TypeUnitsUnderConstruction.push_back(
1952 std::make_pair(std::move(OwnedUnit), CTy));
1954 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1957 uint64_t Signature = makeTypeSignature(Identifier);
1958 NewTU.setTypeSignature(Signature);
1960 if (useSplitDwarf())
1961 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1963 CU.applyStmtList(UnitDie);
1965 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1968 NewTU.setType(NewTU.createTypeDIE(CTy));
1971 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1972 TypeUnitsUnderConstruction.clear();
1974 // Types referencing entries in the address table cannot be placed in type
1976 if (AddrPool.hasBeenUsed()) {
1978 // Remove all the types built while building this type.
1979 // This is pessimistic as some of these types might not be dependent on
1980 // the type that used an address.
1981 for (const auto &TU : TypeUnitsToAdd)
1982 DwarfTypeUnits.erase(TU.second);
1984 // Construct this type in the CU directly.
1985 // This is inefficient because all the dependent types will be rebuilt
1986 // from scratch, including building them in type units, discovering that
1987 // they depend on addresses, throwing them out and rebuilding them.
1988 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
1992 // If the type wasn't dependent on fission addresses, finish adding the type
1993 // and all its dependent types.
1994 for (auto &TU : TypeUnitsToAdd)
1995 InfoHolder.addUnit(std::move(TU.first));
1997 CU.addDIETypeSignature(RefDie, NewTU);
2000 // Accelerator table mutators - add each name along with its companion
2001 // DIE to the proper table while ensuring that the name that we're going
2002 // to reference is in the string table. We do this since the names we
2003 // add may not only be identical to the names in the DIE.
2004 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2005 if (!useDwarfAccelTables())
2007 AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2010 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2011 if (!useDwarfAccelTables())
2013 AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2016 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2017 if (!useDwarfAccelTables())
2019 AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2022 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2023 if (!useDwarfAccelTables())
2025 AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);