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/Target/TargetFrameLowering.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include "llvm/Target/TargetRegisterInfo.h"
53 #include "llvm/Target/TargetSubtargetInfo.h"
56 #define DEBUG_TYPE "dwarfdebug"
59 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
60 cl::desc("Disable debug info printing"));
62 static cl::opt<bool> UnknownLocations(
63 "use-unknown-locations", cl::Hidden,
64 cl::desc("Make an absence of debug location information explicit."),
68 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
69 cl::desc("Generate GNU-style pubnames and pubtypes"),
72 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74 cl::desc("Generate dwarf aranges"),
78 enum DefaultOnOff { Default, Enable, Disable };
81 static cl::opt<DefaultOnOff>
82 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
83 cl::desc("Output prototype dwarf accelerator tables."),
84 cl::values(clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"), clEnumValEnd),
89 static cl::opt<DefaultOnOff>
90 SplitDwarf("split-dwarf", cl::Hidden,
91 cl::desc("Output DWARF5 split debug info."),
92 cl::values(clEnumVal(Default, "Default for platform"),
93 clEnumVal(Enable, "Enabled"),
94 clEnumVal(Disable, "Disabled"), clEnumValEnd),
97 static cl::opt<DefaultOnOff>
98 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
99 cl::desc("Generate DWARF pubnames and pubtypes sections"),
100 cl::values(clEnumVal(Default, "Default for platform"),
101 clEnumVal(Enable, "Enabled"),
102 clEnumVal(Disable, "Disabled"), clEnumValEnd),
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
110 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
111 : dwarf::OperationEncodingString(Op));
114 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
115 BS.EmitSLEB128(Value, Twine(Value));
118 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
119 BS.EmitULEB128(Value, Twine(Value));
122 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
123 // This information is not available while emitting .debug_loc entries.
127 //===----------------------------------------------------------------------===//
129 /// resolve - Look in the DwarfDebug map for the MDNode that
130 /// corresponds to the reference.
131 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
132 return DD->resolve(Ref);
135 bool DbgVariable::isBlockByrefVariable() const {
136 assert(Var.isVariable() && "Invalid complex DbgVariable!");
137 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
140 DIType DbgVariable::getType() const {
141 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
142 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
143 // addresses instead.
144 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
145 /* Byref variables, in Blocks, are declared by the programmer as
146 "SomeType VarName;", but the compiler creates a
147 __Block_byref_x_VarName struct, and gives the variable VarName
148 either the struct, or a pointer to the struct, as its type. This
149 is necessary for various behind-the-scenes things the compiler
150 needs to do with by-reference variables in blocks.
152 However, as far as the original *programmer* is concerned, the
153 variable should still have type 'SomeType', as originally declared.
155 The following function dives into the __Block_byref_x_VarName
156 struct to find the original type of the variable. This will be
157 passed back to the code generating the type for the Debug
158 Information Entry for the variable 'VarName'. 'VarName' will then
159 have the original type 'SomeType' in its debug information.
161 The original type 'SomeType' will be the type of the field named
162 'VarName' inside the __Block_byref_x_VarName struct.
164 NOTE: In order for this to not completely fail on the debugger
165 side, the Debug Information Entry for the variable VarName needs to
166 have a DW_AT_location that tells the debugger how to unwind through
167 the pointers and __Block_byref_x_VarName struct to find the actual
168 value of the variable. The function addBlockByrefType does this. */
170 uint16_t tag = Ty.getTag();
172 if (tag == dwarf::DW_TAG_pointer_type)
173 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
175 DIArray Elements = DICompositeType(subType).getElements();
176 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
177 DIDerivedType DT(Elements.getElement(i));
178 if (getName() == DT.getName())
179 return (resolve(DT.getTypeDerivedFrom()));
185 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
186 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
187 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
188 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
190 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
191 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr),
192 InfoHolder(A, "info_string", DIEValueAllocator),
193 UsedNonDefaultText(false),
194 SkeletonHolder(A, "skel_string", DIEValueAllocator),
195 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
196 IsPS4(Triple(A->getTargetTriple()).isPS4()),
197 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
198 dwarf::DW_FORM_data4)),
199 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
200 dwarf::DW_FORM_data4)),
201 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
202 dwarf::DW_FORM_data4)),
203 AccelTypes(TypeAtoms) {
208 // Turn on accelerator tables for Darwin by default, pubnames by
209 // default for non-Darwin/PS4, and handle split dwarf.
210 if (DwarfAccelTables == Default)
211 HasDwarfAccelTables = IsDarwin;
213 HasDwarfAccelTables = DwarfAccelTables == Enable;
215 if (SplitDwarf == Default)
216 HasSplitDwarf = false;
218 HasSplitDwarf = SplitDwarf == Enable;
220 if (DwarfPubSections == Default)
221 HasDwarfPubSections = !IsDarwin && !IsPS4;
223 HasDwarfPubSections = DwarfPubSections == Enable;
225 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
226 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
227 : MMI->getModule()->getDwarfVersion();
229 // Darwin and PS4 use the standard TLS opcode (defined in DWARF 3).
230 // Everybody else uses GNU's.
231 UseGNUTLSOpcode = !(IsDarwin || IsPS4) || DwarfVersion < 3;
233 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
236 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
241 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
242 DwarfDebug::~DwarfDebug() { }
244 static bool isObjCClass(StringRef Name) {
245 return Name.startswith("+") || Name.startswith("-");
248 static bool hasObjCCategory(StringRef Name) {
249 if (!isObjCClass(Name))
252 return Name.find(") ") != StringRef::npos;
255 static void getObjCClassCategory(StringRef In, StringRef &Class,
256 StringRef &Category) {
257 if (!hasObjCCategory(In)) {
258 Class = In.slice(In.find('[') + 1, In.find(' '));
263 Class = In.slice(In.find('[') + 1, In.find('('));
264 Category = In.slice(In.find('[') + 1, In.find(' '));
268 static StringRef getObjCMethodName(StringRef In) {
269 return In.slice(In.find(' ') + 1, In.find(']'));
272 // Add the various names to the Dwarf accelerator table names.
273 // TODO: Determine whether or not we should add names for programs
274 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
275 // is only slightly different than the lookup of non-standard ObjC names.
276 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
277 if (!SP.isDefinition())
279 addAccelName(SP.getName(), Die);
281 // If the linkage name is different than the name, go ahead and output
282 // that as well into the name table.
283 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284 addAccelName(SP.getLinkageName(), Die);
286 // If this is an Objective-C selector name add it to the ObjC accelerator
288 if (isObjCClass(SP.getName())) {
289 StringRef Class, Category;
290 getObjCClassCategory(SP.getName(), Class, Category);
291 addAccelObjC(Class, Die);
293 addAccelObjC(Category, Die);
294 // Also add the base method name to the name table.
295 addAccelName(getObjCMethodName(SP.getName()), Die);
299 /// isSubprogramContext - Return true if Context is either a subprogram
300 /// or another context nested inside a subprogram.
301 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
304 DIDescriptor D(Context);
305 if (D.isSubprogram())
308 return isSubprogramContext(resolve(DIType(Context).getContext()));
312 /// Check whether we should create a DIE for the given Scope, return true
313 /// if we don't create a DIE (the corresponding DIE is null).
314 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
315 if (Scope->isAbstractScope())
318 // We don't create a DIE if there is no Range.
319 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
323 if (Ranges.size() > 1)
326 // We don't create a DIE if we have a single Range and the end label
328 return !getLabelAfterInsn(Ranges.front().second);
331 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
333 if (auto *SkelCU = CU.getSkeleton())
337 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
338 assert(Scope && Scope->getScopeNode());
339 assert(Scope->isAbstractScope());
340 assert(!Scope->getInlinedAt());
342 const MDNode *SP = Scope->getScopeNode();
344 ProcessedSPNodes.insert(SP);
346 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
347 // was inlined from another compile unit.
348 auto &CU = SPMap[SP];
349 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
350 CU.constructAbstractSubprogramScopeDIE(Scope);
354 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
355 if (!GenerateGnuPubSections)
358 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
361 // Create new DwarfCompileUnit for the given metadata node with tag
362 // DW_TAG_compile_unit.
363 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
364 StringRef FN = DIUnit.getFilename();
365 CompilationDir = DIUnit.getDirectory();
367 auto OwnedUnit = make_unique<DwarfCompileUnit>(
368 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
369 DwarfCompileUnit &NewCU = *OwnedUnit;
370 DIE &Die = NewCU.getUnitDie();
371 InfoHolder.addUnit(std::move(OwnedUnit));
373 NewCU.setSkeleton(constructSkeletonCU(NewCU));
375 // LTO with assembly output shares a single line table amongst multiple CUs.
376 // To avoid the compilation directory being ambiguous, let the line table
377 // explicitly describe the directory of all files, never relying on the
378 // compilation directory.
379 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
380 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
381 NewCU.getUniqueID(), CompilationDir);
383 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
384 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
385 DIUnit.getLanguage());
386 NewCU.addString(Die, dwarf::DW_AT_name, FN);
388 if (!useSplitDwarf()) {
389 NewCU.initStmtList();
391 // If we're using split dwarf the compilation dir is going to be in the
392 // skeleton CU and so we don't need to duplicate it here.
393 if (!CompilationDir.empty())
394 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
396 addGnuPubAttributes(NewCU, Die);
399 if (DIUnit.isOptimized())
400 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
402 StringRef Flags = DIUnit.getFlags();
404 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
406 if (unsigned RVer = DIUnit.getRunTimeVersion())
407 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
408 dwarf::DW_FORM_data1, RVer);
411 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
415 CUMap.insert(std::make_pair(DIUnit, &NewCU));
416 CUDieMap.insert(std::make_pair(&Die, &NewCU));
420 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
422 DIImportedEntity Module(N);
423 assert(Module.Verify());
424 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
425 D->addChild(TheCU.constructImportedEntityDIE(Module));
428 // Emit all Dwarf sections that should come prior to the content. Create
429 // global DIEs and emit initial debug info sections. This is invoked by
430 // the target AsmPrinter.
431 void DwarfDebug::beginModule() {
432 if (DisableDebugInfoPrinting)
435 const Module *M = MMI->getModule();
437 FunctionDIs = makeSubprogramMap(*M);
439 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
442 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
444 SingleCU = CU_Nodes->getNumOperands() == 1;
446 for (MDNode *N : CU_Nodes->operands()) {
447 DICompileUnit CUNode(N);
448 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
449 DIArray ImportedEntities = CUNode.getImportedEntities();
450 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
451 ScopesWithImportedEntities.push_back(std::make_pair(
452 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
453 ImportedEntities.getElement(i)));
454 // Stable sort to preserve the order of appearance of imported entities.
455 // This is to avoid out-of-order processing of interdependent declarations
456 // within the same scope, e.g. { namespace A = base; namespace B = A; }
457 std::stable_sort(ScopesWithImportedEntities.begin(),
458 ScopesWithImportedEntities.end(), less_first());
459 DIArray GVs = CUNode.getGlobalVariables();
460 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
461 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
462 DIArray SPs = CUNode.getSubprograms();
463 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
464 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
465 DIArray EnumTypes = CUNode.getEnumTypes();
466 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
467 DIType Ty(EnumTypes.getElement(i));
468 // The enum types array by design contains pointers to
469 // MDNodes rather than DIRefs. Unique them here.
470 DIType UniqueTy(resolve(Ty.getRef()));
471 CU.getOrCreateTypeDIE(UniqueTy);
473 DIArray RetainedTypes = CUNode.getRetainedTypes();
474 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
475 DIType Ty(RetainedTypes.getElement(i));
476 // The retained types array by design contains pointers to
477 // MDNodes rather than DIRefs. Unique them here.
478 DIType UniqueTy(resolve(Ty.getRef()));
479 CU.getOrCreateTypeDIE(UniqueTy);
481 // Emit imported_modules last so that the relevant context is already
483 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
484 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
487 // Tell MMI that we have debug info.
488 MMI->setDebugInfoAvailability(true);
491 void DwarfDebug::finishVariableDefinitions() {
492 for (const auto &Var : ConcreteVariables) {
493 DIE *VariableDie = Var->getDIE();
495 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
496 // in the ConcreteVariables list, rather than looking it up again here.
497 // DIE::getUnit isn't simple - it walks parent pointers, etc.
498 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
500 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
501 if (AbsVar && AbsVar->getDIE()) {
502 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
505 Unit->applyVariableAttributes(*Var, *VariableDie);
509 void DwarfDebug::finishSubprogramDefinitions() {
510 for (const auto &P : SPMap)
511 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
512 CU.finishSubprogramDefinition(DISubprogram(P.first));
517 // Collect info for variables that were optimized out.
518 void DwarfDebug::collectDeadVariables() {
519 const Module *M = MMI->getModule();
521 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
522 for (MDNode *N : CU_Nodes->operands()) {
523 DICompileUnit TheCU(N);
524 // Construct subprogram DIE and add variables DIEs.
525 DwarfCompileUnit *SPCU =
526 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
527 assert(SPCU && "Unable to find Compile Unit!");
528 DIArray Subprograms = TheCU.getSubprograms();
529 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
530 DISubprogram SP(Subprograms.getElement(i));
531 if (ProcessedSPNodes.count(SP) != 0)
533 SPCU->collectDeadVariables(SP);
539 void DwarfDebug::finalizeModuleInfo() {
540 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
542 finishSubprogramDefinitions();
544 finishVariableDefinitions();
546 // Collect info for variables that were optimized out.
547 collectDeadVariables();
549 // Handle anything that needs to be done on a per-unit basis after
550 // all other generation.
551 for (const auto &P : CUMap) {
552 auto &TheCU = *P.second;
553 // Emit DW_AT_containing_type attribute to connect types with their
554 // vtable holding type.
555 TheCU.constructContainingTypeDIEs();
557 // Add CU specific attributes if we need to add any.
558 // If we're splitting the dwarf out now that we've got the entire
559 // CU then add the dwo id to it.
560 auto *SkCU = TheCU.getSkeleton();
561 if (useSplitDwarf()) {
562 // Emit a unique identifier for this CU.
563 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
564 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
565 dwarf::DW_FORM_data8, ID);
566 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
567 dwarf::DW_FORM_data8, ID);
569 // We don't keep track of which addresses are used in which CU so this
570 // is a bit pessimistic under LTO.
571 if (!AddrPool.isEmpty()) {
572 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
573 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
576 if (!SkCU->getRangeLists().empty()) {
577 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
578 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
583 // If we have code split among multiple sections or non-contiguous
584 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
585 // remain in the .o file, otherwise add a DW_AT_low_pc.
586 // FIXME: We should use ranges allow reordering of code ala
587 // .subsections_via_symbols in mach-o. This would mean turning on
588 // ranges for all subprogram DIEs for mach-o.
589 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
590 if (unsigned NumRanges = TheCU.getRanges().size()) {
592 // A DW_AT_low_pc attribute may also be specified in combination with
593 // DW_AT_ranges to specify the default base address for use in
594 // location lists (see Section 2.6.2) and range lists (see Section
596 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
598 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
599 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
603 // Compute DIE offsets and sizes.
604 InfoHolder.computeSizeAndOffsets();
606 SkeletonHolder.computeSizeAndOffsets();
609 // Emit all Dwarf sections that should come after the content.
610 void DwarfDebug::endModule() {
611 assert(CurFn == nullptr);
612 assert(CurMI == nullptr);
614 // If we aren't actually generating debug info (check beginModule -
615 // conditionalized on !DisableDebugInfoPrinting and the presence of the
616 // llvm.dbg.cu metadata node)
617 if (!MMI->hasDebugInfo())
620 // Finalize the debug info for the module.
621 finalizeModuleInfo();
628 // Emit info into a debug loc section.
631 // Corresponding abbreviations into a abbrev section.
634 // Emit all the DIEs into a debug info section.
637 // Emit info into a debug aranges section.
638 if (GenerateARangeSection)
641 // Emit info into a debug ranges section.
644 if (useSplitDwarf()) {
647 emitDebugAbbrevDWO();
649 // Emit DWO addresses.
650 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
653 // Emit info into the dwarf accelerator table sections.
654 if (useDwarfAccelTables()) {
657 emitAccelNamespaces();
661 // Emit the pubnames and pubtypes sections if requested.
662 if (HasDwarfPubSections) {
663 emitDebugPubNames(GenerateGnuPubSections);
664 emitDebugPubTypes(GenerateGnuPubSections);
669 AbstractVariables.clear();
672 // Find abstract variable, if any, associated with Var.
673 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
674 DIVariable &Cleansed) {
675 LLVMContext &Ctx = DV->getContext();
676 // More then one inlined variable corresponds to one abstract variable.
677 // FIXME: This duplication of variables when inlining should probably be
678 // removed. It's done to allow each DIVariable to describe its location
679 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
680 // make it accurate then remove this duplication/cleansing stuff.
681 Cleansed = cleanseInlinedVariable(DV, Ctx);
682 auto I = AbstractVariables.find(Cleansed);
683 if (I != AbstractVariables.end())
684 return I->second.get();
688 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
690 return getExistingAbstractVariable(DV, Cleansed);
693 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
694 LexicalScope *Scope) {
695 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
696 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
697 AbstractVariables[Var] = std::move(AbsDbgVariable);
700 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
701 const MDNode *ScopeNode) {
702 DIVariable Cleansed = DV;
703 if (getExistingAbstractVariable(DV, Cleansed))
706 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
710 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
711 const MDNode *ScopeNode) {
712 DIVariable Cleansed = DV;
713 if (getExistingAbstractVariable(DV, Cleansed))
716 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
717 createAbstractVariable(Cleansed, Scope);
720 // Collect variable information from side table maintained by MMI.
721 void DwarfDebug::collectVariableInfoFromMMITable(
722 SmallPtrSetImpl<const MDNode *> &Processed) {
723 for (const auto &VI : MMI->getVariableDbgInfo()) {
726 Processed.insert(VI.Var);
727 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
729 // If variable scope is not found then skip this variable.
733 DIVariable DV(VI.Var);
734 DIExpression Expr(VI.Expr);
735 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
736 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
737 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
738 ConcreteVariables.push_back(std::move(RegVar));
742 // Get .debug_loc entry for the instruction range starting at MI.
743 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
744 const MDNode *Expr = MI->getDebugExpression();
745 const MDNode *Var = MI->getDebugVariable();
747 assert(MI->getNumOperands() == 4);
748 if (MI->getOperand(0).isReg()) {
749 MachineLocation MLoc;
750 // If the second operand is an immediate, this is a
751 // register-indirect address.
752 if (!MI->getOperand(1).isImm())
753 MLoc.set(MI->getOperand(0).getReg());
755 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
756 return DebugLocEntry::Value(Var, Expr, MLoc);
758 if (MI->getOperand(0).isImm())
759 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
760 if (MI->getOperand(0).isFPImm())
761 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
762 if (MI->getOperand(0).isCImm())
763 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
765 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
768 /// Determine whether two variable pieces overlap.
769 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
770 if (!P1.isBitPiece() || !P2.isBitPiece())
772 unsigned l1 = P1.getBitPieceOffset();
773 unsigned l2 = P2.getBitPieceOffset();
774 unsigned r1 = l1 + P1.getBitPieceSize();
775 unsigned r2 = l2 + P2.getBitPieceSize();
776 // True where [l1,r1[ and [r1,r2[ overlap.
777 return (l1 < r2) && (l2 < r1);
780 /// Build the location list for all DBG_VALUEs in the function that
781 /// describe the same variable. If the ranges of several independent
782 /// pieces of the same variable overlap partially, split them up and
783 /// combine the ranges. The resulting DebugLocEntries are will have
784 /// strict monotonically increasing begin addresses and will never
789 // Ranges History [var, loc, piece ofs size]
790 // 0 | [x, (reg0, piece 0, 32)]
791 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
793 // 3 | [clobber reg0]
794 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
799 // [0-1] [x, (reg0, piece 0, 32)]
800 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
801 // [3-4] [x, (reg1, piece 32, 32)]
802 // [4- ] [x, (mem, piece 0, 64)]
804 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
805 const DbgValueHistoryMap::InstrRanges &Ranges) {
806 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
808 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
809 const MachineInstr *Begin = I->first;
810 const MachineInstr *End = I->second;
811 assert(Begin->isDebugValue() && "Invalid History entry");
813 // Check if a variable is inaccessible in this range.
814 if (Begin->getNumOperands() > 1 &&
815 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
820 // If this piece overlaps with any open ranges, truncate them.
821 DIExpression DIExpr = Begin->getDebugExpression();
822 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
823 [&](DebugLocEntry::Value R) {
824 return piecesOverlap(DIExpr, R.getExpression());
826 OpenRanges.erase(Last, OpenRanges.end());
828 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
829 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
831 const MCSymbol *EndLabel;
833 EndLabel = getLabelAfterInsn(End);
834 else if (std::next(I) == Ranges.end())
835 EndLabel = Asm->getFunctionEnd();
837 EndLabel = getLabelBeforeInsn(std::next(I)->first);
838 assert(EndLabel && "Forgot label after instruction ending a range!");
840 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
842 auto Value = getDebugLocValue(Begin);
843 DebugLocEntry Loc(StartLabel, EndLabel, Value);
844 bool couldMerge = false;
846 // If this is a piece, it may belong to the current DebugLocEntry.
847 if (DIExpr.isBitPiece()) {
848 // Add this value to the list of open ranges.
849 OpenRanges.push_back(Value);
851 // Attempt to add the piece to the last entry.
852 if (!DebugLoc.empty())
853 if (DebugLoc.back().MergeValues(Loc))
858 // Need to add a new DebugLocEntry. Add all values from still
859 // valid non-overlapping pieces.
860 if (OpenRanges.size())
861 Loc.addValues(OpenRanges);
863 DebugLoc.push_back(std::move(Loc));
866 // Attempt to coalesce the ranges of two otherwise identical
868 auto CurEntry = DebugLoc.rbegin();
869 auto PrevEntry = std::next(CurEntry);
870 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
874 dbgs() << CurEntry->getValues().size() << " Values:\n";
875 for (auto Value : CurEntry->getValues()) {
876 Value.getVariable()->dump();
877 Value.getExpression()->dump();
885 // Find variables for each lexical scope.
887 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
888 SmallPtrSetImpl<const MDNode *> &Processed) {
889 // Grab the variable info that was squirreled away in the MMI side-table.
890 collectVariableInfoFromMMITable(Processed);
892 for (const auto &I : DbgValues) {
893 DIVariable DV(I.first);
894 if (Processed.count(DV))
897 // Instruction ranges, specifying where DV is accessible.
898 const auto &Ranges = I.second;
902 LexicalScope *Scope = nullptr;
903 if (MDNode *IA = DV.getInlinedAt())
904 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
906 Scope = LScopes.findLexicalScope(DV.getContext());
907 // If variable scope is not found then skip this variable.
911 Processed.insert(DV);
912 const MachineInstr *MInsn = Ranges.front().first;
913 assert(MInsn->isDebugValue() && "History must begin with debug value");
914 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
915 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
916 DbgVariable *RegVar = ConcreteVariables.back().get();
917 InfoHolder.addScopeVariable(Scope, RegVar);
919 // Check if the first DBG_VALUE is valid for the rest of the function.
920 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
923 // Handle multiple DBG_VALUE instructions describing one variable.
924 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
926 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
927 DebugLocList &LocList = DotDebugLocEntries.back();
929 LocList.Label = Asm->createTempSymbol("debug_loc");
931 // Build the location list for this variable.
932 buildLocationList(LocList.List, Ranges);
933 // Finalize the entry by lowering it into a DWARF bytestream.
934 for (auto &Entry : LocList.List)
935 Entry.finalize(*Asm, TypeIdentifierMap);
938 // Collect info for variables that were optimized out.
939 DIArray Variables = SP.getVariables();
940 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
941 DIVariable DV(Variables.getElement(i));
942 assert(DV.isVariable());
943 if (!Processed.insert(DV).second)
945 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
946 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
948 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
949 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
954 // Return Label preceding the instruction.
955 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
956 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
957 assert(Label && "Didn't insert label before instruction");
961 // Return Label immediately following the instruction.
962 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
963 return LabelsAfterInsn.lookup(MI);
966 // Process beginning of an instruction.
967 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
968 assert(CurMI == nullptr);
970 // Check if source location changes, but ignore DBG_VALUE locations.
971 if (!MI->isDebugValue()) {
972 DebugLoc DL = MI->getDebugLoc();
973 if (DL != PrevInstLoc) {
974 if (!DL.isUnknown()) {
977 if (DL == PrologEndLoc) {
978 Flags |= DWARF2_FLAG_PROLOGUE_END;
979 PrologEndLoc = DebugLoc();
980 Flags |= DWARF2_FLAG_IS_STMT;
983 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
984 Flags |= DWARF2_FLAG_IS_STMT;
986 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
987 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
988 } else if (UnknownLocations) {
990 recordSourceLine(0, 0, nullptr, 0);
995 // Insert labels where requested.
996 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
997 LabelsBeforeInsn.find(MI);
1000 if (I == LabelsBeforeInsn.end())
1003 // Label already assigned.
1008 PrevLabel = MMI->getContext().CreateTempSymbol();
1009 Asm->OutStreamer.EmitLabel(PrevLabel);
1011 I->second = PrevLabel;
1014 // Process end of an instruction.
1015 void DwarfDebug::endInstruction() {
1016 assert(CurMI != nullptr);
1017 // Don't create a new label after DBG_VALUE instructions.
1018 // They don't generate code.
1019 if (!CurMI->isDebugValue())
1020 PrevLabel = nullptr;
1022 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1023 LabelsAfterInsn.find(CurMI);
1027 if (I == LabelsAfterInsn.end())
1030 // Label already assigned.
1034 // We need a label after this instruction.
1036 PrevLabel = MMI->getContext().CreateTempSymbol();
1037 Asm->OutStreamer.EmitLabel(PrevLabel);
1039 I->second = PrevLabel;
1042 // Each LexicalScope has first instruction and last instruction to mark
1043 // beginning and end of a scope respectively. Create an inverse map that list
1044 // scopes starts (and ends) with an instruction. One instruction may start (or
1045 // end) multiple scopes. Ignore scopes that are not reachable.
1046 void DwarfDebug::identifyScopeMarkers() {
1047 SmallVector<LexicalScope *, 4> WorkList;
1048 WorkList.push_back(LScopes.getCurrentFunctionScope());
1049 while (!WorkList.empty()) {
1050 LexicalScope *S = WorkList.pop_back_val();
1052 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1053 if (!Children.empty())
1054 WorkList.append(Children.begin(), Children.end());
1056 if (S->isAbstractScope())
1059 for (const InsnRange &R : S->getRanges()) {
1060 assert(R.first && "InsnRange does not have first instruction!");
1061 assert(R.second && "InsnRange does not have second instruction!");
1062 requestLabelBeforeInsn(R.first);
1063 requestLabelAfterInsn(R.second);
1068 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1069 // First known non-DBG_VALUE and non-frame setup location marks
1070 // the beginning of the function body.
1071 for (const auto &MBB : *MF)
1072 for (const auto &MI : MBB)
1073 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1074 !MI.getDebugLoc().isUnknown()) {
1075 // Did the target forget to set the FrameSetup flag for CFI insns?
1076 assert(!MI.isCFIInstruction() &&
1077 "First non-frame-setup instruction is a CFI instruction.");
1078 return MI.getDebugLoc();
1083 // Gather pre-function debug information. Assumes being called immediately
1084 // after the function entry point has been emitted.
1085 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1088 // If there's no debug info for the function we're not going to do anything.
1089 if (!MMI->hasDebugInfo())
1092 auto DI = FunctionDIs.find(MF->getFunction());
1093 if (DI == FunctionDIs.end())
1096 // Grab the lexical scopes for the function, if we don't have any of those
1097 // then we're not going to be able to do anything.
1098 LScopes.initialize(*MF);
1099 if (LScopes.empty())
1102 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1104 // Make sure that each lexical scope will have a begin/end label.
1105 identifyScopeMarkers();
1107 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1108 // belongs to so that we add to the correct per-cu line table in the
1110 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1111 // FnScope->getScopeNode() and DI->second should represent the same function,
1112 // though they may not be the same MDNode due to inline functions merged in
1113 // LTO where the debug info metadata still differs (either due to distinct
1114 // written differences - two versions of a linkonce_odr function
1115 // written/copied into two separate files, or some sub-optimal metadata that
1116 // isn't structurally identical (see: file path/name info from clang, which
1117 // includes the directory of the cpp file being built, even when the file name
1118 // is absolute (such as an <> lookup header)))
1119 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1120 assert(TheCU && "Unable to find compile unit!");
1121 if (Asm->OutStreamer.hasRawTextSupport())
1122 // Use a single line table if we are generating assembly.
1123 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1125 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1127 // Calculate history for local variables.
1128 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1131 // Request labels for the full history.
1132 for (const auto &I : DbgValues) {
1133 const auto &Ranges = I.second;
1137 // The first mention of a function argument gets the CurrentFnBegin
1138 // label, so arguments are visible when breaking at function entry.
1139 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1140 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1141 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1142 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1143 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1144 // Mark all non-overlapping initial pieces.
1145 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1146 DIExpression Piece = I->first->getDebugExpression();
1147 if (std::all_of(Ranges.begin(), I,
1148 [&](DbgValueHistoryMap::InstrRange Pred) {
1149 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1151 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1158 for (const auto &Range : Ranges) {
1159 requestLabelBeforeInsn(Range.first);
1161 requestLabelAfterInsn(Range.second);
1165 PrevInstLoc = DebugLoc();
1166 PrevLabel = Asm->getFunctionBegin();
1168 // Record beginning of function.
1169 PrologEndLoc = findPrologueEndLoc(MF);
1170 if (!PrologEndLoc.isUnknown()) {
1171 DebugLoc FnStartDL =
1172 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1174 // We'd like to list the prologue as "not statements" but GDB behaves
1175 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1176 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1177 FnStartDL.getScope(MF->getFunction()->getContext()),
1178 DWARF2_FLAG_IS_STMT);
1182 // Gather and emit post-function debug information.
1183 void DwarfDebug::endFunction(const MachineFunction *MF) {
1184 assert(CurFn == MF &&
1185 "endFunction should be called with the same function as beginFunction");
1187 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1188 !FunctionDIs.count(MF->getFunction())) {
1189 // If we don't have a lexical scope for this function then there will
1190 // be a hole in the range information. Keep note of this by setting the
1191 // previously used section to nullptr.
1197 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1198 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1200 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1201 DISubprogram SP(FnScope->getScopeNode());
1202 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1204 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1205 collectVariableInfo(TheCU, SP, ProcessedVars);
1207 // Add the range of this function to the list of ranges for the CU.
1208 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1210 // Under -gmlt, skip building the subprogram if there are no inlined
1211 // subroutines inside it.
1212 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1213 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1214 assert(InfoHolder.getScopeVariables().empty());
1215 assert(DbgValues.empty());
1216 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1217 // by a -gmlt CU. Add a test and remove this assertion.
1218 assert(AbstractVariables.empty());
1219 LabelsBeforeInsn.clear();
1220 LabelsAfterInsn.clear();
1221 PrevLabel = nullptr;
1227 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1229 // Construct abstract scopes.
1230 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1231 DISubprogram SP(AScope->getScopeNode());
1232 assert(SP.isSubprogram());
1233 // Collect info for variables that were optimized out.
1234 DIArray Variables = SP.getVariables();
1235 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1236 DIVariable DV(Variables.getElement(i));
1237 assert(DV && DV.isVariable());
1238 if (!ProcessedVars.insert(DV).second)
1240 ensureAbstractVariableIsCreated(DV, DV.getContext());
1241 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1242 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1244 constructAbstractSubprogramScopeDIE(AScope);
1247 TheCU.constructSubprogramScopeDIE(FnScope);
1248 if (auto *SkelCU = TheCU.getSkeleton())
1249 if (!LScopes.getAbstractScopesList().empty())
1250 SkelCU->constructSubprogramScopeDIE(FnScope);
1253 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1254 // DbgVariables except those that are also in AbstractVariables (since they
1255 // can be used cross-function)
1256 InfoHolder.getScopeVariables().clear();
1258 LabelsBeforeInsn.clear();
1259 LabelsAfterInsn.clear();
1260 PrevLabel = nullptr;
1264 // Register a source line with debug info. Returns the unique label that was
1265 // emitted and which provides correspondence to the source line list.
1266 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1271 unsigned Discriminator = 0;
1272 if (DIScope Scope = DIScope(S)) {
1273 assert(Scope.isScope());
1274 Fn = Scope.getFilename();
1275 Dir = Scope.getDirectory();
1276 if (Scope.isLexicalBlockFile())
1277 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1279 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1280 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1281 .getOrCreateSourceID(Fn, Dir);
1283 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1287 //===----------------------------------------------------------------------===//
1289 //===----------------------------------------------------------------------===//
1291 // Emit the debug info section.
1292 void DwarfDebug::emitDebugInfo() {
1293 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1294 Holder.emitUnits(/* UseOffsets */ false);
1297 // Emit the abbreviation section.
1298 void DwarfDebug::emitAbbreviations() {
1299 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1301 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1304 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1305 StringRef TableName) {
1306 Accel.FinalizeTable(Asm, TableName);
1307 Asm->OutStreamer.SwitchSection(Section);
1309 // Emit the full data.
1310 Accel.emit(Asm, Section->getBeginSymbol(), this);
1313 // Emit visible names into a hashed accelerator table section.
1314 void DwarfDebug::emitAccelNames() {
1315 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1319 // Emit objective C classes and categories into a hashed accelerator table
1321 void DwarfDebug::emitAccelObjC() {
1322 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1326 // Emit namespace dies into a hashed accelerator table.
1327 void DwarfDebug::emitAccelNamespaces() {
1328 emitAccel(AccelNamespace,
1329 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1333 // Emit type dies into a hashed accelerator table.
1334 void DwarfDebug::emitAccelTypes() {
1335 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1339 // Public name handling.
1340 // The format for the various pubnames:
1342 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1343 // for the DIE that is named.
1345 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1346 // into the CU and the index value is computed according to the type of value
1347 // for the DIE that is named.
1349 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1350 // it's the offset within the debug_info/debug_types dwo section, however, the
1351 // reference in the pubname header doesn't change.
1353 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1354 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1356 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1358 // We could have a specification DIE that has our most of our knowledge,
1359 // look for that now.
1360 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1362 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1363 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1364 Linkage = dwarf::GIEL_EXTERNAL;
1365 } else if (Die->findAttribute(dwarf::DW_AT_external))
1366 Linkage = dwarf::GIEL_EXTERNAL;
1368 switch (Die->getTag()) {
1369 case dwarf::DW_TAG_class_type:
1370 case dwarf::DW_TAG_structure_type:
1371 case dwarf::DW_TAG_union_type:
1372 case dwarf::DW_TAG_enumeration_type:
1373 return dwarf::PubIndexEntryDescriptor(
1374 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1375 ? dwarf::GIEL_STATIC
1376 : dwarf::GIEL_EXTERNAL);
1377 case dwarf::DW_TAG_typedef:
1378 case dwarf::DW_TAG_base_type:
1379 case dwarf::DW_TAG_subrange_type:
1380 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1381 case dwarf::DW_TAG_namespace:
1382 return dwarf::GIEK_TYPE;
1383 case dwarf::DW_TAG_subprogram:
1384 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1385 case dwarf::DW_TAG_variable:
1386 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1387 case dwarf::DW_TAG_enumerator:
1388 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1389 dwarf::GIEL_STATIC);
1391 return dwarf::GIEK_NONE;
1395 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1397 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1398 const MCSection *PSec =
1399 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1400 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1402 emitDebugPubSection(GnuStyle, PSec, "Names",
1403 &DwarfCompileUnit::getGlobalNames);
1406 void DwarfDebug::emitDebugPubSection(
1407 bool GnuStyle, const MCSection *PSec, StringRef Name,
1408 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1409 for (const auto &NU : CUMap) {
1410 DwarfCompileUnit *TheU = NU.second;
1412 const auto &Globals = (TheU->*Accessor)();
1414 if (Globals.empty())
1417 if (auto *Skeleton = TheU->getSkeleton())
1420 // Start the dwarf pubnames section.
1421 Asm->OutStreamer.SwitchSection(PSec);
1424 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1425 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1426 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1427 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1429 Asm->OutStreamer.EmitLabel(BeginLabel);
1431 Asm->OutStreamer.AddComment("DWARF Version");
1432 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1434 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1435 Asm->emitSectionOffset(TheU->getLabelBegin());
1437 Asm->OutStreamer.AddComment("Compilation Unit Length");
1438 Asm->EmitInt32(TheU->getLength());
1440 // Emit the pubnames for this compilation unit.
1441 for (const auto &GI : Globals) {
1442 const char *Name = GI.getKeyData();
1443 const DIE *Entity = GI.second;
1445 Asm->OutStreamer.AddComment("DIE offset");
1446 Asm->EmitInt32(Entity->getOffset());
1449 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1450 Asm->OutStreamer.AddComment(
1451 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1452 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1453 Asm->EmitInt8(Desc.toBits());
1456 Asm->OutStreamer.AddComment("External Name");
1457 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1460 Asm->OutStreamer.AddComment("End Mark");
1462 Asm->OutStreamer.EmitLabel(EndLabel);
1466 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1467 const MCSection *PSec =
1468 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1469 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1471 emitDebugPubSection(GnuStyle, PSec, "Types",
1472 &DwarfCompileUnit::getGlobalTypes);
1475 // Emit visible names into a debug str section.
1476 void DwarfDebug::emitDebugStr() {
1477 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1478 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1482 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1483 const DebugLocEntry &Entry) {
1484 auto Comment = Entry.getComments().begin();
1485 auto End = Entry.getComments().end();
1486 for (uint8_t Byte : Entry.getDWARFBytes())
1487 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1490 static void emitDebugLocValue(const AsmPrinter &AP,
1491 const DITypeIdentifierMap &TypeIdentifierMap,
1492 ByteStreamer &Streamer,
1493 const DebugLocEntry::Value &Value,
1494 unsigned PieceOffsetInBits) {
1495 DIVariable DV = Value.getVariable();
1496 DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1497 AP.getDwarfDebug()->getDwarfVersion(),
1500 if (Value.isInt()) {
1501 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1502 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1503 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1504 DwarfExpr.AddSignedConstant(Value.getInt());
1506 DwarfExpr.AddUnsignedConstant(Value.getInt());
1507 } else if (Value.isLocation()) {
1508 MachineLocation Loc = Value.getLoc();
1509 DIExpression Expr = Value.getExpression();
1510 if (!Expr || (Expr.getNumElements() == 0))
1512 AP.EmitDwarfRegOp(Streamer, Loc);
1514 // Complex address entry.
1515 if (Loc.getOffset()) {
1516 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1517 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1519 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1523 // else ... ignore constant fp. There is not any good way to
1524 // to represent them here in dwarf.
1529 void DebugLocEntry::finalize(const AsmPrinter &AP,
1530 const DITypeIdentifierMap &TypeIdentifierMap) {
1531 BufferByteStreamer Streamer(DWARFBytes, Comments);
1532 const DebugLocEntry::Value Value = Values[0];
1533 if (Value.isBitPiece()) {
1534 // Emit all pieces that belong to the same variable and range.
1535 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1536 return P.isBitPiece();
1537 }) && "all values are expected to be pieces");
1538 assert(std::is_sorted(Values.begin(), Values.end()) &&
1539 "pieces are expected to be sorted");
1541 unsigned Offset = 0;
1542 for (auto Piece : Values) {
1543 DIExpression Expr = Piece.getExpression();
1544 unsigned PieceOffset = Expr.getBitPieceOffset();
1545 unsigned PieceSize = Expr.getBitPieceSize();
1546 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1547 if (Offset < PieceOffset) {
1548 // The DWARF spec seriously mandates pieces with no locations for gaps.
1549 DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1550 AP.getDwarfDebug()->getDwarfVersion(),
1552 Expr.AddOpPiece(PieceOffset-Offset, 0);
1553 Offset += PieceOffset-Offset;
1555 Offset += PieceSize;
1558 DIVariable Var = Piece.getVariable();
1559 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1560 assert(PieceSize+PieceOffset <= VarSize
1561 && "piece is larger than or outside of variable");
1562 assert(PieceSize != VarSize
1563 && "piece covers entire variable");
1565 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1568 assert(Values.size() == 1 && "only pieces may have >1 value");
1569 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1574 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1575 Asm->OutStreamer.AddComment("Loc expr size");
1576 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1577 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1578 Asm->EmitLabelDifference(end, begin, 2);
1579 Asm->OutStreamer.EmitLabel(begin);
1581 APByteStreamer Streamer(*Asm);
1582 emitDebugLocEntry(Streamer, Entry);
1584 Asm->OutStreamer.EmitLabel(end);
1587 // Emit locations into the debug loc section.
1588 void DwarfDebug::emitDebugLoc() {
1589 // Start the dwarf loc section.
1590 Asm->OutStreamer.SwitchSection(
1591 Asm->getObjFileLowering().getDwarfLocSection());
1592 unsigned char Size = Asm->getDataLayout().getPointerSize();
1593 for (const auto &DebugLoc : DotDebugLocEntries) {
1594 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1595 const DwarfCompileUnit *CU = DebugLoc.CU;
1596 for (const auto &Entry : DebugLoc.List) {
1597 // Set up the range. This range is relative to the entry point of the
1598 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1599 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1600 if (auto *Base = CU->getBaseAddress()) {
1601 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1602 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1604 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1605 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1608 emitDebugLocEntryLocation(Entry);
1610 Asm->OutStreamer.EmitIntValue(0, Size);
1611 Asm->OutStreamer.EmitIntValue(0, Size);
1615 void DwarfDebug::emitDebugLocDWO() {
1616 Asm->OutStreamer.SwitchSection(
1617 Asm->getObjFileLowering().getDwarfLocDWOSection());
1618 for (const auto &DebugLoc : DotDebugLocEntries) {
1619 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1620 for (const auto &Entry : DebugLoc.List) {
1621 // Just always use start_length for now - at least that's one address
1622 // rather than two. We could get fancier and try to, say, reuse an
1623 // address we know we've emitted elsewhere (the start of the function?
1624 // The start of the CU or CU subrange that encloses this range?)
1625 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1626 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1627 Asm->EmitULEB128(idx);
1628 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1630 emitDebugLocEntryLocation(Entry);
1632 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1637 const MCSymbol *Start, *End;
1640 // Emit a debug aranges section, containing a CU lookup for any
1641 // address we can tie back to a CU.
1642 void DwarfDebug::emitDebugARanges() {
1643 // Provides a unique id per text section.
1644 MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1646 // Filter labels by section.
1647 for (const SymbolCU &SCU : ArangeLabels) {
1648 if (SCU.Sym->isInSection()) {
1649 // Make a note of this symbol and it's section.
1650 const MCSection *Section = &SCU.Sym->getSection();
1651 if (!Section->getKind().isMetadata())
1652 SectionMap[Section].push_back(SCU);
1654 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1655 // appear in the output. This sucks as we rely on sections to build
1656 // arange spans. We can do it without, but it's icky.
1657 SectionMap[nullptr].push_back(SCU);
1661 // Add terminating symbols for each section.
1662 for (const auto &I : SectionMap) {
1663 const MCSection *Section = I.first;
1664 MCSymbol *Sym = nullptr;
1667 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1668 // if we know the section name up-front. For user-created sections, the
1669 // resulting label may not be valid to use as a label. (section names can
1670 // use a greater set of characters on some systems)
1671 Sym = Asm->createTempSymbol("debug_end");
1672 Asm->OutStreamer.SwitchSection(Section);
1673 Asm->OutStreamer.EmitLabel(Sym);
1676 // Insert a final terminator.
1677 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1680 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1682 for (auto &I : SectionMap) {
1683 const MCSection *Section = I.first;
1684 SmallVector<SymbolCU, 8> &List = I.second;
1685 if (List.size() < 2)
1688 // If we have no section (e.g. common), just write out
1689 // individual spans for each symbol.
1691 for (const SymbolCU &Cur : List) {
1693 Span.Start = Cur.Sym;
1696 Spans[Cur.CU].push_back(Span);
1701 // Sort the symbols by offset within the section.
1702 std::sort(List.begin(), List.end(),
1703 [&](const SymbolCU &A, const SymbolCU &B) {
1704 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1705 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1707 // Symbols with no order assigned should be placed at the end.
1708 // (e.g. section end labels)
1716 // Build spans between each label.
1717 const MCSymbol *StartSym = List[0].Sym;
1718 for (size_t n = 1, e = List.size(); n < e; n++) {
1719 const SymbolCU &Prev = List[n - 1];
1720 const SymbolCU &Cur = List[n];
1722 // Try and build the longest span we can within the same CU.
1723 if (Cur.CU != Prev.CU) {
1725 Span.Start = StartSym;
1727 Spans[Prev.CU].push_back(Span);
1733 // Start the dwarf aranges section.
1734 Asm->OutStreamer.SwitchSection(
1735 Asm->getObjFileLowering().getDwarfARangesSection());
1737 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1739 // Build a list of CUs used.
1740 std::vector<DwarfCompileUnit *> CUs;
1741 for (const auto &it : Spans) {
1742 DwarfCompileUnit *CU = it.first;
1746 // Sort the CU list (again, to ensure consistent output order).
1747 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1748 return A->getUniqueID() < B->getUniqueID();
1751 // Emit an arange table for each CU we used.
1752 for (DwarfCompileUnit *CU : CUs) {
1753 std::vector<ArangeSpan> &List = Spans[CU];
1755 // Describe the skeleton CU's offset and length, not the dwo file's.
1756 if (auto *Skel = CU->getSkeleton())
1759 // Emit size of content not including length itself.
1760 unsigned ContentSize =
1761 sizeof(int16_t) + // DWARF ARange version number
1762 sizeof(int32_t) + // Offset of CU in the .debug_info section
1763 sizeof(int8_t) + // Pointer Size (in bytes)
1764 sizeof(int8_t); // Segment Size (in bytes)
1766 unsigned TupleSize = PtrSize * 2;
1768 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1770 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1772 ContentSize += Padding;
1773 ContentSize += (List.size() + 1) * TupleSize;
1775 // For each compile unit, write the list of spans it covers.
1776 Asm->OutStreamer.AddComment("Length of ARange Set");
1777 Asm->EmitInt32(ContentSize);
1778 Asm->OutStreamer.AddComment("DWARF Arange version number");
1779 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1780 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1781 Asm->emitSectionOffset(CU->getLabelBegin());
1782 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1783 Asm->EmitInt8(PtrSize);
1784 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1787 Asm->OutStreamer.EmitFill(Padding, 0xff);
1789 for (const ArangeSpan &Span : List) {
1790 Asm->EmitLabelReference(Span.Start, PtrSize);
1792 // Calculate the size as being from the span start to it's end.
1794 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1796 // For symbols without an end marker (e.g. common), we
1797 // write a single arange entry containing just that one symbol.
1798 uint64_t Size = SymSize[Span.Start];
1802 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1806 Asm->OutStreamer.AddComment("ARange terminator");
1807 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1808 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1812 // Emit visible names into a debug ranges section.
1813 void DwarfDebug::emitDebugRanges() {
1814 // Start the dwarf ranges section.
1815 Asm->OutStreamer.SwitchSection(
1816 Asm->getObjFileLowering().getDwarfRangesSection());
1818 // Size for our labels.
1819 unsigned char Size = Asm->getDataLayout().getPointerSize();
1821 // Grab the specific ranges for the compile units in the module.
1822 for (const auto &I : CUMap) {
1823 DwarfCompileUnit *TheCU = I.second;
1825 if (auto *Skel = TheCU->getSkeleton())
1828 // Iterate over the misc ranges for the compile units in the module.
1829 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1830 // Emit our symbol so we can find the beginning of the range.
1831 Asm->OutStreamer.EmitLabel(List.getSym());
1833 for (const RangeSpan &Range : List.getRanges()) {
1834 const MCSymbol *Begin = Range.getStart();
1835 const MCSymbol *End = Range.getEnd();
1836 assert(Begin && "Range without a begin symbol?");
1837 assert(End && "Range without an end symbol?");
1838 if (auto *Base = TheCU->getBaseAddress()) {
1839 Asm->EmitLabelDifference(Begin, Base, Size);
1840 Asm->EmitLabelDifference(End, Base, Size);
1842 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1843 Asm->OutStreamer.EmitSymbolValue(End, Size);
1847 // And terminate the list with two 0 values.
1848 Asm->OutStreamer.EmitIntValue(0, Size);
1849 Asm->OutStreamer.EmitIntValue(0, Size);
1854 // DWARF5 Experimental Separate Dwarf emitters.
1856 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1857 std::unique_ptr<DwarfUnit> NewU) {
1858 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1859 U.getCUNode().getSplitDebugFilename());
1861 if (!CompilationDir.empty())
1862 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1864 addGnuPubAttributes(*NewU, Die);
1866 SkeletonHolder.addUnit(std::move(NewU));
1869 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1870 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1871 // DW_AT_addr_base, DW_AT_ranges_base.
1872 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1874 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1875 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1876 DwarfCompileUnit &NewCU = *OwnedUnit;
1877 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1879 NewCU.initStmtList();
1881 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1886 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1887 // compile units that would normally be in debug_info.
1888 void DwarfDebug::emitDebugInfoDWO() {
1889 assert(useSplitDwarf() && "No split dwarf debug info?");
1890 // Don't emit relocations into the dwo file.
1891 InfoHolder.emitUnits(/* UseOffsets */ true);
1894 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1895 // abbreviations for the .debug_info.dwo section.
1896 void DwarfDebug::emitDebugAbbrevDWO() {
1897 assert(useSplitDwarf() && "No split dwarf?");
1898 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1901 void DwarfDebug::emitDebugLineDWO() {
1902 assert(useSplitDwarf() && "No split dwarf?");
1903 Asm->OutStreamer.SwitchSection(
1904 Asm->getObjFileLowering().getDwarfLineDWOSection());
1905 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
1908 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1909 // string section and is identical in format to traditional .debug_str
1911 void DwarfDebug::emitDebugStrDWO() {
1912 assert(useSplitDwarf() && "No split dwarf?");
1913 const MCSection *OffSec =
1914 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1915 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1919 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1920 if (!useSplitDwarf())
1923 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
1924 return &SplitTypeUnitFileTable;
1927 static uint64_t makeTypeSignature(StringRef Identifier) {
1929 Hash.update(Identifier);
1930 // ... take the least significant 8 bytes and return those. Our MD5
1931 // implementation always returns its results in little endian, swap bytes
1933 MD5::MD5Result Result;
1935 return support::endian::read64le(Result + 8);
1938 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1939 StringRef Identifier, DIE &RefDie,
1940 DICompositeType CTy) {
1941 // Fast path if we're building some type units and one has already used the
1942 // address pool we know we're going to throw away all this work anyway, so
1943 // don't bother building dependent types.
1944 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1947 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
1949 CU.addDIETypeSignature(RefDie, *TU);
1953 bool TopLevelType = TypeUnitsUnderConstruction.empty();
1954 AddrPool.resetUsedFlag();
1956 auto OwnedUnit = make_unique<DwarfTypeUnit>(
1957 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
1958 this, &InfoHolder, getDwoLineTable(CU));
1959 DwarfTypeUnit &NewTU = *OwnedUnit;
1960 DIE &UnitDie = NewTU.getUnitDie();
1962 TypeUnitsUnderConstruction.push_back(
1963 std::make_pair(std::move(OwnedUnit), CTy));
1965 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1968 uint64_t Signature = makeTypeSignature(Identifier);
1969 NewTU.setTypeSignature(Signature);
1971 if (useSplitDwarf())
1972 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1974 CU.applyStmtList(UnitDie);
1976 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1979 NewTU.setType(NewTU.createTypeDIE(CTy));
1982 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1983 TypeUnitsUnderConstruction.clear();
1985 // Types referencing entries in the address table cannot be placed in type
1987 if (AddrPool.hasBeenUsed()) {
1989 // Remove all the types built while building this type.
1990 // This is pessimistic as some of these types might not be dependent on
1991 // the type that used an address.
1992 for (const auto &TU : TypeUnitsToAdd)
1993 DwarfTypeUnits.erase(TU.second);
1995 // Construct this type in the CU directly.
1996 // This is inefficient because all the dependent types will be rebuilt
1997 // from scratch, including building them in type units, discovering that
1998 // they depend on addresses, throwing them out and rebuilding them.
1999 CU.constructTypeDIE(RefDie, CTy);
2003 // If the type wasn't dependent on fission addresses, finish adding the type
2004 // and all its dependent types.
2005 for (auto &TU : TypeUnitsToAdd)
2006 InfoHolder.addUnit(std::move(TU.first));
2008 CU.addDIETypeSignature(RefDie, NewTU);
2011 // Accelerator table mutators - add each name along with its companion
2012 // DIE to the proper table while ensuring that the name that we're going
2013 // to reference is in the string table. We do this since the names we
2014 // add may not only be identical to the names in the DIE.
2015 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2016 if (!useDwarfAccelTables())
2018 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2022 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2023 if (!useDwarfAccelTables())
2025 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2029 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2030 if (!useDwarfAccelTables())
2032 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2036 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2037 if (!useDwarfAccelTables())
2039 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),