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 "DwarfCompileUnit.h"
18 #include "DwarfExpression.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/DIE.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/Endian.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MD5.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetFrameLowering.h"
50 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
57 #define DEBUG_TYPE "dwarfdebug"
60 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
61 cl::desc("Disable debug info printing"));
63 static cl::opt<bool> UnknownLocations(
64 "use-unknown-locations", cl::Hidden,
65 cl::desc("Make an absence of debug location information explicit."),
69 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
70 cl::desc("Generate GNU-style pubnames and pubtypes"),
73 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
75 cl::desc("Generate dwarf aranges"),
79 enum DefaultOnOff { Default, Enable, Disable };
82 static cl::opt<DefaultOnOff>
83 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
84 cl::desc("Output prototype dwarf accelerator tables."),
85 cl::values(clEnumVal(Default, "Default for platform"),
86 clEnumVal(Enable, "Enabled"),
87 clEnumVal(Disable, "Disabled"), clEnumValEnd),
90 static cl::opt<DefaultOnOff>
91 SplitDwarf("split-dwarf", cl::Hidden,
92 cl::desc("Output DWARF5 split debug info."),
93 cl::values(clEnumVal(Default, "Default for platform"),
94 clEnumVal(Enable, "Enabled"),
95 clEnumVal(Disable, "Disabled"), clEnumValEnd),
98 static cl::opt<DefaultOnOff>
99 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
100 cl::desc("Generate DWARF pubnames and pubtypes sections"),
101 cl::values(clEnumVal(Default, "Default for platform"),
102 clEnumVal(Enable, "Enabled"),
103 clEnumVal(Disable, "Disabled"), clEnumValEnd),
106 static const char *const DWARFGroupName = "DWARF Emission";
107 static const char *const DbgTimerName = "DWARF Debug Writer";
109 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
111 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
112 : dwarf::OperationEncodingString(Op));
115 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
116 BS.EmitSLEB128(Value, Twine(Value));
119 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
120 BS.EmitULEB128(Value, Twine(Value));
123 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
124 // This information is not available while emitting .debug_loc entries.
128 //===----------------------------------------------------------------------===//
130 /// resolve - Look in the DwarfDebug map for the MDNode that
131 /// corresponds to the reference.
132 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
133 return DD->resolve(Ref);
136 bool DbgVariable::isBlockByrefVariable() const {
137 assert(Var && "Invalid complex DbgVariable!");
138 return Var->getType()
139 .resolve(DD->getTypeIdentifierMap())
140 ->isBlockByrefStruct();
143 DIType DbgVariable::getType() const {
144 DIType Ty = Var->getType().resolve(DD->getTypeIdentifierMap());
145 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
146 // addresses instead.
147 if (Ty->isBlockByrefStruct()) {
148 /* Byref variables, in Blocks, are declared by the programmer as
149 "SomeType VarName;", but the compiler creates a
150 __Block_byref_x_VarName struct, and gives the variable VarName
151 either the struct, or a pointer to the struct, as its type. This
152 is necessary for various behind-the-scenes things the compiler
153 needs to do with by-reference variables in blocks.
155 However, as far as the original *programmer* is concerned, the
156 variable should still have type 'SomeType', as originally declared.
158 The following function dives into the __Block_byref_x_VarName
159 struct to find the original type of the variable. This will be
160 passed back to the code generating the type for the Debug
161 Information Entry for the variable 'VarName'. 'VarName' will then
162 have the original type 'SomeType' in its debug information.
164 The original type 'SomeType' will be the type of the field named
165 'VarName' inside the __Block_byref_x_VarName struct.
167 NOTE: In order for this to not completely fail on the debugger
168 side, the Debug Information Entry for the variable VarName needs to
169 have a DW_AT_location that tells the debugger how to unwind through
170 the pointers and __Block_byref_x_VarName struct to find the actual
171 value of the variable. The function addBlockByrefType does this. */
173 uint16_t tag = Ty.getTag();
175 if (tag == dwarf::DW_TAG_pointer_type)
176 subType = resolve(DITypeRef(cast<MDDerivedType>(Ty)->getBaseType()));
178 DIArray Elements(cast<MDCompositeTypeBase>(subType)->getElements());
179 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
180 DIDerivedType DT = cast<MDDerivedTypeBase>(Elements[i]);
181 if (getName() == DT.getName())
182 return (resolve(DT.getTypeDerivedFrom()));
188 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
189 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
190 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
191 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
193 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
194 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr),
195 InfoHolder(A, "info_string", DIEValueAllocator),
196 UsedNonDefaultText(false),
197 SkeletonHolder(A, "skel_string", DIEValueAllocator),
198 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
199 IsPS4(Triple(A->getTargetTriple()).isPS4()),
200 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
201 dwarf::DW_FORM_data4)),
202 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
203 dwarf::DW_FORM_data4)),
204 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
205 dwarf::DW_FORM_data4)),
206 AccelTypes(TypeAtoms) {
211 // Turn on accelerator tables for Darwin by default, pubnames by
212 // default for non-Darwin/PS4, and handle split dwarf.
213 if (DwarfAccelTables == Default)
214 HasDwarfAccelTables = IsDarwin;
216 HasDwarfAccelTables = DwarfAccelTables == Enable;
218 if (SplitDwarf == Default)
219 HasSplitDwarf = false;
221 HasSplitDwarf = SplitDwarf == Enable;
223 if (DwarfPubSections == Default)
224 HasDwarfPubSections = !IsDarwin && !IsPS4;
226 HasDwarfPubSections = DwarfPubSections == Enable;
228 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
229 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
230 : MMI->getModule()->getDwarfVersion();
232 // Darwin and PS4 use the standard TLS opcode (defined in DWARF 3).
233 // Everybody else uses GNU's.
234 UseGNUTLSOpcode = !(IsDarwin || IsPS4) || DwarfVersion < 3;
236 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
239 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
244 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
245 DwarfDebug::~DwarfDebug() { }
247 static bool isObjCClass(StringRef Name) {
248 return Name.startswith("+") || Name.startswith("-");
251 static bool hasObjCCategory(StringRef Name) {
252 if (!isObjCClass(Name))
255 return Name.find(") ") != StringRef::npos;
258 static void getObjCClassCategory(StringRef In, StringRef &Class,
259 StringRef &Category) {
260 if (!hasObjCCategory(In)) {
261 Class = In.slice(In.find('[') + 1, In.find(' '));
266 Class = In.slice(In.find('[') + 1, In.find('('));
267 Category = In.slice(In.find('[') + 1, In.find(' '));
271 static StringRef getObjCMethodName(StringRef In) {
272 return In.slice(In.find(' ') + 1, In.find(']'));
275 // Add the various names to the Dwarf accelerator table names.
276 // TODO: Determine whether or not we should add names for programs
277 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
278 // is only slightly different than the lookup of non-standard ObjC names.
279 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
280 if (!SP.isDefinition())
282 addAccelName(SP.getName(), Die);
284 // If the linkage name is different than the name, go ahead and output
285 // that as well into the name table.
286 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
287 addAccelName(SP.getLinkageName(), Die);
289 // If this is an Objective-C selector name add it to the ObjC accelerator
291 if (isObjCClass(SP.getName())) {
292 StringRef Class, Category;
293 getObjCClassCategory(SP.getName(), Class, Category);
294 addAccelObjC(Class, Die);
296 addAccelObjC(Category, Die);
297 // Also add the base method name to the name table.
298 addAccelName(getObjCMethodName(SP.getName()), Die);
302 /// isSubprogramContext - Return true if Context is either a subprogram
303 /// or another context nested inside a subprogram.
304 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
307 if (isa<MDSubprogram>(Context))
309 if (DIType T = dyn_cast<MDType>(Context))
310 return isSubprogramContext(resolve(T.getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
335 if (auto *SkelCU = CU.getSkeleton())
339 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
340 assert(Scope && Scope->getScopeNode());
341 assert(Scope->isAbstractScope());
342 assert(!Scope->getInlinedAt());
344 const MDNode *SP = Scope->getScopeNode();
346 ProcessedSPNodes.insert(SP);
348 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
349 // was inlined from another compile unit.
350 auto &CU = SPMap[SP];
351 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
352 CU.constructAbstractSubprogramScopeDIE(Scope);
356 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
357 if (!GenerateGnuPubSections)
360 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
363 // Create new DwarfCompileUnit for the given metadata node with tag
364 // DW_TAG_compile_unit.
365 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
366 StringRef FN = DIUnit.getFilename();
367 CompilationDir = DIUnit.getDirectory();
369 auto OwnedUnit = make_unique<DwarfCompileUnit>(
370 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
371 DwarfCompileUnit &NewCU = *OwnedUnit;
372 DIE &Die = NewCU.getUnitDie();
373 InfoHolder.addUnit(std::move(OwnedUnit));
375 NewCU.setSkeleton(constructSkeletonCU(NewCU));
377 // LTO with assembly output shares a single line table amongst multiple CUs.
378 // To avoid the compilation directory being ambiguous, let the line table
379 // explicitly describe the directory of all files, never relying on the
380 // compilation directory.
381 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
382 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
383 NewCU.getUniqueID(), CompilationDir);
385 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
386 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
387 DIUnit.getLanguage());
388 NewCU.addString(Die, dwarf::DW_AT_name, FN);
390 if (!useSplitDwarf()) {
391 NewCU.initStmtList();
393 // If we're using split dwarf the compilation dir is going to be in the
394 // skeleton CU and so we don't need to duplicate it here.
395 if (!CompilationDir.empty())
396 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
398 addGnuPubAttributes(NewCU, Die);
401 if (DIUnit.isOptimized())
402 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
404 StringRef Flags = DIUnit.getFlags();
406 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
408 if (unsigned RVer = DIUnit.getRunTimeVersion())
409 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
410 dwarf::DW_FORM_data1, RVer);
413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
415 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
417 CUMap.insert(std::make_pair(DIUnit, &NewCU));
418 CUDieMap.insert(std::make_pair(&Die, &NewCU));
422 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
424 DIImportedEntity Module = cast<MDImportedEntity>(N);
425 if (DIE *D = TheCU.getOrCreateContextDIE(Module->getScope()))
426 D->addChild(TheCU.constructImportedEntityDIE(Module));
429 // Emit all Dwarf sections that should come prior to the content. Create
430 // global DIEs and emit initial debug info sections. This is invoked by
431 // the target AsmPrinter.
432 void DwarfDebug::beginModule() {
433 if (DisableDebugInfoPrinting)
436 const Module *M = MMI->getModule();
438 FunctionDIs = makeSubprogramMap(*M);
440 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
443 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
445 SingleCU = CU_Nodes->getNumOperands() == 1;
447 for (MDNode *N : CU_Nodes->operands()) {
448 DICompileUnit CUNode = cast<MDCompileUnit>(N);
449 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
450 for (auto *IE : CUNode->getImportedEntities())
451 ScopesWithImportedEntities.push_back(std::make_pair(IE->getScope(), IE));
452 // Stable sort to preserve the order of appearance of imported entities.
453 // This is to avoid out-of-order processing of interdependent declarations
454 // within the same scope, e.g. { namespace A = base; namespace B = A; }
455 std::stable_sort(ScopesWithImportedEntities.begin(),
456 ScopesWithImportedEntities.end(), less_first());
457 for (auto *GV : CUNode->getGlobalVariables())
458 CU.getOrCreateGlobalVariableDIE(GV);
459 for (auto *SP : CUNode->getSubprograms())
460 SPMap.insert(std::make_pair(SP, &CU));
461 for (DIType Ty : CUNode->getEnumTypes()) {
462 // The enum types array by design contains pointers to
463 // MDNodes rather than DIRefs. Unique them here.
464 DIType UniqueTy = cast<MDType>(resolve(Ty.getRef()));
465 CU.getOrCreateTypeDIE(UniqueTy);
467 for (DIType Ty : CUNode->getRetainedTypes()) {
468 // The retained types array by design contains pointers to
469 // MDNodes rather than DIRefs. Unique them here.
470 DIType UniqueTy = cast<MDType>(resolve(Ty.getRef()));
471 CU.getOrCreateTypeDIE(UniqueTy);
473 // Emit imported_modules last so that the relevant context is already
475 for (auto *IE : CUNode->getImportedEntities())
476 constructAndAddImportedEntityDIE(CU, IE);
479 // Tell MMI that we have debug info.
480 MMI->setDebugInfoAvailability(true);
483 void DwarfDebug::finishVariableDefinitions() {
484 for (const auto &Var : ConcreteVariables) {
485 DIE *VariableDie = Var->getDIE();
487 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
488 // in the ConcreteVariables list, rather than looking it up again here.
489 // DIE::getUnit isn't simple - it walks parent pointers, etc.
490 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
492 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
493 if (AbsVar && AbsVar->getDIE()) {
494 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
497 Unit->applyVariableAttributes(*Var, *VariableDie);
501 void DwarfDebug::finishSubprogramDefinitions() {
502 for (const auto &P : SPMap)
503 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
504 CU.finishSubprogramDefinition(cast<MDSubprogram>(P.first));
509 // Collect info for variables that were optimized out.
510 void DwarfDebug::collectDeadVariables() {
511 const Module *M = MMI->getModule();
513 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
514 for (MDNode *N : CU_Nodes->operands()) {
515 DICompileUnit TheCU = cast<MDCompileUnit>(N);
516 // Construct subprogram DIE and add variables DIEs.
517 DwarfCompileUnit *SPCU =
518 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
519 assert(SPCU && "Unable to find Compile Unit!");
520 for (auto *SP : TheCU->getSubprograms()) {
521 if (ProcessedSPNodes.count(SP) != 0)
523 SPCU->collectDeadVariables(SP);
529 void DwarfDebug::finalizeModuleInfo() {
530 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
532 finishSubprogramDefinitions();
534 finishVariableDefinitions();
536 // Collect info for variables that were optimized out.
537 collectDeadVariables();
539 // Handle anything that needs to be done on a per-unit basis after
540 // all other generation.
541 for (const auto &P : CUMap) {
542 auto &TheCU = *P.second;
543 // Emit DW_AT_containing_type attribute to connect types with their
544 // vtable holding type.
545 TheCU.constructContainingTypeDIEs();
547 // Add CU specific attributes if we need to add any.
548 // If we're splitting the dwarf out now that we've got the entire
549 // CU then add the dwo id to it.
550 auto *SkCU = TheCU.getSkeleton();
551 if (useSplitDwarf()) {
552 // Emit a unique identifier for this CU.
553 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
554 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
555 dwarf::DW_FORM_data8, ID);
556 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
557 dwarf::DW_FORM_data8, ID);
559 // We don't keep track of which addresses are used in which CU so this
560 // is a bit pessimistic under LTO.
561 if (!AddrPool.isEmpty()) {
562 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
563 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
566 if (!SkCU->getRangeLists().empty()) {
567 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
568 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
573 // If we have code split among multiple sections or non-contiguous
574 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
575 // remain in the .o file, otherwise add a DW_AT_low_pc.
576 // FIXME: We should use ranges allow reordering of code ala
577 // .subsections_via_symbols in mach-o. This would mean turning on
578 // ranges for all subprogram DIEs for mach-o.
579 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
580 if (unsigned NumRanges = TheCU.getRanges().size()) {
582 // A DW_AT_low_pc attribute may also be specified in combination with
583 // DW_AT_ranges to specify the default base address for use in
584 // location lists (see Section 2.6.2) and range lists (see Section
586 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
588 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
589 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
593 // Compute DIE offsets and sizes.
594 InfoHolder.computeSizeAndOffsets();
596 SkeletonHolder.computeSizeAndOffsets();
599 // Emit all Dwarf sections that should come after the content.
600 void DwarfDebug::endModule() {
601 assert(CurFn == nullptr);
602 assert(CurMI == nullptr);
604 // If we aren't actually generating debug info (check beginModule -
605 // conditionalized on !DisableDebugInfoPrinting and the presence of the
606 // llvm.dbg.cu metadata node)
607 if (!MMI->hasDebugInfo())
610 // Finalize the debug info for the module.
611 finalizeModuleInfo();
618 // Emit info into a debug loc section.
621 // Corresponding abbreviations into a abbrev section.
624 // Emit all the DIEs into a debug info section.
627 // Emit info into a debug aranges section.
628 if (GenerateARangeSection)
631 // Emit info into a debug ranges section.
634 if (useSplitDwarf()) {
637 emitDebugAbbrevDWO();
639 // Emit DWO addresses.
640 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
643 // Emit info into the dwarf accelerator table sections.
644 if (useDwarfAccelTables()) {
647 emitAccelNamespaces();
651 // Emit the pubnames and pubtypes sections if requested.
652 if (HasDwarfPubSections) {
653 emitDebugPubNames(GenerateGnuPubSections);
654 emitDebugPubTypes(GenerateGnuPubSections);
659 AbstractVariables.clear();
662 // Find abstract variable, if any, associated with Var.
663 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
664 DIVariable &Cleansed) {
665 LLVMContext &Ctx = DV->getContext();
666 // More then one inlined variable corresponds to one abstract variable.
667 // FIXME: This duplication of variables when inlining should probably be
668 // removed. It's done to allow each DIVariable to describe its location
669 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
670 // make it accurate then remove this duplication/cleansing stuff.
671 Cleansed = cleanseInlinedVariable(DV, Ctx);
672 auto I = AbstractVariables.find(Cleansed);
673 if (I != AbstractVariables.end())
674 return I->second.get();
678 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
680 return getExistingAbstractVariable(DV, Cleansed);
683 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
684 LexicalScope *Scope) {
685 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
686 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
687 AbstractVariables[Var] = std::move(AbsDbgVariable);
690 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
691 const MDNode *ScopeNode) {
692 DIVariable Cleansed = DV;
693 if (getExistingAbstractVariable(DV, Cleansed))
696 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
697 cast<MDLocalScope>(ScopeNode)));
701 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
702 const MDNode *ScopeNode) {
703 DIVariable Cleansed = DV;
704 if (getExistingAbstractVariable(DV, Cleansed))
707 if (LexicalScope *Scope =
708 LScopes.findAbstractScope(cast_or_null<MDLocalScope>(ScopeNode)))
709 createAbstractVariable(Cleansed, Scope);
712 // Collect variable information from side table maintained by MMI.
713 void DwarfDebug::collectVariableInfoFromMMITable(
714 SmallPtrSetImpl<const MDNode *> &Processed) {
715 for (const auto &VI : MMI->getVariableDbgInfo()) {
718 Processed.insert(VI.Var);
719 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
721 // If variable scope is not found then skip this variable.
725 DIVariable DV = cast<MDLocalVariable>(VI.Var);
726 assert(DV->isValidLocationForIntrinsic(VI.Loc) &&
727 "Expected inlined-at fields to agree");
728 DIExpression Expr = cast_or_null<MDExpression>(VI.Expr);
729 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
730 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
731 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
732 ConcreteVariables.push_back(std::move(RegVar));
736 // Get .debug_loc entry for the instruction range starting at MI.
737 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
738 const MDNode *Expr = MI->getDebugExpression();
739 const MDNode *Var = MI->getDebugVariable();
741 assert(MI->getNumOperands() == 4);
742 if (MI->getOperand(0).isReg()) {
743 MachineLocation MLoc;
744 // If the second operand is an immediate, this is a
745 // register-indirect address.
746 if (!MI->getOperand(1).isImm())
747 MLoc.set(MI->getOperand(0).getReg());
749 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
750 return DebugLocEntry::Value(Var, Expr, MLoc);
752 if (MI->getOperand(0).isImm())
753 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
754 if (MI->getOperand(0).isFPImm())
755 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
756 if (MI->getOperand(0).isCImm())
757 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
759 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
762 /// Determine whether two variable pieces overlap.
763 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
764 if (!P1->isBitPiece() || !P2->isBitPiece())
766 unsigned l1 = P1->getBitPieceOffset();
767 unsigned l2 = P2->getBitPieceOffset();
768 unsigned r1 = l1 + P1->getBitPieceSize();
769 unsigned r2 = l2 + P2->getBitPieceSize();
770 // True where [l1,r1[ and [r1,r2[ overlap.
771 return (l1 < r2) && (l2 < r1);
774 /// Build the location list for all DBG_VALUEs in the function that
775 /// describe the same variable. If the ranges of several independent
776 /// pieces of the same variable overlap partially, split them up and
777 /// combine the ranges. The resulting DebugLocEntries are will have
778 /// strict monotonically increasing begin addresses and will never
783 // Ranges History [var, loc, piece ofs size]
784 // 0 | [x, (reg0, piece 0, 32)]
785 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
787 // 3 | [clobber reg0]
788 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
793 // [0-1] [x, (reg0, piece 0, 32)]
794 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
795 // [3-4] [x, (reg1, piece 32, 32)]
796 // [4- ] [x, (mem, piece 0, 64)]
798 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
799 const DbgValueHistoryMap::InstrRanges &Ranges) {
800 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
802 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
803 const MachineInstr *Begin = I->first;
804 const MachineInstr *End = I->second;
805 assert(Begin->isDebugValue() && "Invalid History entry");
807 // Check if a variable is inaccessible in this range.
808 if (Begin->getNumOperands() > 1 &&
809 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
814 // If this piece overlaps with any open ranges, truncate them.
815 DIExpression DIExpr = Begin->getDebugExpression();
816 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
817 [&](DebugLocEntry::Value R) {
818 return piecesOverlap(DIExpr, R.getExpression());
820 OpenRanges.erase(Last, OpenRanges.end());
822 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
823 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
825 const MCSymbol *EndLabel;
827 EndLabel = getLabelAfterInsn(End);
828 else if (std::next(I) == Ranges.end())
829 EndLabel = Asm->getFunctionEnd();
831 EndLabel = getLabelBeforeInsn(std::next(I)->first);
832 assert(EndLabel && "Forgot label after instruction ending a range!");
834 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
836 auto Value = getDebugLocValue(Begin);
837 DebugLocEntry Loc(StartLabel, EndLabel, Value);
838 bool couldMerge = false;
840 // If this is a piece, it may belong to the current DebugLocEntry.
841 if (DIExpr->isBitPiece()) {
842 // Add this value to the list of open ranges.
843 OpenRanges.push_back(Value);
845 // Attempt to add the piece to the last entry.
846 if (!DebugLoc.empty())
847 if (DebugLoc.back().MergeValues(Loc))
852 // Need to add a new DebugLocEntry. Add all values from still
853 // valid non-overlapping pieces.
854 if (OpenRanges.size())
855 Loc.addValues(OpenRanges);
857 DebugLoc.push_back(std::move(Loc));
860 // Attempt to coalesce the ranges of two otherwise identical
862 auto CurEntry = DebugLoc.rbegin();
863 auto PrevEntry = std::next(CurEntry);
864 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
868 dbgs() << CurEntry->getValues().size() << " Values:\n";
869 for (auto Value : CurEntry->getValues()) {
870 Value.getVariable()->dump();
871 Value.getExpression()->dump();
879 // Find variables for each lexical scope.
881 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
882 SmallPtrSetImpl<const MDNode *> &Processed) {
883 // Grab the variable info that was squirreled away in the MMI side-table.
884 collectVariableInfoFromMMITable(Processed);
886 for (const auto &I : DbgValues) {
887 DIVariable DV = cast<MDLocalVariable>(I.first);
888 if (Processed.count(DV))
891 // Instruction ranges, specifying where DV is accessible.
892 const auto &Ranges = I.second;
896 LexicalScope *Scope = nullptr;
897 if (MDLocation *IA = DV->getInlinedAt())
898 Scope = LScopes.findInlinedScope(DV->getScope(), IA);
900 Scope = LScopes.findLexicalScope(DV->getScope());
901 // If variable scope is not found then skip this variable.
905 Processed.insert(DV);
906 const MachineInstr *MInsn = Ranges.front().first;
907 assert(MInsn->isDebugValue() && "History must begin with debug value");
908 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
909 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
910 DbgVariable *RegVar = ConcreteVariables.back().get();
911 InfoHolder.addScopeVariable(Scope, RegVar);
913 // Check if the first DBG_VALUE is valid for the rest of the function.
914 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
917 // Handle multiple DBG_VALUE instructions describing one variable.
918 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
920 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
921 DebugLocList &LocList = DotDebugLocEntries.back();
923 LocList.Label = Asm->createTempSymbol("debug_loc");
925 // Build the location list for this variable.
926 buildLocationList(LocList.List, Ranges);
927 // Finalize the entry by lowering it into a DWARF bytestream.
928 for (auto &Entry : LocList.List)
929 Entry.finalize(*Asm, TypeIdentifierMap);
932 // Collect info for variables that were optimized out.
933 for (DIVariable DV : SP->getVariables()) {
934 if (!Processed.insert(DV).second)
936 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope())) {
937 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
939 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
940 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
945 // Return Label preceding the instruction.
946 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
947 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
948 assert(Label && "Didn't insert label before instruction");
952 // Return Label immediately following the instruction.
953 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
954 return LabelsAfterInsn.lookup(MI);
957 // Process beginning of an instruction.
958 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
959 assert(CurMI == nullptr);
961 // Check if source location changes, but ignore DBG_VALUE locations.
962 if (!MI->isDebugValue()) {
963 DebugLoc DL = MI->getDebugLoc();
964 if (DL != PrevInstLoc) {
968 if (DL == PrologEndLoc) {
969 Flags |= DWARF2_FLAG_PROLOGUE_END;
970 PrologEndLoc = DebugLoc();
971 Flags |= DWARF2_FLAG_IS_STMT;
974 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
975 Flags |= DWARF2_FLAG_IS_STMT;
977 const MDNode *Scope = DL.getScope();
978 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
979 } else if (UnknownLocations) {
981 recordSourceLine(0, 0, nullptr, 0);
986 // Insert labels where requested.
987 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
988 LabelsBeforeInsn.find(MI);
991 if (I == LabelsBeforeInsn.end())
994 // Label already assigned.
999 PrevLabel = MMI->getContext().CreateTempSymbol();
1000 Asm->OutStreamer.EmitLabel(PrevLabel);
1002 I->second = PrevLabel;
1005 // Process end of an instruction.
1006 void DwarfDebug::endInstruction() {
1007 assert(CurMI != nullptr);
1008 // Don't create a new label after DBG_VALUE instructions.
1009 // They don't generate code.
1010 if (!CurMI->isDebugValue())
1011 PrevLabel = nullptr;
1013 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1014 LabelsAfterInsn.find(CurMI);
1018 if (I == LabelsAfterInsn.end())
1021 // Label already assigned.
1025 // We need a label after this instruction.
1027 PrevLabel = MMI->getContext().CreateTempSymbol();
1028 Asm->OutStreamer.EmitLabel(PrevLabel);
1030 I->second = PrevLabel;
1033 // Each LexicalScope has first instruction and last instruction to mark
1034 // beginning and end of a scope respectively. Create an inverse map that list
1035 // scopes starts (and ends) with an instruction. One instruction may start (or
1036 // end) multiple scopes. Ignore scopes that are not reachable.
1037 void DwarfDebug::identifyScopeMarkers() {
1038 SmallVector<LexicalScope *, 4> WorkList;
1039 WorkList.push_back(LScopes.getCurrentFunctionScope());
1040 while (!WorkList.empty()) {
1041 LexicalScope *S = WorkList.pop_back_val();
1043 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1044 if (!Children.empty())
1045 WorkList.append(Children.begin(), Children.end());
1047 if (S->isAbstractScope())
1050 for (const InsnRange &R : S->getRanges()) {
1051 assert(R.first && "InsnRange does not have first instruction!");
1052 assert(R.second && "InsnRange does not have second instruction!");
1053 requestLabelBeforeInsn(R.first);
1054 requestLabelAfterInsn(R.second);
1059 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1060 // First known non-DBG_VALUE and non-frame setup location marks
1061 // the beginning of the function body.
1062 for (const auto &MBB : *MF)
1063 for (const auto &MI : MBB)
1064 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1066 // Did the target forget to set the FrameSetup flag for CFI insns?
1067 assert(!MI.isCFIInstruction() &&
1068 "First non-frame-setup instruction is a CFI instruction.");
1069 return MI.getDebugLoc();
1074 // Gather pre-function debug information. Assumes being called immediately
1075 // after the function entry point has been emitted.
1076 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1079 // If there's no debug info for the function we're not going to do anything.
1080 if (!MMI->hasDebugInfo())
1083 auto DI = FunctionDIs.find(MF->getFunction());
1084 if (DI == FunctionDIs.end())
1087 // Grab the lexical scopes for the function, if we don't have any of those
1088 // then we're not going to be able to do anything.
1089 LScopes.initialize(*MF);
1090 if (LScopes.empty())
1093 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1095 // Make sure that each lexical scope will have a begin/end label.
1096 identifyScopeMarkers();
1098 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1099 // belongs to so that we add to the correct per-cu line table in the
1101 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1102 // FnScope->getScopeNode() and DI->second should represent the same function,
1103 // though they may not be the same MDNode due to inline functions merged in
1104 // LTO where the debug info metadata still differs (either due to distinct
1105 // written differences - two versions of a linkonce_odr function
1106 // written/copied into two separate files, or some sub-optimal metadata that
1107 // isn't structurally identical (see: file path/name info from clang, which
1108 // includes the directory of the cpp file being built, even when the file name
1109 // is absolute (such as an <> lookup header)))
1110 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1111 assert(TheCU && "Unable to find compile unit!");
1112 if (Asm->OutStreamer.hasRawTextSupport())
1113 // Use a single line table if we are generating assembly.
1114 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1116 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1118 // Calculate history for local variables.
1119 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1122 // Request labels for the full history.
1123 for (const auto &I : DbgValues) {
1124 const auto &Ranges = I.second;
1128 // The first mention of a function argument gets the CurrentFnBegin
1129 // label, so arguments are visible when breaking at function entry.
1130 DIVariable DIVar = Ranges.front().first->getDebugVariable();
1131 if (DIVar->getTag() == dwarf::DW_TAG_arg_variable &&
1132 getDISubprogram(DIVar->getScope()).describes(MF->getFunction())) {
1133 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1134 if (Ranges.front().first->getDebugExpression()->isBitPiece()) {
1135 // Mark all non-overlapping initial pieces.
1136 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1137 DIExpression Piece = I->first->getDebugExpression();
1138 if (std::all_of(Ranges.begin(), I,
1139 [&](DbgValueHistoryMap::InstrRange Pred) {
1140 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1142 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1149 for (const auto &Range : Ranges) {
1150 requestLabelBeforeInsn(Range.first);
1152 requestLabelAfterInsn(Range.second);
1156 PrevInstLoc = DebugLoc();
1157 PrevLabel = Asm->getFunctionBegin();
1159 // Record beginning of function.
1160 PrologEndLoc = findPrologueEndLoc(MF);
1161 if (MDLocation *L = PrologEndLoc) {
1162 // We'd like to list the prologue as "not statements" but GDB behaves
1163 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1164 auto *SP = L->getInlinedAtScope()->getSubprogram();
1165 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1169 // Gather and emit post-function debug information.
1170 void DwarfDebug::endFunction(const MachineFunction *MF) {
1171 assert(CurFn == MF &&
1172 "endFunction should be called with the same function as beginFunction");
1174 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1175 !FunctionDIs.count(MF->getFunction())) {
1176 // If we don't have a lexical scope for this function then there will
1177 // be a hole in the range information. Keep note of this by setting the
1178 // previously used section to nullptr.
1184 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1185 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1187 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1188 DISubprogram SP = cast<MDSubprogram>(FnScope->getScopeNode());
1189 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1191 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1192 collectVariableInfo(TheCU, SP, ProcessedVars);
1194 // Add the range of this function to the list of ranges for the CU.
1195 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1197 // Under -gmlt, skip building the subprogram if there are no inlined
1198 // subroutines inside it.
1199 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1200 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1201 assert(InfoHolder.getScopeVariables().empty());
1202 assert(DbgValues.empty());
1203 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1204 // by a -gmlt CU. Add a test and remove this assertion.
1205 assert(AbstractVariables.empty());
1206 LabelsBeforeInsn.clear();
1207 LabelsAfterInsn.clear();
1208 PrevLabel = nullptr;
1214 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1216 // Construct abstract scopes.
1217 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1218 DISubprogram SP = cast<MDSubprogram>(AScope->getScopeNode());
1219 // Collect info for variables that were optimized out.
1220 for (DIVariable DV : SP->getVariables()) {
1221 if (!ProcessedVars.insert(DV).second)
1223 ensureAbstractVariableIsCreated(DV, DV->getScope());
1224 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1225 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1227 constructAbstractSubprogramScopeDIE(AScope);
1230 TheCU.constructSubprogramScopeDIE(FnScope);
1231 if (auto *SkelCU = TheCU.getSkeleton())
1232 if (!LScopes.getAbstractScopesList().empty())
1233 SkelCU->constructSubprogramScopeDIE(FnScope);
1236 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1237 // DbgVariables except those that are also in AbstractVariables (since they
1238 // can be used cross-function)
1239 InfoHolder.getScopeVariables().clear();
1241 LabelsBeforeInsn.clear();
1242 LabelsAfterInsn.clear();
1243 PrevLabel = nullptr;
1247 // Register a source line with debug info. Returns the unique label that was
1248 // emitted and which provides correspondence to the source line list.
1249 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1254 unsigned Discriminator = 0;
1255 if (DIScope Scope = cast_or_null<MDScope>(S)) {
1256 Fn = Scope.getFilename();
1257 Dir = Scope.getDirectory();
1258 if (DILexicalBlockFile LBF = dyn_cast<MDLexicalBlockFile>(Scope))
1259 Discriminator = LBF.getDiscriminator();
1261 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1262 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1263 .getOrCreateSourceID(Fn, Dir);
1265 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1269 //===----------------------------------------------------------------------===//
1271 //===----------------------------------------------------------------------===//
1273 // Emit the debug info section.
1274 void DwarfDebug::emitDebugInfo() {
1275 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1276 Holder.emitUnits(/* UseOffsets */ false);
1279 // Emit the abbreviation section.
1280 void DwarfDebug::emitAbbreviations() {
1281 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1283 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1286 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1287 StringRef TableName) {
1288 Accel.FinalizeTable(Asm, TableName);
1289 Asm->OutStreamer.SwitchSection(Section);
1291 // Emit the full data.
1292 Accel.emit(Asm, Section->getBeginSymbol(), this);
1295 // Emit visible names into a hashed accelerator table section.
1296 void DwarfDebug::emitAccelNames() {
1297 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1301 // Emit objective C classes and categories into a hashed accelerator table
1303 void DwarfDebug::emitAccelObjC() {
1304 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1308 // Emit namespace dies into a hashed accelerator table.
1309 void DwarfDebug::emitAccelNamespaces() {
1310 emitAccel(AccelNamespace,
1311 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1315 // Emit type dies into a hashed accelerator table.
1316 void DwarfDebug::emitAccelTypes() {
1317 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1321 // Public name handling.
1322 // The format for the various pubnames:
1324 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1325 // for the DIE that is named.
1327 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1328 // into the CU and the index value is computed according to the type of value
1329 // for the DIE that is named.
1331 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1332 // it's the offset within the debug_info/debug_types dwo section, however, the
1333 // reference in the pubname header doesn't change.
1335 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1336 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1338 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1340 // We could have a specification DIE that has our most of our knowledge,
1341 // look for that now.
1342 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1344 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1345 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1346 Linkage = dwarf::GIEL_EXTERNAL;
1347 } else if (Die->findAttribute(dwarf::DW_AT_external))
1348 Linkage = dwarf::GIEL_EXTERNAL;
1350 switch (Die->getTag()) {
1351 case dwarf::DW_TAG_class_type:
1352 case dwarf::DW_TAG_structure_type:
1353 case dwarf::DW_TAG_union_type:
1354 case dwarf::DW_TAG_enumeration_type:
1355 return dwarf::PubIndexEntryDescriptor(
1356 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1357 ? dwarf::GIEL_STATIC
1358 : dwarf::GIEL_EXTERNAL);
1359 case dwarf::DW_TAG_typedef:
1360 case dwarf::DW_TAG_base_type:
1361 case dwarf::DW_TAG_subrange_type:
1362 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1363 case dwarf::DW_TAG_namespace:
1364 return dwarf::GIEK_TYPE;
1365 case dwarf::DW_TAG_subprogram:
1366 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1367 case dwarf::DW_TAG_variable:
1368 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1369 case dwarf::DW_TAG_enumerator:
1370 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1371 dwarf::GIEL_STATIC);
1373 return dwarf::GIEK_NONE;
1377 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1379 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1380 const MCSection *PSec =
1381 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1382 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1384 emitDebugPubSection(GnuStyle, PSec, "Names",
1385 &DwarfCompileUnit::getGlobalNames);
1388 void DwarfDebug::emitDebugPubSection(
1389 bool GnuStyle, const MCSection *PSec, StringRef Name,
1390 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1391 for (const auto &NU : CUMap) {
1392 DwarfCompileUnit *TheU = NU.second;
1394 const auto &Globals = (TheU->*Accessor)();
1396 if (Globals.empty())
1399 if (auto *Skeleton = TheU->getSkeleton())
1402 // Start the dwarf pubnames section.
1403 Asm->OutStreamer.SwitchSection(PSec);
1406 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1407 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1408 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1409 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1411 Asm->OutStreamer.EmitLabel(BeginLabel);
1413 Asm->OutStreamer.AddComment("DWARF Version");
1414 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1416 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1417 Asm->emitSectionOffset(TheU->getLabelBegin());
1419 Asm->OutStreamer.AddComment("Compilation Unit Length");
1420 Asm->EmitInt32(TheU->getLength());
1422 // Emit the pubnames for this compilation unit.
1423 for (const auto &GI : Globals) {
1424 const char *Name = GI.getKeyData();
1425 const DIE *Entity = GI.second;
1427 Asm->OutStreamer.AddComment("DIE offset");
1428 Asm->EmitInt32(Entity->getOffset());
1431 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1432 Asm->OutStreamer.AddComment(
1433 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1434 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1435 Asm->EmitInt8(Desc.toBits());
1438 Asm->OutStreamer.AddComment("External Name");
1439 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1442 Asm->OutStreamer.AddComment("End Mark");
1444 Asm->OutStreamer.EmitLabel(EndLabel);
1448 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1449 const MCSection *PSec =
1450 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1451 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1453 emitDebugPubSection(GnuStyle, PSec, "Types",
1454 &DwarfCompileUnit::getGlobalTypes);
1457 // Emit visible names into a debug str section.
1458 void DwarfDebug::emitDebugStr() {
1459 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1460 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1464 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1465 const DebugLocEntry &Entry) {
1466 auto Comment = Entry.getComments().begin();
1467 auto End = Entry.getComments().end();
1468 for (uint8_t Byte : Entry.getDWARFBytes())
1469 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1472 static void emitDebugLocValue(const AsmPrinter &AP,
1473 const DITypeIdentifierMap &TypeIdentifierMap,
1474 ByteStreamer &Streamer,
1475 const DebugLocEntry::Value &Value,
1476 unsigned PieceOffsetInBits) {
1477 DIVariable DV = Value.getVariable();
1478 DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1479 AP.getDwarfDebug()->getDwarfVersion(),
1482 if (Value.isInt()) {
1483 MDType *T = DV->getType().resolve(TypeIdentifierMap);
1484 auto *B = dyn_cast<MDBasicType>(T);
1485 if (B && (B->getEncoding() == dwarf::DW_ATE_signed ||
1486 B->getEncoding() == dwarf::DW_ATE_signed_char))
1487 DwarfExpr.AddSignedConstant(Value.getInt());
1489 DwarfExpr.AddUnsignedConstant(Value.getInt());
1490 } else if (Value.isLocation()) {
1491 MachineLocation Loc = Value.getLoc();
1492 DIExpression Expr = Value.getExpression();
1493 if (!Expr || !Expr->getNumElements())
1495 AP.EmitDwarfRegOp(Streamer, Loc);
1497 // Complex address entry.
1498 if (Loc.getOffset()) {
1499 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1500 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(),
1503 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1507 // else ... ignore constant fp. There is not any good way to
1508 // to represent them here in dwarf.
1513 void DebugLocEntry::finalize(const AsmPrinter &AP,
1514 const DITypeIdentifierMap &TypeIdentifierMap) {
1515 BufferByteStreamer Streamer(DWARFBytes, Comments);
1516 const DebugLocEntry::Value Value = Values[0];
1517 if (Value.isBitPiece()) {
1518 // Emit all pieces that belong to the same variable and range.
1519 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1520 return P.isBitPiece();
1521 }) && "all values are expected to be pieces");
1522 assert(std::is_sorted(Values.begin(), Values.end()) &&
1523 "pieces are expected to be sorted");
1525 unsigned Offset = 0;
1526 for (auto Piece : Values) {
1527 DIExpression Expr = Piece.getExpression();
1528 unsigned PieceOffset = Expr->getBitPieceOffset();
1529 unsigned PieceSize = Expr->getBitPieceSize();
1530 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1531 if (Offset < PieceOffset) {
1532 // The DWARF spec seriously mandates pieces with no locations for gaps.
1533 DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1534 AP.getDwarfDebug()->getDwarfVersion(),
1536 Expr.AddOpPiece(PieceOffset-Offset, 0);
1537 Offset += PieceOffset-Offset;
1539 Offset += PieceSize;
1541 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1544 assert(Values.size() == 1 && "only pieces may have >1 value");
1545 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1550 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1551 Asm->OutStreamer.AddComment("Loc expr size");
1552 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1553 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1554 Asm->EmitLabelDifference(end, begin, 2);
1555 Asm->OutStreamer.EmitLabel(begin);
1557 APByteStreamer Streamer(*Asm);
1558 emitDebugLocEntry(Streamer, Entry);
1560 Asm->OutStreamer.EmitLabel(end);
1563 // Emit locations into the debug loc section.
1564 void DwarfDebug::emitDebugLoc() {
1565 // Start the dwarf loc section.
1566 Asm->OutStreamer.SwitchSection(
1567 Asm->getObjFileLowering().getDwarfLocSection());
1568 unsigned char Size = Asm->getDataLayout().getPointerSize();
1569 for (const auto &DebugLoc : DotDebugLocEntries) {
1570 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1571 const DwarfCompileUnit *CU = DebugLoc.CU;
1572 for (const auto &Entry : DebugLoc.List) {
1573 // Set up the range. This range is relative to the entry point of the
1574 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1575 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1576 if (auto *Base = CU->getBaseAddress()) {
1577 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1578 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1580 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1581 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1584 emitDebugLocEntryLocation(Entry);
1586 Asm->OutStreamer.EmitIntValue(0, Size);
1587 Asm->OutStreamer.EmitIntValue(0, Size);
1591 void DwarfDebug::emitDebugLocDWO() {
1592 Asm->OutStreamer.SwitchSection(
1593 Asm->getObjFileLowering().getDwarfLocDWOSection());
1594 for (const auto &DebugLoc : DotDebugLocEntries) {
1595 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1596 for (const auto &Entry : DebugLoc.List) {
1597 // Just always use start_length for now - at least that's one address
1598 // rather than two. We could get fancier and try to, say, reuse an
1599 // address we know we've emitted elsewhere (the start of the function?
1600 // The start of the CU or CU subrange that encloses this range?)
1601 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1602 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1603 Asm->EmitULEB128(idx);
1604 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1606 emitDebugLocEntryLocation(Entry);
1608 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1613 const MCSymbol *Start, *End;
1616 // Emit a debug aranges section, containing a CU lookup for any
1617 // address we can tie back to a CU.
1618 void DwarfDebug::emitDebugARanges() {
1619 // Provides a unique id per text section.
1620 MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1622 // Filter labels by section.
1623 for (const SymbolCU &SCU : ArangeLabels) {
1624 if (SCU.Sym->isInSection()) {
1625 // Make a note of this symbol and it's section.
1626 const MCSection *Section = &SCU.Sym->getSection();
1627 if (!Section->getKind().isMetadata())
1628 SectionMap[Section].push_back(SCU);
1630 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1631 // appear in the output. This sucks as we rely on sections to build
1632 // arange spans. We can do it without, but it's icky.
1633 SectionMap[nullptr].push_back(SCU);
1637 // Add terminating symbols for each section.
1638 for (const auto &I : SectionMap) {
1639 const MCSection *Section = I.first;
1640 MCSymbol *Sym = nullptr;
1643 Sym = Asm->OutStreamer.endSection(Section);
1645 // Insert a final terminator.
1646 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1649 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1651 for (auto &I : SectionMap) {
1652 const MCSection *Section = I.first;
1653 SmallVector<SymbolCU, 8> &List = I.second;
1654 if (List.size() < 2)
1657 // If we have no section (e.g. common), just write out
1658 // individual spans for each symbol.
1660 for (const SymbolCU &Cur : List) {
1662 Span.Start = Cur.Sym;
1665 Spans[Cur.CU].push_back(Span);
1670 // Sort the symbols by offset within the section.
1671 std::sort(List.begin(), List.end(),
1672 [&](const SymbolCU &A, const SymbolCU &B) {
1673 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1674 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1676 // Symbols with no order assigned should be placed at the end.
1677 // (e.g. section end labels)
1685 // Build spans between each label.
1686 const MCSymbol *StartSym = List[0].Sym;
1687 for (size_t n = 1, e = List.size(); n < e; n++) {
1688 const SymbolCU &Prev = List[n - 1];
1689 const SymbolCU &Cur = List[n];
1691 // Try and build the longest span we can within the same CU.
1692 if (Cur.CU != Prev.CU) {
1694 Span.Start = StartSym;
1696 Spans[Prev.CU].push_back(Span);
1702 // Start the dwarf aranges section.
1703 Asm->OutStreamer.SwitchSection(
1704 Asm->getObjFileLowering().getDwarfARangesSection());
1706 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1708 // Build a list of CUs used.
1709 std::vector<DwarfCompileUnit *> CUs;
1710 for (const auto &it : Spans) {
1711 DwarfCompileUnit *CU = it.first;
1715 // Sort the CU list (again, to ensure consistent output order).
1716 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1717 return A->getUniqueID() < B->getUniqueID();
1720 // Emit an arange table for each CU we used.
1721 for (DwarfCompileUnit *CU : CUs) {
1722 std::vector<ArangeSpan> &List = Spans[CU];
1724 // Describe the skeleton CU's offset and length, not the dwo file's.
1725 if (auto *Skel = CU->getSkeleton())
1728 // Emit size of content not including length itself.
1729 unsigned ContentSize =
1730 sizeof(int16_t) + // DWARF ARange version number
1731 sizeof(int32_t) + // Offset of CU in the .debug_info section
1732 sizeof(int8_t) + // Pointer Size (in bytes)
1733 sizeof(int8_t); // Segment Size (in bytes)
1735 unsigned TupleSize = PtrSize * 2;
1737 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1739 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1741 ContentSize += Padding;
1742 ContentSize += (List.size() + 1) * TupleSize;
1744 // For each compile unit, write the list of spans it covers.
1745 Asm->OutStreamer.AddComment("Length of ARange Set");
1746 Asm->EmitInt32(ContentSize);
1747 Asm->OutStreamer.AddComment("DWARF Arange version number");
1748 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1749 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1750 Asm->emitSectionOffset(CU->getLabelBegin());
1751 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1752 Asm->EmitInt8(PtrSize);
1753 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1756 Asm->OutStreamer.EmitFill(Padding, 0xff);
1758 for (const ArangeSpan &Span : List) {
1759 Asm->EmitLabelReference(Span.Start, PtrSize);
1761 // Calculate the size as being from the span start to it's end.
1763 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1765 // For symbols without an end marker (e.g. common), we
1766 // write a single arange entry containing just that one symbol.
1767 uint64_t Size = SymSize[Span.Start];
1771 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1775 Asm->OutStreamer.AddComment("ARange terminator");
1776 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1777 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1781 // Emit visible names into a debug ranges section.
1782 void DwarfDebug::emitDebugRanges() {
1783 // Start the dwarf ranges section.
1784 Asm->OutStreamer.SwitchSection(
1785 Asm->getObjFileLowering().getDwarfRangesSection());
1787 // Size for our labels.
1788 unsigned char Size = Asm->getDataLayout().getPointerSize();
1790 // Grab the specific ranges for the compile units in the module.
1791 for (const auto &I : CUMap) {
1792 DwarfCompileUnit *TheCU = I.second;
1794 if (auto *Skel = TheCU->getSkeleton())
1797 // Iterate over the misc ranges for the compile units in the module.
1798 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1799 // Emit our symbol so we can find the beginning of the range.
1800 Asm->OutStreamer.EmitLabel(List.getSym());
1802 for (const RangeSpan &Range : List.getRanges()) {
1803 const MCSymbol *Begin = Range.getStart();
1804 const MCSymbol *End = Range.getEnd();
1805 assert(Begin && "Range without a begin symbol?");
1806 assert(End && "Range without an end symbol?");
1807 if (auto *Base = TheCU->getBaseAddress()) {
1808 Asm->EmitLabelDifference(Begin, Base, Size);
1809 Asm->EmitLabelDifference(End, Base, Size);
1811 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1812 Asm->OutStreamer.EmitSymbolValue(End, Size);
1816 // And terminate the list with two 0 values.
1817 Asm->OutStreamer.EmitIntValue(0, Size);
1818 Asm->OutStreamer.EmitIntValue(0, Size);
1823 // DWARF5 Experimental Separate Dwarf emitters.
1825 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1826 std::unique_ptr<DwarfUnit> NewU) {
1827 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1828 U.getCUNode().getSplitDebugFilename());
1830 if (!CompilationDir.empty())
1831 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1833 addGnuPubAttributes(*NewU, Die);
1835 SkeletonHolder.addUnit(std::move(NewU));
1838 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1839 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1840 // DW_AT_addr_base, DW_AT_ranges_base.
1841 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1843 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1844 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1845 DwarfCompileUnit &NewCU = *OwnedUnit;
1846 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1848 NewCU.initStmtList();
1850 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1855 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1856 // compile units that would normally be in debug_info.
1857 void DwarfDebug::emitDebugInfoDWO() {
1858 assert(useSplitDwarf() && "No split dwarf debug info?");
1859 // Don't emit relocations into the dwo file.
1860 InfoHolder.emitUnits(/* UseOffsets */ true);
1863 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1864 // abbreviations for the .debug_info.dwo section.
1865 void DwarfDebug::emitDebugAbbrevDWO() {
1866 assert(useSplitDwarf() && "No split dwarf?");
1867 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1870 void DwarfDebug::emitDebugLineDWO() {
1871 assert(useSplitDwarf() && "No split dwarf?");
1872 Asm->OutStreamer.SwitchSection(
1873 Asm->getObjFileLowering().getDwarfLineDWOSection());
1874 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
1877 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1878 // string section and is identical in format to traditional .debug_str
1880 void DwarfDebug::emitDebugStrDWO() {
1881 assert(useSplitDwarf() && "No split dwarf?");
1882 const MCSection *OffSec =
1883 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1884 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1888 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1889 if (!useSplitDwarf())
1892 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
1893 return &SplitTypeUnitFileTable;
1896 static uint64_t makeTypeSignature(StringRef Identifier) {
1898 Hash.update(Identifier);
1899 // ... take the least significant 8 bytes and return those. Our MD5
1900 // implementation always returns its results in little endian, swap bytes
1902 MD5::MD5Result Result;
1904 return support::endian::read64le(Result + 8);
1907 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1908 StringRef Identifier, DIE &RefDie,
1909 DICompositeType CTy) {
1910 // Fast path if we're building some type units and one has already used the
1911 // address pool we know we're going to throw away all this work anyway, so
1912 // don't bother building dependent types.
1913 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1916 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
1918 CU.addDIETypeSignature(RefDie, *TU);
1922 bool TopLevelType = TypeUnitsUnderConstruction.empty();
1923 AddrPool.resetUsedFlag();
1925 auto OwnedUnit = make_unique<DwarfTypeUnit>(
1926 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
1927 this, &InfoHolder, getDwoLineTable(CU));
1928 DwarfTypeUnit &NewTU = *OwnedUnit;
1929 DIE &UnitDie = NewTU.getUnitDie();
1931 TypeUnitsUnderConstruction.push_back(
1932 std::make_pair(std::move(OwnedUnit), CTy));
1934 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1937 uint64_t Signature = makeTypeSignature(Identifier);
1938 NewTU.setTypeSignature(Signature);
1940 if (useSplitDwarf())
1941 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1943 CU.applyStmtList(UnitDie);
1945 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1948 NewTU.setType(NewTU.createTypeDIE(CTy));
1951 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1952 TypeUnitsUnderConstruction.clear();
1954 // Types referencing entries in the address table cannot be placed in type
1956 if (AddrPool.hasBeenUsed()) {
1958 // Remove all the types built while building this type.
1959 // This is pessimistic as some of these types might not be dependent on
1960 // the type that used an address.
1961 for (const auto &TU : TypeUnitsToAdd)
1962 DwarfTypeUnits.erase(TU.second);
1964 // Construct this type in the CU directly.
1965 // This is inefficient because all the dependent types will be rebuilt
1966 // from scratch, including building them in type units, discovering that
1967 // they depend on addresses, throwing them out and rebuilding them.
1968 CU.constructTypeDIE(RefDie, CTy);
1972 // If the type wasn't dependent on fission addresses, finish adding the type
1973 // and all its dependent types.
1974 for (auto &TU : TypeUnitsToAdd)
1975 InfoHolder.addUnit(std::move(TU.first));
1977 CU.addDIETypeSignature(RefDie, NewTU);
1980 // Accelerator table mutators - add each name along with its companion
1981 // DIE to the proper table while ensuring that the name that we're going
1982 // to reference is in the string table. We do this since the names we
1983 // add may not only be identical to the names in the DIE.
1984 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
1985 if (!useDwarfAccelTables())
1987 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
1991 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
1992 if (!useDwarfAccelTables())
1994 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
1998 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
1999 if (!useDwarfAccelTables())
2001 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2005 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2006 if (!useDwarfAccelTables())
2008 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),