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.isVariable() && "Invalid complex DbgVariable!");
138 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
141 DIType DbgVariable::getType() const {
142 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
143 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
144 // addresses instead.
145 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
146 /* Byref variables, in Blocks, are declared by the programmer as
147 "SomeType VarName;", but the compiler creates a
148 __Block_byref_x_VarName struct, and gives the variable VarName
149 either the struct, or a pointer to the struct, as its type. This
150 is necessary for various behind-the-scenes things the compiler
151 needs to do with by-reference variables in blocks.
153 However, as far as the original *programmer* is concerned, the
154 variable should still have type 'SomeType', as originally declared.
156 The following function dives into the __Block_byref_x_VarName
157 struct to find the original type of the variable. This will be
158 passed back to the code generating the type for the Debug
159 Information Entry for the variable 'VarName'. 'VarName' will then
160 have the original type 'SomeType' in its debug information.
162 The original type 'SomeType' will be the type of the field named
163 'VarName' inside the __Block_byref_x_VarName struct.
165 NOTE: In order for this to not completely fail on the debugger
166 side, the Debug Information Entry for the variable VarName needs to
167 have a DW_AT_location that tells the debugger how to unwind through
168 the pointers and __Block_byref_x_VarName struct to find the actual
169 value of the variable. The function addBlockByrefType does this. */
171 uint16_t tag = Ty.getTag();
173 if (tag == dwarf::DW_TAG_pointer_type)
174 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
176 DIArray Elements = DICompositeType(subType).getElements();
177 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
178 DIDerivedType DT(Elements.getElement(i));
179 if (getName() == DT.getName())
180 return (resolve(DT.getTypeDerivedFrom()));
186 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
187 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
188 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
189 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
191 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
192 : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr),
193 InfoHolder(A, "info_string", DIEValueAllocator),
194 UsedNonDefaultText(false),
195 SkeletonHolder(A, "skel_string", DIEValueAllocator),
196 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
197 IsPS4(Triple(A->getTargetTriple()).isPS4()),
198 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
199 dwarf::DW_FORM_data4)),
200 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
201 dwarf::DW_FORM_data4)),
202 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
203 dwarf::DW_FORM_data4)),
204 AccelTypes(TypeAtoms) {
209 // Turn on accelerator tables for Darwin by default, pubnames by
210 // default for non-Darwin/PS4, and handle split dwarf.
211 if (DwarfAccelTables == Default)
212 HasDwarfAccelTables = IsDarwin;
214 HasDwarfAccelTables = DwarfAccelTables == Enable;
216 if (SplitDwarf == Default)
217 HasSplitDwarf = false;
219 HasSplitDwarf = SplitDwarf == Enable;
221 if (DwarfPubSections == Default)
222 HasDwarfPubSections = !IsDarwin && !IsPS4;
224 HasDwarfPubSections = DwarfPubSections == Enable;
226 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
227 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
228 : MMI->getModule()->getDwarfVersion();
230 // Darwin and PS4 use the standard TLS opcode (defined in DWARF 3).
231 // Everybody else uses GNU's.
232 UseGNUTLSOpcode = !(IsDarwin || IsPS4) || DwarfVersion < 3;
234 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
237 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
242 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
243 DwarfDebug::~DwarfDebug() { }
245 static bool isObjCClass(StringRef Name) {
246 return Name.startswith("+") || Name.startswith("-");
249 static bool hasObjCCategory(StringRef Name) {
250 if (!isObjCClass(Name))
253 return Name.find(") ") != StringRef::npos;
256 static void getObjCClassCategory(StringRef In, StringRef &Class,
257 StringRef &Category) {
258 if (!hasObjCCategory(In)) {
259 Class = In.slice(In.find('[') + 1, In.find(' '));
264 Class = In.slice(In.find('[') + 1, In.find('('));
265 Category = In.slice(In.find('[') + 1, In.find(' '));
269 static StringRef getObjCMethodName(StringRef In) {
270 return In.slice(In.find(' ') + 1, In.find(']'));
273 // Add the various names to the Dwarf accelerator table names.
274 // TODO: Determine whether or not we should add names for programs
275 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
276 // is only slightly different than the lookup of non-standard ObjC names.
277 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
278 if (!SP.isDefinition())
280 addAccelName(SP.getName(), Die);
282 // If the linkage name is different than the name, go ahead and output
283 // that as well into the name table.
284 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
285 addAccelName(SP.getLinkageName(), Die);
287 // If this is an Objective-C selector name add it to the ObjC accelerator
289 if (isObjCClass(SP.getName())) {
290 StringRef Class, Category;
291 getObjCClassCategory(SP.getName(), Class, Category);
292 addAccelObjC(Class, Die);
294 addAccelObjC(Category, Die);
295 // Also add the base method name to the name table.
296 addAccelName(getObjCMethodName(SP.getName()), Die);
300 /// isSubprogramContext - Return true if Context is either a subprogram
301 /// or another context nested inside a subprogram.
302 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
305 DIDescriptor D(Context);
306 if (D.isSubprogram())
309 return isSubprogramContext(resolve(DIType(Context).getContext()));
313 /// Check whether we should create a DIE for the given Scope, return true
314 /// if we don't create a DIE (the corresponding DIE is null).
315 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
316 if (Scope->isAbstractScope())
319 // We don't create a DIE if there is no Range.
320 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
324 if (Ranges.size() > 1)
327 // We don't create a DIE if we have a single Range and the end label
329 return !getLabelAfterInsn(Ranges.front().second);
332 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
334 if (auto *SkelCU = CU.getSkeleton())
338 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
339 assert(Scope && Scope->getScopeNode());
340 assert(Scope->isAbstractScope());
341 assert(!Scope->getInlinedAt());
343 const MDNode *SP = Scope->getScopeNode();
345 ProcessedSPNodes.insert(SP);
347 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
348 // was inlined from another compile unit.
349 auto &CU = SPMap[SP];
350 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
351 CU.constructAbstractSubprogramScopeDIE(Scope);
355 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
356 if (!GenerateGnuPubSections)
359 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
362 // Create new DwarfCompileUnit for the given metadata node with tag
363 // DW_TAG_compile_unit.
364 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
365 StringRef FN = DIUnit.getFilename();
366 CompilationDir = DIUnit.getDirectory();
368 auto OwnedUnit = make_unique<DwarfCompileUnit>(
369 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
370 DwarfCompileUnit &NewCU = *OwnedUnit;
371 DIE &Die = NewCU.getUnitDie();
372 InfoHolder.addUnit(std::move(OwnedUnit));
374 NewCU.setSkeleton(constructSkeletonCU(NewCU));
376 // LTO with assembly output shares a single line table amongst multiple CUs.
377 // To avoid the compilation directory being ambiguous, let the line table
378 // explicitly describe the directory of all files, never relying on the
379 // compilation directory.
380 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
381 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
382 NewCU.getUniqueID(), CompilationDir);
384 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
385 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
386 DIUnit.getLanguage());
387 NewCU.addString(Die, dwarf::DW_AT_name, FN);
389 if (!useSplitDwarf()) {
390 NewCU.initStmtList();
392 // If we're using split dwarf the compilation dir is going to be in the
393 // skeleton CU and so we don't need to duplicate it here.
394 if (!CompilationDir.empty())
395 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
397 addGnuPubAttributes(NewCU, Die);
400 if (DIUnit.isOptimized())
401 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
403 StringRef Flags = DIUnit.getFlags();
405 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
407 if (unsigned RVer = DIUnit.getRunTimeVersion())
408 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
409 dwarf::DW_FORM_data1, RVer);
412 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
414 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
416 CUMap.insert(std::make_pair(DIUnit, &NewCU));
417 CUDieMap.insert(std::make_pair(&Die, &NewCU));
421 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
423 DIImportedEntity Module(N);
424 assert(Module.Verify());
425 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
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(N);
449 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
450 DIArray ImportedEntities = CUNode.getImportedEntities();
451 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
452 ScopesWithImportedEntities.push_back(std::make_pair(
453 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
454 ImportedEntities.getElement(i)));
455 // Stable sort to preserve the order of appearance of imported entities.
456 // This is to avoid out-of-order processing of interdependent declarations
457 // within the same scope, e.g. { namespace A = base; namespace B = A; }
458 std::stable_sort(ScopesWithImportedEntities.begin(),
459 ScopesWithImportedEntities.end(), less_first());
460 DIArray GVs = CUNode.getGlobalVariables();
461 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
462 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
463 DIArray SPs = CUNode.getSubprograms();
464 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
465 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
466 DIArray EnumTypes = CUNode.getEnumTypes();
467 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
468 DIType Ty(EnumTypes.getElement(i));
469 // The enum types array by design contains pointers to
470 // MDNodes rather than DIRefs. Unique them here.
471 DIType UniqueTy(resolve(Ty.getRef()));
472 CU.getOrCreateTypeDIE(UniqueTy);
474 DIArray RetainedTypes = CUNode.getRetainedTypes();
475 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
476 DIType Ty(RetainedTypes.getElement(i));
477 // The retained types array by design contains pointers to
478 // MDNodes rather than DIRefs. Unique them here.
479 DIType UniqueTy(resolve(Ty.getRef()));
480 CU.getOrCreateTypeDIE(UniqueTy);
482 // Emit imported_modules last so that the relevant context is already
484 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
485 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
488 // Tell MMI that we have debug info.
489 MMI->setDebugInfoAvailability(true);
492 void DwarfDebug::finishVariableDefinitions() {
493 for (const auto &Var : ConcreteVariables) {
494 DIE *VariableDie = Var->getDIE();
496 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
497 // in the ConcreteVariables list, rather than looking it up again here.
498 // DIE::getUnit isn't simple - it walks parent pointers, etc.
499 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
501 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
502 if (AbsVar && AbsVar->getDIE()) {
503 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
506 Unit->applyVariableAttributes(*Var, *VariableDie);
510 void DwarfDebug::finishSubprogramDefinitions() {
511 for (const auto &P : SPMap)
512 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
513 CU.finishSubprogramDefinition(DISubprogram(P.first));
518 // Collect info for variables that were optimized out.
519 void DwarfDebug::collectDeadVariables() {
520 const Module *M = MMI->getModule();
522 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
523 for (MDNode *N : CU_Nodes->operands()) {
524 DICompileUnit TheCU(N);
525 // Construct subprogram DIE and add variables DIEs.
526 DwarfCompileUnit *SPCU =
527 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
528 assert(SPCU && "Unable to find Compile Unit!");
529 DIArray Subprograms = TheCU.getSubprograms();
530 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
531 DISubprogram SP(Subprograms.getElement(i));
532 if (ProcessedSPNodes.count(SP) != 0)
534 SPCU->collectDeadVariables(SP);
540 void DwarfDebug::finalizeModuleInfo() {
541 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
543 finishSubprogramDefinitions();
545 finishVariableDefinitions();
547 // Collect info for variables that were optimized out.
548 collectDeadVariables();
550 // Handle anything that needs to be done on a per-unit basis after
551 // all other generation.
552 for (const auto &P : CUMap) {
553 auto &TheCU = *P.second;
554 // Emit DW_AT_containing_type attribute to connect types with their
555 // vtable holding type.
556 TheCU.constructContainingTypeDIEs();
558 // Add CU specific attributes if we need to add any.
559 // If we're splitting the dwarf out now that we've got the entire
560 // CU then add the dwo id to it.
561 auto *SkCU = TheCU.getSkeleton();
562 if (useSplitDwarf()) {
563 // Emit a unique identifier for this CU.
564 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
565 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
566 dwarf::DW_FORM_data8, ID);
567 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
568 dwarf::DW_FORM_data8, ID);
570 // We don't keep track of which addresses are used in which CU so this
571 // is a bit pessimistic under LTO.
572 if (!AddrPool.isEmpty()) {
573 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
574 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
577 if (!SkCU->getRangeLists().empty()) {
578 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
579 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
584 // If we have code split among multiple sections or non-contiguous
585 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
586 // remain in the .o file, otherwise add a DW_AT_low_pc.
587 // FIXME: We should use ranges allow reordering of code ala
588 // .subsections_via_symbols in mach-o. This would mean turning on
589 // ranges for all subprogram DIEs for mach-o.
590 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
591 if (unsigned NumRanges = TheCU.getRanges().size()) {
593 // A DW_AT_low_pc attribute may also be specified in combination with
594 // DW_AT_ranges to specify the default base address for use in
595 // location lists (see Section 2.6.2) and range lists (see Section
597 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
599 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
600 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
604 // Compute DIE offsets and sizes.
605 InfoHolder.computeSizeAndOffsets();
607 SkeletonHolder.computeSizeAndOffsets();
610 // Emit all Dwarf sections that should come after the content.
611 void DwarfDebug::endModule() {
612 assert(CurFn == nullptr);
613 assert(CurMI == nullptr);
615 // If we aren't actually generating debug info (check beginModule -
616 // conditionalized on !DisableDebugInfoPrinting and the presence of the
617 // llvm.dbg.cu metadata node)
618 if (!MMI->hasDebugInfo())
621 // Finalize the debug info for the module.
622 finalizeModuleInfo();
629 // Emit info into a debug loc section.
632 // Corresponding abbreviations into a abbrev section.
635 // Emit all the DIEs into a debug info section.
638 // Emit info into a debug aranges section.
639 if (GenerateARangeSection)
642 // Emit info into a debug ranges section.
645 if (useSplitDwarf()) {
648 emitDebugAbbrevDWO();
650 // Emit DWO addresses.
651 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
654 // Emit info into the dwarf accelerator table sections.
655 if (useDwarfAccelTables()) {
658 emitAccelNamespaces();
662 // Emit the pubnames and pubtypes sections if requested.
663 if (HasDwarfPubSections) {
664 emitDebugPubNames(GenerateGnuPubSections);
665 emitDebugPubTypes(GenerateGnuPubSections);
670 AbstractVariables.clear();
673 // Find abstract variable, if any, associated with Var.
674 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
675 DIVariable &Cleansed) {
676 LLVMContext &Ctx = DV->getContext();
677 // More then one inlined variable corresponds to one abstract variable.
678 // FIXME: This duplication of variables when inlining should probably be
679 // removed. It's done to allow each DIVariable to describe its location
680 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
681 // make it accurate then remove this duplication/cleansing stuff.
682 Cleansed = cleanseInlinedVariable(DV, Ctx);
683 auto I = AbstractVariables.find(Cleansed);
684 if (I != AbstractVariables.end())
685 return I->second.get();
689 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
691 return getExistingAbstractVariable(DV, Cleansed);
694 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
695 LexicalScope *Scope) {
696 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
697 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
698 AbstractVariables[Var] = std::move(AbsDbgVariable);
701 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
702 const MDNode *ScopeNode) {
703 DIVariable Cleansed = DV;
704 if (getExistingAbstractVariable(DV, Cleansed))
707 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
708 cast<MDLocalScope>(ScopeNode)));
712 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
713 const MDNode *ScopeNode) {
714 DIVariable Cleansed = DV;
715 if (getExistingAbstractVariable(DV, Cleansed))
718 if (LexicalScope *Scope =
719 LScopes.findAbstractScope(cast_or_null<MDLocalScope>(ScopeNode)))
720 createAbstractVariable(Cleansed, Scope);
723 // Collect variable information from side table maintained by MMI.
724 void DwarfDebug::collectVariableInfoFromMMITable(
725 SmallPtrSetImpl<const MDNode *> &Processed) {
726 for (const auto &VI : MMI->getVariableDbgInfo()) {
729 Processed.insert(VI.Var);
730 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
732 // If variable scope is not found then skip this variable.
736 DIVariable DV(VI.Var);
737 DIExpression Expr(VI.Expr);
738 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
739 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
740 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
741 ConcreteVariables.push_back(std::move(RegVar));
745 // Get .debug_loc entry for the instruction range starting at MI.
746 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
747 const MDNode *Expr = MI->getDebugExpression();
748 const MDNode *Var = MI->getDebugVariable();
750 assert(MI->getNumOperands() == 4);
751 if (MI->getOperand(0).isReg()) {
752 MachineLocation MLoc;
753 // If the second operand is an immediate, this is a
754 // register-indirect address.
755 if (!MI->getOperand(1).isImm())
756 MLoc.set(MI->getOperand(0).getReg());
758 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
759 return DebugLocEntry::Value(Var, Expr, MLoc);
761 if (MI->getOperand(0).isImm())
762 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
763 if (MI->getOperand(0).isFPImm())
764 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
765 if (MI->getOperand(0).isCImm())
766 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
768 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
771 /// Determine whether two variable pieces overlap.
772 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
773 if (!P1.isBitPiece() || !P2.isBitPiece())
775 unsigned l1 = P1.getBitPieceOffset();
776 unsigned l2 = P2.getBitPieceOffset();
777 unsigned r1 = l1 + P1.getBitPieceSize();
778 unsigned r2 = l2 + P2.getBitPieceSize();
779 // True where [l1,r1[ and [r1,r2[ overlap.
780 return (l1 < r2) && (l2 < r1);
783 /// Build the location list for all DBG_VALUEs in the function that
784 /// describe the same variable. If the ranges of several independent
785 /// pieces of the same variable overlap partially, split them up and
786 /// combine the ranges. The resulting DebugLocEntries are will have
787 /// strict monotonically increasing begin addresses and will never
792 // Ranges History [var, loc, piece ofs size]
793 // 0 | [x, (reg0, piece 0, 32)]
794 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
796 // 3 | [clobber reg0]
797 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
802 // [0-1] [x, (reg0, piece 0, 32)]
803 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
804 // [3-4] [x, (reg1, piece 32, 32)]
805 // [4- ] [x, (mem, piece 0, 64)]
807 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
808 const DbgValueHistoryMap::InstrRanges &Ranges) {
809 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
811 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
812 const MachineInstr *Begin = I->first;
813 const MachineInstr *End = I->second;
814 assert(Begin->isDebugValue() && "Invalid History entry");
816 // Check if a variable is inaccessible in this range.
817 if (Begin->getNumOperands() > 1 &&
818 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
823 // If this piece overlaps with any open ranges, truncate them.
824 DIExpression DIExpr = Begin->getDebugExpression();
825 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
826 [&](DebugLocEntry::Value R) {
827 return piecesOverlap(DIExpr, R.getExpression());
829 OpenRanges.erase(Last, OpenRanges.end());
831 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
832 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
834 const MCSymbol *EndLabel;
836 EndLabel = getLabelAfterInsn(End);
837 else if (std::next(I) == Ranges.end())
838 EndLabel = Asm->getFunctionEnd();
840 EndLabel = getLabelBeforeInsn(std::next(I)->first);
841 assert(EndLabel && "Forgot label after instruction ending a range!");
843 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
845 auto Value = getDebugLocValue(Begin);
846 DebugLocEntry Loc(StartLabel, EndLabel, Value);
847 bool couldMerge = false;
849 // If this is a piece, it may belong to the current DebugLocEntry.
850 if (DIExpr.isBitPiece()) {
851 // Add this value to the list of open ranges.
852 OpenRanges.push_back(Value);
854 // Attempt to add the piece to the last entry.
855 if (!DebugLoc.empty())
856 if (DebugLoc.back().MergeValues(Loc))
861 // Need to add a new DebugLocEntry. Add all values from still
862 // valid non-overlapping pieces.
863 if (OpenRanges.size())
864 Loc.addValues(OpenRanges);
866 DebugLoc.push_back(std::move(Loc));
869 // Attempt to coalesce the ranges of two otherwise identical
871 auto CurEntry = DebugLoc.rbegin();
872 auto PrevEntry = std::next(CurEntry);
873 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
877 dbgs() << CurEntry->getValues().size() << " Values:\n";
878 for (auto Value : CurEntry->getValues()) {
879 Value.getVariable()->dump();
880 Value.getExpression()->dump();
888 // Find variables for each lexical scope.
890 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
891 SmallPtrSetImpl<const MDNode *> &Processed) {
892 // Grab the variable info that was squirreled away in the MMI side-table.
893 collectVariableInfoFromMMITable(Processed);
895 for (const auto &I : DbgValues) {
896 DIVariable DV(I.first);
897 if (Processed.count(DV))
900 // Instruction ranges, specifying where DV is accessible.
901 const auto &Ranges = I.second;
905 LexicalScope *Scope = nullptr;
906 if (MDLocation *IA = DV.get()->getInlinedAt())
907 Scope = LScopes.findInlinedScope(DV.get()->getScope(), IA);
909 Scope = LScopes.findLexicalScope(DV.get()->getScope());
910 // If variable scope is not found then skip this variable.
914 Processed.insert(DV);
915 const MachineInstr *MInsn = Ranges.front().first;
916 assert(MInsn->isDebugValue() && "History must begin with debug value");
917 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
918 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
919 DbgVariable *RegVar = ConcreteVariables.back().get();
920 InfoHolder.addScopeVariable(Scope, RegVar);
922 // Check if the first DBG_VALUE is valid for the rest of the function.
923 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
926 // Handle multiple DBG_VALUE instructions describing one variable.
927 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
929 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
930 DebugLocList &LocList = DotDebugLocEntries.back();
932 LocList.Label = Asm->createTempSymbol("debug_loc");
934 // Build the location list for this variable.
935 buildLocationList(LocList.List, Ranges);
936 // Finalize the entry by lowering it into a DWARF bytestream.
937 for (auto &Entry : LocList.List)
938 Entry.finalize(*Asm, TypeIdentifierMap);
941 // Collect info for variables that were optimized out.
942 DIArray Variables = SP.getVariables();
943 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
944 DIVariable DV(Variables.getElement(i));
945 assert(DV.isVariable());
946 if (!Processed.insert(DV).second)
948 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.get()->getScope())) {
949 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
951 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
952 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
957 // Return Label preceding the instruction.
958 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
959 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
960 assert(Label && "Didn't insert label before instruction");
964 // Return Label immediately following the instruction.
965 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
966 return LabelsAfterInsn.lookup(MI);
969 // Process beginning of an instruction.
970 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
971 assert(CurMI == nullptr);
973 // Check if source location changes, but ignore DBG_VALUE locations.
974 if (!MI->isDebugValue()) {
975 DebugLoc DL = MI->getDebugLoc();
976 if (DL != PrevInstLoc) {
980 if (DL == PrologEndLoc) {
981 Flags |= DWARF2_FLAG_PROLOGUE_END;
982 PrologEndLoc = DebugLoc();
983 Flags |= DWARF2_FLAG_IS_STMT;
986 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
987 Flags |= DWARF2_FLAG_IS_STMT;
989 const MDNode *Scope = DL.getScope();
990 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
991 } else if (UnknownLocations) {
993 recordSourceLine(0, 0, nullptr, 0);
998 // Insert labels where requested.
999 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1000 LabelsBeforeInsn.find(MI);
1003 if (I == LabelsBeforeInsn.end())
1006 // Label already assigned.
1011 PrevLabel = MMI->getContext().CreateTempSymbol();
1012 Asm->OutStreamer.EmitLabel(PrevLabel);
1014 I->second = PrevLabel;
1017 // Process end of an instruction.
1018 void DwarfDebug::endInstruction() {
1019 assert(CurMI != nullptr);
1020 // Don't create a new label after DBG_VALUE instructions.
1021 // They don't generate code.
1022 if (!CurMI->isDebugValue())
1023 PrevLabel = nullptr;
1025 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1026 LabelsAfterInsn.find(CurMI);
1030 if (I == LabelsAfterInsn.end())
1033 // Label already assigned.
1037 // We need a label after this instruction.
1039 PrevLabel = MMI->getContext().CreateTempSymbol();
1040 Asm->OutStreamer.EmitLabel(PrevLabel);
1042 I->second = PrevLabel;
1045 // Each LexicalScope has first instruction and last instruction to mark
1046 // beginning and end of a scope respectively. Create an inverse map that list
1047 // scopes starts (and ends) with an instruction. One instruction may start (or
1048 // end) multiple scopes. Ignore scopes that are not reachable.
1049 void DwarfDebug::identifyScopeMarkers() {
1050 SmallVector<LexicalScope *, 4> WorkList;
1051 WorkList.push_back(LScopes.getCurrentFunctionScope());
1052 while (!WorkList.empty()) {
1053 LexicalScope *S = WorkList.pop_back_val();
1055 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1056 if (!Children.empty())
1057 WorkList.append(Children.begin(), Children.end());
1059 if (S->isAbstractScope())
1062 for (const InsnRange &R : S->getRanges()) {
1063 assert(R.first && "InsnRange does not have first instruction!");
1064 assert(R.second && "InsnRange does not have second instruction!");
1065 requestLabelBeforeInsn(R.first);
1066 requestLabelAfterInsn(R.second);
1071 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1072 // First known non-DBG_VALUE and non-frame setup location marks
1073 // the beginning of the function body.
1074 for (const auto &MBB : *MF)
1075 for (const auto &MI : MBB)
1076 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1078 // Did the target forget to set the FrameSetup flag for CFI insns?
1079 assert(!MI.isCFIInstruction() &&
1080 "First non-frame-setup instruction is a CFI instruction.");
1081 return MI.getDebugLoc();
1086 // Gather pre-function debug information. Assumes being called immediately
1087 // after the function entry point has been emitted.
1088 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1091 // If there's no debug info for the function we're not going to do anything.
1092 if (!MMI->hasDebugInfo())
1095 auto DI = FunctionDIs.find(MF->getFunction());
1096 if (DI == FunctionDIs.end())
1099 // Grab the lexical scopes for the function, if we don't have any of those
1100 // then we're not going to be able to do anything.
1101 LScopes.initialize(*MF);
1102 if (LScopes.empty())
1105 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1107 // Make sure that each lexical scope will have a begin/end label.
1108 identifyScopeMarkers();
1110 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1111 // belongs to so that we add to the correct per-cu line table in the
1113 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1114 // FnScope->getScopeNode() and DI->second should represent the same function,
1115 // though they may not be the same MDNode due to inline functions merged in
1116 // LTO where the debug info metadata still differs (either due to distinct
1117 // written differences - two versions of a linkonce_odr function
1118 // written/copied into two separate files, or some sub-optimal metadata that
1119 // isn't structurally identical (see: file path/name info from clang, which
1120 // includes the directory of the cpp file being built, even when the file name
1121 // is absolute (such as an <> lookup header)))
1122 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1123 assert(TheCU && "Unable to find compile unit!");
1124 if (Asm->OutStreamer.hasRawTextSupport())
1125 // Use a single line table if we are generating assembly.
1126 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1128 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1130 // Calculate history for local variables.
1131 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1134 // Request labels for the full history.
1135 for (const auto &I : DbgValues) {
1136 const auto &Ranges = I.second;
1140 // The first mention of a function argument gets the CurrentFnBegin
1141 // label, so arguments are visible when breaking at function entry.
1142 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1143 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1144 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1145 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1146 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1147 // Mark all non-overlapping initial pieces.
1148 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1149 DIExpression Piece = I->first->getDebugExpression();
1150 if (std::all_of(Ranges.begin(), I,
1151 [&](DbgValueHistoryMap::InstrRange Pred) {
1152 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1154 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1161 for (const auto &Range : Ranges) {
1162 requestLabelBeforeInsn(Range.first);
1164 requestLabelAfterInsn(Range.second);
1168 PrevInstLoc = DebugLoc();
1169 PrevLabel = Asm->getFunctionBegin();
1171 // Record beginning of function.
1172 PrologEndLoc = findPrologueEndLoc(MF);
1173 if (MDLocation *L = PrologEndLoc) {
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 auto *SP = L->getInlinedAtScope()->getSubprogram();
1177 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1181 // Gather and emit post-function debug information.
1182 void DwarfDebug::endFunction(const MachineFunction *MF) {
1183 assert(CurFn == MF &&
1184 "endFunction should be called with the same function as beginFunction");
1186 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1187 !FunctionDIs.count(MF->getFunction())) {
1188 // If we don't have a lexical scope for this function then there will
1189 // be a hole in the range information. Keep note of this by setting the
1190 // previously used section to nullptr.
1196 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1197 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1199 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1200 DISubprogram SP(FnScope->getScopeNode());
1201 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1203 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1204 collectVariableInfo(TheCU, SP, ProcessedVars);
1206 // Add the range of this function to the list of ranges for the CU.
1207 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1209 // Under -gmlt, skip building the subprogram if there are no inlined
1210 // subroutines inside it.
1211 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1212 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1213 assert(InfoHolder.getScopeVariables().empty());
1214 assert(DbgValues.empty());
1215 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1216 // by a -gmlt CU. Add a test and remove this assertion.
1217 assert(AbstractVariables.empty());
1218 LabelsBeforeInsn.clear();
1219 LabelsAfterInsn.clear();
1220 PrevLabel = nullptr;
1226 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1228 // Construct abstract scopes.
1229 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1230 DISubprogram SP(AScope->getScopeNode());
1231 assert(SP.isSubprogram());
1232 // Collect info for variables that were optimized out.
1233 DIArray Variables = SP.getVariables();
1234 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1235 DIVariable DV(Variables.getElement(i));
1236 assert(DV && DV.isVariable());
1237 if (!ProcessedVars.insert(DV).second)
1239 ensureAbstractVariableIsCreated(DV, DV.getContext());
1240 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1241 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1243 constructAbstractSubprogramScopeDIE(AScope);
1246 TheCU.constructSubprogramScopeDIE(FnScope);
1247 if (auto *SkelCU = TheCU.getSkeleton())
1248 if (!LScopes.getAbstractScopesList().empty())
1249 SkelCU->constructSubprogramScopeDIE(FnScope);
1252 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1253 // DbgVariables except those that are also in AbstractVariables (since they
1254 // can be used cross-function)
1255 InfoHolder.getScopeVariables().clear();
1257 LabelsBeforeInsn.clear();
1258 LabelsAfterInsn.clear();
1259 PrevLabel = nullptr;
1263 // Register a source line with debug info. Returns the unique label that was
1264 // emitted and which provides correspondence to the source line list.
1265 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1270 unsigned Discriminator = 0;
1271 if (DIScope Scope = DIScope(S)) {
1272 assert(Scope.isScope());
1273 Fn = Scope.getFilename();
1274 Dir = Scope.getDirectory();
1275 if (Scope.isLexicalBlockFile())
1276 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1278 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1279 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1280 .getOrCreateSourceID(Fn, Dir);
1282 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1286 //===----------------------------------------------------------------------===//
1288 //===----------------------------------------------------------------------===//
1290 // Emit the debug info section.
1291 void DwarfDebug::emitDebugInfo() {
1292 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1293 Holder.emitUnits(/* UseOffsets */ false);
1296 // Emit the abbreviation section.
1297 void DwarfDebug::emitAbbreviations() {
1298 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1300 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1303 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1304 StringRef TableName) {
1305 Accel.FinalizeTable(Asm, TableName);
1306 Asm->OutStreamer.SwitchSection(Section);
1308 // Emit the full data.
1309 Accel.emit(Asm, Section->getBeginSymbol(), this);
1312 // Emit visible names into a hashed accelerator table section.
1313 void DwarfDebug::emitAccelNames() {
1314 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1318 // Emit objective C classes and categories into a hashed accelerator table
1320 void DwarfDebug::emitAccelObjC() {
1321 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1325 // Emit namespace dies into a hashed accelerator table.
1326 void DwarfDebug::emitAccelNamespaces() {
1327 emitAccel(AccelNamespace,
1328 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1332 // Emit type dies into a hashed accelerator table.
1333 void DwarfDebug::emitAccelTypes() {
1334 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1338 // Public name handling.
1339 // The format for the various pubnames:
1341 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1342 // for the DIE that is named.
1344 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1345 // into the CU and the index value is computed according to the type of value
1346 // for the DIE that is named.
1348 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1349 // it's the offset within the debug_info/debug_types dwo section, however, the
1350 // reference in the pubname header doesn't change.
1352 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1353 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1355 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1357 // We could have a specification DIE that has our most of our knowledge,
1358 // look for that now.
1359 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1361 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1362 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1363 Linkage = dwarf::GIEL_EXTERNAL;
1364 } else if (Die->findAttribute(dwarf::DW_AT_external))
1365 Linkage = dwarf::GIEL_EXTERNAL;
1367 switch (Die->getTag()) {
1368 case dwarf::DW_TAG_class_type:
1369 case dwarf::DW_TAG_structure_type:
1370 case dwarf::DW_TAG_union_type:
1371 case dwarf::DW_TAG_enumeration_type:
1372 return dwarf::PubIndexEntryDescriptor(
1373 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1374 ? dwarf::GIEL_STATIC
1375 : dwarf::GIEL_EXTERNAL);
1376 case dwarf::DW_TAG_typedef:
1377 case dwarf::DW_TAG_base_type:
1378 case dwarf::DW_TAG_subrange_type:
1379 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1380 case dwarf::DW_TAG_namespace:
1381 return dwarf::GIEK_TYPE;
1382 case dwarf::DW_TAG_subprogram:
1383 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1384 case dwarf::DW_TAG_variable:
1385 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1386 case dwarf::DW_TAG_enumerator:
1387 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1388 dwarf::GIEL_STATIC);
1390 return dwarf::GIEK_NONE;
1394 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1396 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1397 const MCSection *PSec =
1398 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1399 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1401 emitDebugPubSection(GnuStyle, PSec, "Names",
1402 &DwarfCompileUnit::getGlobalNames);
1405 void DwarfDebug::emitDebugPubSection(
1406 bool GnuStyle, const MCSection *PSec, StringRef Name,
1407 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1408 for (const auto &NU : CUMap) {
1409 DwarfCompileUnit *TheU = NU.second;
1411 const auto &Globals = (TheU->*Accessor)();
1413 if (Globals.empty())
1416 if (auto *Skeleton = TheU->getSkeleton())
1419 // Start the dwarf pubnames section.
1420 Asm->OutStreamer.SwitchSection(PSec);
1423 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1424 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1425 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1426 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1428 Asm->OutStreamer.EmitLabel(BeginLabel);
1430 Asm->OutStreamer.AddComment("DWARF Version");
1431 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1433 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1434 Asm->emitSectionOffset(TheU->getLabelBegin());
1436 Asm->OutStreamer.AddComment("Compilation Unit Length");
1437 Asm->EmitInt32(TheU->getLength());
1439 // Emit the pubnames for this compilation unit.
1440 for (const auto &GI : Globals) {
1441 const char *Name = GI.getKeyData();
1442 const DIE *Entity = GI.second;
1444 Asm->OutStreamer.AddComment("DIE offset");
1445 Asm->EmitInt32(Entity->getOffset());
1448 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1449 Asm->OutStreamer.AddComment(
1450 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1451 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1452 Asm->EmitInt8(Desc.toBits());
1455 Asm->OutStreamer.AddComment("External Name");
1456 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1459 Asm->OutStreamer.AddComment("End Mark");
1461 Asm->OutStreamer.EmitLabel(EndLabel);
1465 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1466 const MCSection *PSec =
1467 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1468 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1470 emitDebugPubSection(GnuStyle, PSec, "Types",
1471 &DwarfCompileUnit::getGlobalTypes);
1474 // Emit visible names into a debug str section.
1475 void DwarfDebug::emitDebugStr() {
1476 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1477 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1481 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1482 const DebugLocEntry &Entry) {
1483 auto Comment = Entry.getComments().begin();
1484 auto End = Entry.getComments().end();
1485 for (uint8_t Byte : Entry.getDWARFBytes())
1486 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1489 static void emitDebugLocValue(const AsmPrinter &AP,
1490 const DITypeIdentifierMap &TypeIdentifierMap,
1491 ByteStreamer &Streamer,
1492 const DebugLocEntry::Value &Value,
1493 unsigned PieceOffsetInBits) {
1494 DIVariable DV = Value.getVariable();
1495 DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1496 AP.getDwarfDebug()->getDwarfVersion(),
1499 if (Value.isInt()) {
1500 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1501 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1502 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1503 DwarfExpr.AddSignedConstant(Value.getInt());
1505 DwarfExpr.AddUnsignedConstant(Value.getInt());
1506 } else if (Value.isLocation()) {
1507 MachineLocation Loc = Value.getLoc();
1508 DIExpression Expr = Value.getExpression();
1509 if (!Expr || (Expr.getNumElements() == 0))
1511 AP.EmitDwarfRegOp(Streamer, Loc);
1513 // Complex address entry.
1514 if (Loc.getOffset()) {
1515 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1516 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1518 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1522 // else ... ignore constant fp. There is not any good way to
1523 // to represent them here in dwarf.
1528 void DebugLocEntry::finalize(const AsmPrinter &AP,
1529 const DITypeIdentifierMap &TypeIdentifierMap) {
1530 BufferByteStreamer Streamer(DWARFBytes, Comments);
1531 const DebugLocEntry::Value Value = Values[0];
1532 if (Value.isBitPiece()) {
1533 // Emit all pieces that belong to the same variable and range.
1534 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1535 return P.isBitPiece();
1536 }) && "all values are expected to be pieces");
1537 assert(std::is_sorted(Values.begin(), Values.end()) &&
1538 "pieces are expected to be sorted");
1540 unsigned Offset = 0;
1541 for (auto Piece : Values) {
1542 DIExpression Expr = Piece.getExpression();
1543 unsigned PieceOffset = Expr.getBitPieceOffset();
1544 unsigned PieceSize = Expr.getBitPieceSize();
1545 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1546 if (Offset < PieceOffset) {
1547 // The DWARF spec seriously mandates pieces with no locations for gaps.
1548 DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1549 AP.getDwarfDebug()->getDwarfVersion(),
1551 Expr.AddOpPiece(PieceOffset-Offset, 0);
1552 Offset += PieceOffset-Offset;
1554 Offset += PieceSize;
1557 DIVariable Var = Piece.getVariable();
1558 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1559 assert(PieceSize+PieceOffset <= VarSize
1560 && "piece is larger than or outside of variable");
1561 assert(PieceSize != VarSize
1562 && "piece covers entire variable");
1564 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1567 assert(Values.size() == 1 && "only pieces may have >1 value");
1568 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1573 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1574 Asm->OutStreamer.AddComment("Loc expr size");
1575 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1576 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1577 Asm->EmitLabelDifference(end, begin, 2);
1578 Asm->OutStreamer.EmitLabel(begin);
1580 APByteStreamer Streamer(*Asm);
1581 emitDebugLocEntry(Streamer, Entry);
1583 Asm->OutStreamer.EmitLabel(end);
1586 // Emit locations into the debug loc section.
1587 void DwarfDebug::emitDebugLoc() {
1588 // Start the dwarf loc section.
1589 Asm->OutStreamer.SwitchSection(
1590 Asm->getObjFileLowering().getDwarfLocSection());
1591 unsigned char Size = Asm->getDataLayout().getPointerSize();
1592 for (const auto &DebugLoc : DotDebugLocEntries) {
1593 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1594 const DwarfCompileUnit *CU = DebugLoc.CU;
1595 for (const auto &Entry : DebugLoc.List) {
1596 // Set up the range. This range is relative to the entry point of the
1597 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1598 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1599 if (auto *Base = CU->getBaseAddress()) {
1600 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1601 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1603 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1604 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1607 emitDebugLocEntryLocation(Entry);
1609 Asm->OutStreamer.EmitIntValue(0, Size);
1610 Asm->OutStreamer.EmitIntValue(0, Size);
1614 void DwarfDebug::emitDebugLocDWO() {
1615 Asm->OutStreamer.SwitchSection(
1616 Asm->getObjFileLowering().getDwarfLocDWOSection());
1617 for (const auto &DebugLoc : DotDebugLocEntries) {
1618 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1619 for (const auto &Entry : DebugLoc.List) {
1620 // Just always use start_length for now - at least that's one address
1621 // rather than two. We could get fancier and try to, say, reuse an
1622 // address we know we've emitted elsewhere (the start of the function?
1623 // The start of the CU or CU subrange that encloses this range?)
1624 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1625 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1626 Asm->EmitULEB128(idx);
1627 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1629 emitDebugLocEntryLocation(Entry);
1631 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1636 const MCSymbol *Start, *End;
1639 // Emit a debug aranges section, containing a CU lookup for any
1640 // address we can tie back to a CU.
1641 void DwarfDebug::emitDebugARanges() {
1642 // Provides a unique id per text section.
1643 MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1645 // Filter labels by section.
1646 for (const SymbolCU &SCU : ArangeLabels) {
1647 if (SCU.Sym->isInSection()) {
1648 // Make a note of this symbol and it's section.
1649 const MCSection *Section = &SCU.Sym->getSection();
1650 if (!Section->getKind().isMetadata())
1651 SectionMap[Section].push_back(SCU);
1653 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1654 // appear in the output. This sucks as we rely on sections to build
1655 // arange spans. We can do it without, but it's icky.
1656 SectionMap[nullptr].push_back(SCU);
1660 // Add terminating symbols for each section.
1661 for (const auto &I : SectionMap) {
1662 const MCSection *Section = I.first;
1663 MCSymbol *Sym = nullptr;
1666 Sym = Asm->OutStreamer.endSection(Section);
1668 // Insert a final terminator.
1669 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1672 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1674 for (auto &I : SectionMap) {
1675 const MCSection *Section = I.first;
1676 SmallVector<SymbolCU, 8> &List = I.second;
1677 if (List.size() < 2)
1680 // If we have no section (e.g. common), just write out
1681 // individual spans for each symbol.
1683 for (const SymbolCU &Cur : List) {
1685 Span.Start = Cur.Sym;
1688 Spans[Cur.CU].push_back(Span);
1693 // Sort the symbols by offset within the section.
1694 std::sort(List.begin(), List.end(),
1695 [&](const SymbolCU &A, const SymbolCU &B) {
1696 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1697 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1699 // Symbols with no order assigned should be placed at the end.
1700 // (e.g. section end labels)
1708 // Build spans between each label.
1709 const MCSymbol *StartSym = List[0].Sym;
1710 for (size_t n = 1, e = List.size(); n < e; n++) {
1711 const SymbolCU &Prev = List[n - 1];
1712 const SymbolCU &Cur = List[n];
1714 // Try and build the longest span we can within the same CU.
1715 if (Cur.CU != Prev.CU) {
1717 Span.Start = StartSym;
1719 Spans[Prev.CU].push_back(Span);
1725 // Start the dwarf aranges section.
1726 Asm->OutStreamer.SwitchSection(
1727 Asm->getObjFileLowering().getDwarfARangesSection());
1729 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1731 // Build a list of CUs used.
1732 std::vector<DwarfCompileUnit *> CUs;
1733 for (const auto &it : Spans) {
1734 DwarfCompileUnit *CU = it.first;
1738 // Sort the CU list (again, to ensure consistent output order).
1739 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1740 return A->getUniqueID() < B->getUniqueID();
1743 // Emit an arange table for each CU we used.
1744 for (DwarfCompileUnit *CU : CUs) {
1745 std::vector<ArangeSpan> &List = Spans[CU];
1747 // Describe the skeleton CU's offset and length, not the dwo file's.
1748 if (auto *Skel = CU->getSkeleton())
1751 // Emit size of content not including length itself.
1752 unsigned ContentSize =
1753 sizeof(int16_t) + // DWARF ARange version number
1754 sizeof(int32_t) + // Offset of CU in the .debug_info section
1755 sizeof(int8_t) + // Pointer Size (in bytes)
1756 sizeof(int8_t); // Segment Size (in bytes)
1758 unsigned TupleSize = PtrSize * 2;
1760 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1762 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1764 ContentSize += Padding;
1765 ContentSize += (List.size() + 1) * TupleSize;
1767 // For each compile unit, write the list of spans it covers.
1768 Asm->OutStreamer.AddComment("Length of ARange Set");
1769 Asm->EmitInt32(ContentSize);
1770 Asm->OutStreamer.AddComment("DWARF Arange version number");
1771 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1772 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1773 Asm->emitSectionOffset(CU->getLabelBegin());
1774 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1775 Asm->EmitInt8(PtrSize);
1776 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1779 Asm->OutStreamer.EmitFill(Padding, 0xff);
1781 for (const ArangeSpan &Span : List) {
1782 Asm->EmitLabelReference(Span.Start, PtrSize);
1784 // Calculate the size as being from the span start to it's end.
1786 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1788 // For symbols without an end marker (e.g. common), we
1789 // write a single arange entry containing just that one symbol.
1790 uint64_t Size = SymSize[Span.Start];
1794 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1798 Asm->OutStreamer.AddComment("ARange terminator");
1799 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1800 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1804 // Emit visible names into a debug ranges section.
1805 void DwarfDebug::emitDebugRanges() {
1806 // Start the dwarf ranges section.
1807 Asm->OutStreamer.SwitchSection(
1808 Asm->getObjFileLowering().getDwarfRangesSection());
1810 // Size for our labels.
1811 unsigned char Size = Asm->getDataLayout().getPointerSize();
1813 // Grab the specific ranges for the compile units in the module.
1814 for (const auto &I : CUMap) {
1815 DwarfCompileUnit *TheCU = I.second;
1817 if (auto *Skel = TheCU->getSkeleton())
1820 // Iterate over the misc ranges for the compile units in the module.
1821 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1822 // Emit our symbol so we can find the beginning of the range.
1823 Asm->OutStreamer.EmitLabel(List.getSym());
1825 for (const RangeSpan &Range : List.getRanges()) {
1826 const MCSymbol *Begin = Range.getStart();
1827 const MCSymbol *End = Range.getEnd();
1828 assert(Begin && "Range without a begin symbol?");
1829 assert(End && "Range without an end symbol?");
1830 if (auto *Base = TheCU->getBaseAddress()) {
1831 Asm->EmitLabelDifference(Begin, Base, Size);
1832 Asm->EmitLabelDifference(End, Base, Size);
1834 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1835 Asm->OutStreamer.EmitSymbolValue(End, Size);
1839 // And terminate the list with two 0 values.
1840 Asm->OutStreamer.EmitIntValue(0, Size);
1841 Asm->OutStreamer.EmitIntValue(0, Size);
1846 // DWARF5 Experimental Separate Dwarf emitters.
1848 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1849 std::unique_ptr<DwarfUnit> NewU) {
1850 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1851 U.getCUNode().getSplitDebugFilename());
1853 if (!CompilationDir.empty())
1854 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1856 addGnuPubAttributes(*NewU, Die);
1858 SkeletonHolder.addUnit(std::move(NewU));
1861 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1862 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1863 // DW_AT_addr_base, DW_AT_ranges_base.
1864 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1866 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1867 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1868 DwarfCompileUnit &NewCU = *OwnedUnit;
1869 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1871 NewCU.initStmtList();
1873 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1878 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1879 // compile units that would normally be in debug_info.
1880 void DwarfDebug::emitDebugInfoDWO() {
1881 assert(useSplitDwarf() && "No split dwarf debug info?");
1882 // Don't emit relocations into the dwo file.
1883 InfoHolder.emitUnits(/* UseOffsets */ true);
1886 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1887 // abbreviations for the .debug_info.dwo section.
1888 void DwarfDebug::emitDebugAbbrevDWO() {
1889 assert(useSplitDwarf() && "No split dwarf?");
1890 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1893 void DwarfDebug::emitDebugLineDWO() {
1894 assert(useSplitDwarf() && "No split dwarf?");
1895 Asm->OutStreamer.SwitchSection(
1896 Asm->getObjFileLowering().getDwarfLineDWOSection());
1897 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
1900 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1901 // string section and is identical in format to traditional .debug_str
1903 void DwarfDebug::emitDebugStrDWO() {
1904 assert(useSplitDwarf() && "No split dwarf?");
1905 const MCSection *OffSec =
1906 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1907 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1911 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1912 if (!useSplitDwarf())
1915 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
1916 return &SplitTypeUnitFileTable;
1919 static uint64_t makeTypeSignature(StringRef Identifier) {
1921 Hash.update(Identifier);
1922 // ... take the least significant 8 bytes and return those. Our MD5
1923 // implementation always returns its results in little endian, swap bytes
1925 MD5::MD5Result Result;
1927 return support::endian::read64le(Result + 8);
1930 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1931 StringRef Identifier, DIE &RefDie,
1932 DICompositeType CTy) {
1933 // Fast path if we're building some type units and one has already used the
1934 // address pool we know we're going to throw away all this work anyway, so
1935 // don't bother building dependent types.
1936 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1939 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
1941 CU.addDIETypeSignature(RefDie, *TU);
1945 bool TopLevelType = TypeUnitsUnderConstruction.empty();
1946 AddrPool.resetUsedFlag();
1948 auto OwnedUnit = make_unique<DwarfTypeUnit>(
1949 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
1950 this, &InfoHolder, getDwoLineTable(CU));
1951 DwarfTypeUnit &NewTU = *OwnedUnit;
1952 DIE &UnitDie = NewTU.getUnitDie();
1954 TypeUnitsUnderConstruction.push_back(
1955 std::make_pair(std::move(OwnedUnit), CTy));
1957 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1960 uint64_t Signature = makeTypeSignature(Identifier);
1961 NewTU.setTypeSignature(Signature);
1963 if (useSplitDwarf())
1964 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1966 CU.applyStmtList(UnitDie);
1968 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1971 NewTU.setType(NewTU.createTypeDIE(CTy));
1974 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1975 TypeUnitsUnderConstruction.clear();
1977 // Types referencing entries in the address table cannot be placed in type
1979 if (AddrPool.hasBeenUsed()) {
1981 // Remove all the types built while building this type.
1982 // This is pessimistic as some of these types might not be dependent on
1983 // the type that used an address.
1984 for (const auto &TU : TypeUnitsToAdd)
1985 DwarfTypeUnits.erase(TU.second);
1987 // Construct this type in the CU directly.
1988 // This is inefficient because all the dependent types will be rebuilt
1989 // from scratch, including building them in type units, discovering that
1990 // they depend on addresses, throwing them out and rebuilding them.
1991 CU.constructTypeDIE(RefDie, CTy);
1995 // If the type wasn't dependent on fission addresses, finish adding the type
1996 // and all its dependent types.
1997 for (auto &TU : TypeUnitsToAdd)
1998 InfoHolder.addUnit(std::move(TU.first));
2000 CU.addDIETypeSignature(RefDie, NewTU);
2003 // Accelerator table mutators - add each name along with its companion
2004 // DIE to the proper table while ensuring that the name that we're going
2005 // to reference is in the string table. We do this since the names we
2006 // add may not only be identical to the names in the DIE.
2007 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2008 if (!useDwarfAccelTables())
2010 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2014 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2015 if (!useDwarfAccelTables())
2017 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2021 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2022 if (!useDwarfAccelTables())
2024 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2028 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2029 if (!useDwarfAccelTables())
2031 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),