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), GlobalRangeCount(0),
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 // Switch to the specified MCSection and emit an assembler
245 // temporary label to it if SymbolStem is specified.
246 static void emitSectionSym(AsmPrinter *Asm, const MCSection *Section) {
247 Asm->OutStreamer.SwitchSection(Section);
248 MCSymbol *TmpSym = Section->getBeginSymbol();
249 Asm->OutStreamer.EmitLabel(TmpSym);
252 static bool isObjCClass(StringRef Name) {
253 return Name.startswith("+") || Name.startswith("-");
256 static bool hasObjCCategory(StringRef Name) {
257 if (!isObjCClass(Name))
260 return Name.find(") ") != StringRef::npos;
263 static void getObjCClassCategory(StringRef In, StringRef &Class,
264 StringRef &Category) {
265 if (!hasObjCCategory(In)) {
266 Class = In.slice(In.find('[') + 1, In.find(' '));
271 Class = In.slice(In.find('[') + 1, In.find('('));
272 Category = In.slice(In.find('[') + 1, In.find(' '));
276 static StringRef getObjCMethodName(StringRef In) {
277 return In.slice(In.find(' ') + 1, In.find(']'));
280 // Add the various names to the Dwarf accelerator table names.
281 // TODO: Determine whether or not we should add names for programs
282 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
283 // is only slightly different than the lookup of non-standard ObjC names.
284 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
285 if (!SP.isDefinition())
287 addAccelName(SP.getName(), Die);
289 // If the linkage name is different than the name, go ahead and output
290 // that as well into the name table.
291 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
292 addAccelName(SP.getLinkageName(), Die);
294 // If this is an Objective-C selector name add it to the ObjC accelerator
296 if (isObjCClass(SP.getName())) {
297 StringRef Class, Category;
298 getObjCClassCategory(SP.getName(), Class, Category);
299 addAccelObjC(Class, Die);
301 addAccelObjC(Category, Die);
302 // Also add the base method name to the name table.
303 addAccelName(getObjCMethodName(SP.getName()), Die);
307 /// isSubprogramContext - Return true if Context is either a subprogram
308 /// or another context nested inside a subprogram.
309 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
312 DIDescriptor D(Context);
313 if (D.isSubprogram())
316 return isSubprogramContext(resolve(DIType(Context).getContext()));
320 /// Check whether we should create a DIE for the given Scope, return true
321 /// if we don't create a DIE (the corresponding DIE is null).
322 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
323 if (Scope->isAbstractScope())
326 // We don't create a DIE if there is no Range.
327 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
331 if (Ranges.size() > 1)
334 // We don't create a DIE if we have a single Range and the end label
336 return !getLabelAfterInsn(Ranges.front().second);
339 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
341 if (auto *SkelCU = CU.getSkeleton())
345 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
346 assert(Scope && Scope->getScopeNode());
347 assert(Scope->isAbstractScope());
348 assert(!Scope->getInlinedAt());
350 const MDNode *SP = Scope->getScopeNode();
352 ProcessedSPNodes.insert(SP);
354 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
355 // was inlined from another compile unit.
356 auto &CU = SPMap[SP];
357 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
358 CU.constructAbstractSubprogramScopeDIE(Scope);
362 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
363 if (!GenerateGnuPubSections)
366 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
369 // Create new DwarfCompileUnit for the given metadata node with tag
370 // DW_TAG_compile_unit.
371 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
372 StringRef FN = DIUnit.getFilename();
373 CompilationDir = DIUnit.getDirectory();
375 auto OwnedUnit = make_unique<DwarfCompileUnit>(
376 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
377 DwarfCompileUnit &NewCU = *OwnedUnit;
378 DIE &Die = NewCU.getUnitDie();
379 InfoHolder.addUnit(std::move(OwnedUnit));
381 NewCU.setSkeleton(constructSkeletonCU(NewCU));
383 // LTO with assembly output shares a single line table amongst multiple CUs.
384 // To avoid the compilation directory being ambiguous, let the line table
385 // explicitly describe the directory of all files, never relying on the
386 // compilation directory.
387 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
388 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
389 NewCU.getUniqueID(), CompilationDir);
391 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
392 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
393 DIUnit.getLanguage());
394 NewCU.addString(Die, dwarf::DW_AT_name, FN);
396 if (!useSplitDwarf()) {
397 NewCU.initStmtList();
399 // If we're using split dwarf the compilation dir is going to be in the
400 // skeleton CU and so we don't need to duplicate it here.
401 if (!CompilationDir.empty())
402 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
404 addGnuPubAttributes(NewCU, Die);
407 if (DIUnit.isOptimized())
408 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
410 StringRef Flags = DIUnit.getFlags();
412 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
414 if (unsigned RVer = DIUnit.getRunTimeVersion())
415 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
416 dwarf::DW_FORM_data1, RVer);
419 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
421 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
423 CUMap.insert(std::make_pair(DIUnit, &NewCU));
424 CUDieMap.insert(std::make_pair(&Die, &NewCU));
428 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
430 DIImportedEntity Module(N);
431 assert(Module.Verify());
432 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
433 D->addChild(TheCU.constructImportedEntityDIE(Module));
436 // Emit all Dwarf sections that should come prior to the content. Create
437 // global DIEs and emit initial debug info sections. This is invoked by
438 // the target AsmPrinter.
439 void DwarfDebug::beginModule() {
440 if (DisableDebugInfoPrinting)
443 const Module *M = MMI->getModule();
445 FunctionDIs = makeSubprogramMap(*M);
447 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
450 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
452 // Emit initial sections so we can reference labels later.
455 SingleCU = CU_Nodes->getNumOperands() == 1;
457 for (MDNode *N : CU_Nodes->operands()) {
458 DICompileUnit CUNode(N);
459 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
460 DIArray ImportedEntities = CUNode.getImportedEntities();
461 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
462 ScopesWithImportedEntities.push_back(std::make_pair(
463 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
464 ImportedEntities.getElement(i)));
465 // Stable sort to preserve the order of appearance of imported entities.
466 // This is to avoid out-of-order processing of interdependent declarations
467 // within the same scope, e.g. { namespace A = base; namespace B = A; }
468 std::stable_sort(ScopesWithImportedEntities.begin(),
469 ScopesWithImportedEntities.end(), less_first());
470 DIArray GVs = CUNode.getGlobalVariables();
471 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
472 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
473 DIArray SPs = CUNode.getSubprograms();
474 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
475 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
476 DIArray EnumTypes = CUNode.getEnumTypes();
477 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
478 DIType Ty(EnumTypes.getElement(i));
479 // The enum types array by design contains pointers to
480 // MDNodes rather than DIRefs. Unique them here.
481 DIType UniqueTy(resolve(Ty.getRef()));
482 CU.getOrCreateTypeDIE(UniqueTy);
484 DIArray RetainedTypes = CUNode.getRetainedTypes();
485 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
486 DIType Ty(RetainedTypes.getElement(i));
487 // The retained types array by design contains pointers to
488 // MDNodes rather than DIRefs. Unique them here.
489 DIType UniqueTy(resolve(Ty.getRef()));
490 CU.getOrCreateTypeDIE(UniqueTy);
492 // Emit imported_modules last so that the relevant context is already
494 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
495 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
498 // Tell MMI that we have debug info.
499 MMI->setDebugInfoAvailability(true);
502 void DwarfDebug::finishVariableDefinitions() {
503 for (const auto &Var : ConcreteVariables) {
504 DIE *VariableDie = Var->getDIE();
506 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
507 // in the ConcreteVariables list, rather than looking it up again here.
508 // DIE::getUnit isn't simple - it walks parent pointers, etc.
509 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
511 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
512 if (AbsVar && AbsVar->getDIE()) {
513 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
516 Unit->applyVariableAttributes(*Var, *VariableDie);
520 void DwarfDebug::finishSubprogramDefinitions() {
521 for (const auto &P : SPMap)
522 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
523 CU.finishSubprogramDefinition(DISubprogram(P.first));
528 // Collect info for variables that were optimized out.
529 void DwarfDebug::collectDeadVariables() {
530 const Module *M = MMI->getModule();
532 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
533 for (MDNode *N : CU_Nodes->operands()) {
534 DICompileUnit TheCU(N);
535 // Construct subprogram DIE and add variables DIEs.
536 DwarfCompileUnit *SPCU =
537 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
538 assert(SPCU && "Unable to find Compile Unit!");
539 DIArray Subprograms = TheCU.getSubprograms();
540 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
541 DISubprogram SP(Subprograms.getElement(i));
542 if (ProcessedSPNodes.count(SP) != 0)
544 SPCU->collectDeadVariables(SP);
550 void DwarfDebug::finalizeModuleInfo() {
551 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
553 finishSubprogramDefinitions();
555 finishVariableDefinitions();
557 // Collect info for variables that were optimized out.
558 collectDeadVariables();
560 // Handle anything that needs to be done on a per-unit basis after
561 // all other generation.
562 for (const auto &P : CUMap) {
563 auto &TheCU = *P.second;
564 // Emit DW_AT_containing_type attribute to connect types with their
565 // vtable holding type.
566 TheCU.constructContainingTypeDIEs();
568 // Add CU specific attributes if we need to add any.
569 // If we're splitting the dwarf out now that we've got the entire
570 // CU then add the dwo id to it.
571 auto *SkCU = TheCU.getSkeleton();
572 if (useSplitDwarf()) {
573 // Emit a unique identifier for this CU.
574 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
575 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
576 dwarf::DW_FORM_data8, ID);
577 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
578 dwarf::DW_FORM_data8, ID);
580 // We don't keep track of which addresses are used in which CU so this
581 // is a bit pessimistic under LTO.
582 if (!AddrPool.isEmpty()) {
583 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
584 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
587 if (!SkCU->getRangeLists().empty()) {
588 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
589 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
594 // If we have code split among multiple sections or non-contiguous
595 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
596 // remain in the .o file, otherwise add a DW_AT_low_pc.
597 // FIXME: We should use ranges allow reordering of code ala
598 // .subsections_via_symbols in mach-o. This would mean turning on
599 // ranges for all subprogram DIEs for mach-o.
600 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
601 if (unsigned NumRanges = TheCU.getRanges().size()) {
603 // A DW_AT_low_pc attribute may also be specified in combination with
604 // DW_AT_ranges to specify the default base address for use in
605 // location lists (see Section 2.6.2) and range lists (see Section
607 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
609 TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
610 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
614 // Compute DIE offsets and sizes.
615 InfoHolder.computeSizeAndOffsets();
617 SkeletonHolder.computeSizeAndOffsets();
620 // Emit all Dwarf sections that should come after the content.
621 void DwarfDebug::endModule() {
622 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
623 assert(CurFn == nullptr);
624 assert(CurMI == nullptr);
626 // If we aren't actually generating debug info (check beginModule -
627 // conditionalized on !DisableDebugInfoPrinting and the presence of the
628 // llvm.dbg.cu metadata node)
629 if (!TLOF.getDwarfInfoSection()->getBeginSymbol()->isInSection())
632 // Finalize the debug info for the module.
633 finalizeModuleInfo();
640 // Emit info into a debug loc section.
643 // Emit all the DIEs into a debug info section.
646 // Corresponding abbreviations into a abbrev section.
649 // Emit info into a debug aranges section.
650 if (GenerateARangeSection)
653 // Emit info into a debug ranges section.
656 if (useSplitDwarf()) {
659 emitDebugAbbrevDWO();
661 // Emit DWO addresses.
662 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
665 // Emit info into the dwarf accelerator table sections.
666 if (useDwarfAccelTables()) {
669 emitAccelNamespaces();
673 // Emit the pubnames and pubtypes sections if requested.
674 if (HasDwarfPubSections) {
675 emitDebugPubNames(GenerateGnuPubSections);
676 emitDebugPubTypes(GenerateGnuPubSections);
681 AbstractVariables.clear();
684 // Find abstract variable, if any, associated with Var.
685 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
686 DIVariable &Cleansed) {
687 LLVMContext &Ctx = DV->getContext();
688 // More then one inlined variable corresponds to one abstract variable.
689 // FIXME: This duplication of variables when inlining should probably be
690 // removed. It's done to allow each DIVariable to describe its location
691 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
692 // make it accurate then remove this duplication/cleansing stuff.
693 Cleansed = cleanseInlinedVariable(DV, Ctx);
694 auto I = AbstractVariables.find(Cleansed);
695 if (I != AbstractVariables.end())
696 return I->second.get();
700 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
702 return getExistingAbstractVariable(DV, Cleansed);
705 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
706 LexicalScope *Scope) {
707 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
708 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
709 AbstractVariables[Var] = std::move(AbsDbgVariable);
712 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
713 const MDNode *ScopeNode) {
714 DIVariable Cleansed = DV;
715 if (getExistingAbstractVariable(DV, Cleansed))
718 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
722 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
723 const MDNode *ScopeNode) {
724 DIVariable Cleansed = DV;
725 if (getExistingAbstractVariable(DV, Cleansed))
728 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
729 createAbstractVariable(Cleansed, Scope);
732 // Collect variable information from side table maintained by MMI.
733 void DwarfDebug::collectVariableInfoFromMMITable(
734 SmallPtrSetImpl<const MDNode *> &Processed) {
735 for (const auto &VI : MMI->getVariableDbgInfo()) {
738 Processed.insert(VI.Var);
739 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
741 // If variable scope is not found then skip this variable.
745 DIVariable DV(VI.Var);
746 DIExpression Expr(VI.Expr);
747 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
748 auto RegVar = make_unique<DbgVariable>(DV, Expr, this, VI.Slot);
749 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
750 ConcreteVariables.push_back(std::move(RegVar));
754 // Get .debug_loc entry for the instruction range starting at MI.
755 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
756 const MDNode *Expr = MI->getDebugExpression();
757 const MDNode *Var = MI->getDebugVariable();
759 assert(MI->getNumOperands() == 4);
760 if (MI->getOperand(0).isReg()) {
761 MachineLocation MLoc;
762 // If the second operand is an immediate, this is a
763 // register-indirect address.
764 if (!MI->getOperand(1).isImm())
765 MLoc.set(MI->getOperand(0).getReg());
767 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
768 return DebugLocEntry::Value(Var, Expr, MLoc);
770 if (MI->getOperand(0).isImm())
771 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
772 if (MI->getOperand(0).isFPImm())
773 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
774 if (MI->getOperand(0).isCImm())
775 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
777 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
780 /// Determine whether two variable pieces overlap.
781 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
782 if (!P1.isBitPiece() || !P2.isBitPiece())
784 unsigned l1 = P1.getBitPieceOffset();
785 unsigned l2 = P2.getBitPieceOffset();
786 unsigned r1 = l1 + P1.getBitPieceSize();
787 unsigned r2 = l2 + P2.getBitPieceSize();
788 // True where [l1,r1[ and [r1,r2[ overlap.
789 return (l1 < r2) && (l2 < r1);
792 /// Build the location list for all DBG_VALUEs in the function that
793 /// describe the same variable. If the ranges of several independent
794 /// pieces of the same variable overlap partially, split them up and
795 /// combine the ranges. The resulting DebugLocEntries are will have
796 /// strict monotonically increasing begin addresses and will never
801 // Ranges History [var, loc, piece ofs size]
802 // 0 | [x, (reg0, piece 0, 32)]
803 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
805 // 3 | [clobber reg0]
806 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
811 // [0-1] [x, (reg0, piece 0, 32)]
812 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
813 // [3-4] [x, (reg1, piece 32, 32)]
814 // [4- ] [x, (mem, piece 0, 64)]
816 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
817 const DbgValueHistoryMap::InstrRanges &Ranges) {
818 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
820 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
821 const MachineInstr *Begin = I->first;
822 const MachineInstr *End = I->second;
823 assert(Begin->isDebugValue() && "Invalid History entry");
825 // Check if a variable is inaccessible in this range.
826 if (Begin->getNumOperands() > 1 &&
827 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
832 // If this piece overlaps with any open ranges, truncate them.
833 DIExpression DIExpr = Begin->getDebugExpression();
834 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
835 [&](DebugLocEntry::Value R) {
836 return piecesOverlap(DIExpr, R.getExpression());
838 OpenRanges.erase(Last, OpenRanges.end());
840 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
841 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
843 const MCSymbol *EndLabel;
845 EndLabel = getLabelAfterInsn(End);
846 else if (std::next(I) == Ranges.end())
847 EndLabel = Asm->getFunctionEnd();
849 EndLabel = getLabelBeforeInsn(std::next(I)->first);
850 assert(EndLabel && "Forgot label after instruction ending a range!");
852 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
854 auto Value = getDebugLocValue(Begin);
855 DebugLocEntry Loc(StartLabel, EndLabel, Value);
856 bool couldMerge = false;
858 // If this is a piece, it may belong to the current DebugLocEntry.
859 if (DIExpr.isBitPiece()) {
860 // Add this value to the list of open ranges.
861 OpenRanges.push_back(Value);
863 // Attempt to add the piece to the last entry.
864 if (!DebugLoc.empty())
865 if (DebugLoc.back().MergeValues(Loc))
870 // Need to add a new DebugLocEntry. Add all values from still
871 // valid non-overlapping pieces.
872 if (OpenRanges.size())
873 Loc.addValues(OpenRanges);
875 DebugLoc.push_back(std::move(Loc));
878 // Attempt to coalesce the ranges of two otherwise identical
880 auto CurEntry = DebugLoc.rbegin();
881 auto PrevEntry = std::next(CurEntry);
882 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
886 dbgs() << CurEntry->getValues().size() << " Values:\n";
887 for (auto Value : CurEntry->getValues()) {
888 Value.getVariable()->dump();
889 Value.getExpression()->dump();
897 // Find variables for each lexical scope.
899 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
900 SmallPtrSetImpl<const MDNode *> &Processed) {
901 // Grab the variable info that was squirreled away in the MMI side-table.
902 collectVariableInfoFromMMITable(Processed);
904 for (const auto &I : DbgValues) {
905 DIVariable DV(I.first);
906 if (Processed.count(DV))
909 // Instruction ranges, specifying where DV is accessible.
910 const auto &Ranges = I.second;
914 LexicalScope *Scope = nullptr;
915 if (MDNode *IA = DV.getInlinedAt())
916 Scope = LScopes.findInlinedScope(DV.getContext(), IA);
918 Scope = LScopes.findLexicalScope(DV.getContext());
919 // If variable scope is not found then skip this variable.
923 Processed.insert(DV);
924 const MachineInstr *MInsn = Ranges.front().first;
925 assert(MInsn->isDebugValue() && "History must begin with debug value");
926 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
927 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
928 DbgVariable *RegVar = ConcreteVariables.back().get();
929 InfoHolder.addScopeVariable(Scope, RegVar);
931 // Check if the first DBG_VALUE is valid for the rest of the function.
932 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
935 // Handle multiple DBG_VALUE instructions describing one variable.
936 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
938 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
939 DebugLocList &LocList = DotDebugLocEntries.back();
942 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
944 // Build the location list for this variable.
945 buildLocationList(LocList.List, Ranges);
946 // Finalize the entry by lowering it into a DWARF bytestream.
947 for (auto &Entry : LocList.List)
948 Entry.finalize(*Asm, TypeIdentifierMap);
951 // Collect info for variables that were optimized out.
952 DIArray Variables = SP.getVariables();
953 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
954 DIVariable DV(Variables.getElement(i));
955 assert(DV.isVariable());
956 if (!Processed.insert(DV).second)
958 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
959 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
961 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
962 InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
967 // Return Label preceding the instruction.
968 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
969 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
970 assert(Label && "Didn't insert label before instruction");
974 // Return Label immediately following the instruction.
975 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
976 return LabelsAfterInsn.lookup(MI);
979 // Process beginning of an instruction.
980 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
981 assert(CurMI == nullptr);
983 // Check if source location changes, but ignore DBG_VALUE locations.
984 if (!MI->isDebugValue()) {
985 DebugLoc DL = MI->getDebugLoc();
986 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
989 if (DL == PrologEndLoc) {
990 Flags |= DWARF2_FLAG_PROLOGUE_END;
991 PrologEndLoc = DebugLoc();
992 Flags |= DWARF2_FLAG_IS_STMT;
995 Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
996 Flags |= DWARF2_FLAG_IS_STMT;
998 if (!DL.isUnknown()) {
999 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1000 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1002 recordSourceLine(0, 0, nullptr, 0);
1006 // Insert labels where requested.
1007 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1008 LabelsBeforeInsn.find(MI);
1011 if (I == LabelsBeforeInsn.end())
1014 // Label already assigned.
1019 PrevLabel = MMI->getContext().CreateTempSymbol();
1020 Asm->OutStreamer.EmitLabel(PrevLabel);
1022 I->second = PrevLabel;
1025 // Process end of an instruction.
1026 void DwarfDebug::endInstruction() {
1027 assert(CurMI != nullptr);
1028 // Don't create a new label after DBG_VALUE instructions.
1029 // They don't generate code.
1030 if (!CurMI->isDebugValue())
1031 PrevLabel = nullptr;
1033 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1034 LabelsAfterInsn.find(CurMI);
1038 if (I == LabelsAfterInsn.end())
1041 // Label already assigned.
1045 // We need a label after this instruction.
1047 PrevLabel = MMI->getContext().CreateTempSymbol();
1048 Asm->OutStreamer.EmitLabel(PrevLabel);
1050 I->second = PrevLabel;
1053 // Each LexicalScope has first instruction and last instruction to mark
1054 // beginning and end of a scope respectively. Create an inverse map that list
1055 // scopes starts (and ends) with an instruction. One instruction may start (or
1056 // end) multiple scopes. Ignore scopes that are not reachable.
1057 void DwarfDebug::identifyScopeMarkers() {
1058 SmallVector<LexicalScope *, 4> WorkList;
1059 WorkList.push_back(LScopes.getCurrentFunctionScope());
1060 while (!WorkList.empty()) {
1061 LexicalScope *S = WorkList.pop_back_val();
1063 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1064 if (!Children.empty())
1065 WorkList.append(Children.begin(), Children.end());
1067 if (S->isAbstractScope())
1070 for (const InsnRange &R : S->getRanges()) {
1071 assert(R.first && "InsnRange does not have first instruction!");
1072 assert(R.second && "InsnRange does not have second instruction!");
1073 requestLabelBeforeInsn(R.first);
1074 requestLabelAfterInsn(R.second);
1079 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1080 // First known non-DBG_VALUE and non-frame setup location marks
1081 // the beginning of the function body.
1082 for (const auto &MBB : *MF)
1083 for (const auto &MI : MBB)
1084 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1085 !MI.getDebugLoc().isUnknown()) {
1086 // Did the target forget to set the FrameSetup flag for CFI insns?
1087 assert(!MI.isCFIInstruction() &&
1088 "First non-frame-setup instruction is a CFI instruction.");
1089 return MI.getDebugLoc();
1094 // Gather pre-function debug information. Assumes being called immediately
1095 // after the function entry point has been emitted.
1096 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1099 // If there's no debug info for the function we're not going to do anything.
1100 if (!MMI->hasDebugInfo())
1103 auto DI = FunctionDIs.find(MF->getFunction());
1104 if (DI == FunctionDIs.end())
1107 // Grab the lexical scopes for the function, if we don't have any of those
1108 // then we're not going to be able to do anything.
1109 LScopes.initialize(*MF);
1110 if (LScopes.empty())
1113 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1115 // Make sure that each lexical scope will have a begin/end label.
1116 identifyScopeMarkers();
1118 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1119 // belongs to so that we add to the correct per-cu line table in the
1121 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1122 // FnScope->getScopeNode() and DI->second should represent the same function,
1123 // though they may not be the same MDNode due to inline functions merged in
1124 // LTO where the debug info metadata still differs (either due to distinct
1125 // written differences - two versions of a linkonce_odr function
1126 // written/copied into two separate files, or some sub-optimal metadata that
1127 // isn't structurally identical (see: file path/name info from clang, which
1128 // includes the directory of the cpp file being built, even when the file name
1129 // is absolute (such as an <> lookup header)))
1130 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1131 assert(TheCU && "Unable to find compile unit!");
1132 if (Asm->OutStreamer.hasRawTextSupport())
1133 // Use a single line table if we are generating assembly.
1134 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1136 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1138 // Calculate history for local variables.
1139 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1142 // Request labels for the full history.
1143 for (const auto &I : DbgValues) {
1144 const auto &Ranges = I.second;
1148 // The first mention of a function argument gets the CurrentFnBegin
1149 // label, so arguments are visible when breaking at function entry.
1150 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1151 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1152 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1153 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1154 if (Ranges.front().first->getDebugExpression().isBitPiece()) {
1155 // Mark all non-overlapping initial pieces.
1156 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1157 DIExpression Piece = I->first->getDebugExpression();
1158 if (std::all_of(Ranges.begin(), I,
1159 [&](DbgValueHistoryMap::InstrRange Pred) {
1160 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1162 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1169 for (const auto &Range : Ranges) {
1170 requestLabelBeforeInsn(Range.first);
1172 requestLabelAfterInsn(Range.second);
1176 PrevInstLoc = DebugLoc();
1177 PrevLabel = Asm->getFunctionBegin();
1179 // Record beginning of function.
1180 PrologEndLoc = findPrologueEndLoc(MF);
1181 if (!PrologEndLoc.isUnknown()) {
1182 DebugLoc FnStartDL =
1183 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1185 // We'd like to list the prologue as "not statements" but GDB behaves
1186 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1187 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1188 FnStartDL.getScope(MF->getFunction()->getContext()),
1189 DWARF2_FLAG_IS_STMT);
1193 // Gather and emit post-function debug information.
1194 void DwarfDebug::endFunction(const MachineFunction *MF) {
1195 assert(CurFn == MF &&
1196 "endFunction should be called with the same function as beginFunction");
1198 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1199 !FunctionDIs.count(MF->getFunction())) {
1200 // If we don't have a lexical scope for this function then there will
1201 // be a hole in the range information. Keep note of this by setting the
1202 // previously used section to nullptr.
1208 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1209 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1211 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1212 DISubprogram SP(FnScope->getScopeNode());
1213 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1215 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1216 collectVariableInfo(TheCU, SP, ProcessedVars);
1218 // Add the range of this function to the list of ranges for the CU.
1219 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1221 // Under -gmlt, skip building the subprogram if there are no inlined
1222 // subroutines inside it.
1223 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1224 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1225 assert(InfoHolder.getScopeVariables().empty());
1226 assert(DbgValues.empty());
1227 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1228 // by a -gmlt CU. Add a test and remove this assertion.
1229 assert(AbstractVariables.empty());
1230 LabelsBeforeInsn.clear();
1231 LabelsAfterInsn.clear();
1232 PrevLabel = nullptr;
1238 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1240 // Construct abstract scopes.
1241 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1242 DISubprogram SP(AScope->getScopeNode());
1243 assert(SP.isSubprogram());
1244 // Collect info for variables that were optimized out.
1245 DIArray Variables = SP.getVariables();
1246 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1247 DIVariable DV(Variables.getElement(i));
1248 assert(DV && DV.isVariable());
1249 if (!ProcessedVars.insert(DV).second)
1251 ensureAbstractVariableIsCreated(DV, DV.getContext());
1252 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1253 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1255 constructAbstractSubprogramScopeDIE(AScope);
1258 TheCU.constructSubprogramScopeDIE(FnScope);
1259 if (auto *SkelCU = TheCU.getSkeleton())
1260 if (!LScopes.getAbstractScopesList().empty())
1261 SkelCU->constructSubprogramScopeDIE(FnScope);
1264 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1265 // DbgVariables except those that are also in AbstractVariables (since they
1266 // can be used cross-function)
1267 InfoHolder.getScopeVariables().clear();
1269 LabelsBeforeInsn.clear();
1270 LabelsAfterInsn.clear();
1271 PrevLabel = nullptr;
1275 // Register a source line with debug info. Returns the unique label that was
1276 // emitted and which provides correspondence to the source line list.
1277 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1282 unsigned Discriminator = 0;
1283 if (DIScope Scope = DIScope(S)) {
1284 assert(Scope.isScope());
1285 Fn = Scope.getFilename();
1286 Dir = Scope.getDirectory();
1287 if (Scope.isLexicalBlockFile())
1288 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1290 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1291 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1292 .getOrCreateSourceID(Fn, Dir);
1294 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1298 //===----------------------------------------------------------------------===//
1300 //===----------------------------------------------------------------------===//
1302 // Emit initial Dwarf sections with a label at the start of each one.
1303 void DwarfDebug::emitSectionLabels() {
1304 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1306 // Dwarf sections base addresses.
1307 emitSectionSym(Asm, TLOF.getDwarfInfoSection());
1308 if (useSplitDwarf()) {
1309 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection());
1310 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection());
1312 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection());
1313 if (useSplitDwarf())
1314 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection());
1316 emitSectionSym(Asm, TLOF.getDwarfLineSection());
1317 emitSectionSym(Asm, TLOF.getDwarfStrSection());
1318 if (useSplitDwarf()) {
1319 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection());
1320 emitSectionSym(Asm, TLOF.getDwarfAddrSection());
1321 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection());
1323 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1324 emitSectionSym(Asm, TLOF.getDwarfRangesSection());
1327 // Emit the debug info section.
1328 void DwarfDebug::emitDebugInfo() {
1329 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1330 Holder.emitUnits(/* UseOffsets */ false);
1333 // Emit the abbreviation section.
1334 void DwarfDebug::emitAbbreviations() {
1335 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1337 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1340 // Emit the last address of the section and the end of the line matrix.
1341 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1342 // Define last address of section.
1343 Asm->OutStreamer.AddComment("Extended Op");
1346 Asm->OutStreamer.AddComment("Op size");
1347 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1348 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1349 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1351 Asm->OutStreamer.AddComment("Section end label");
1353 Asm->OutStreamer.EmitSymbolValue(
1354 Asm->GetTempSymbol("section_end", SectionEnd),
1355 Asm->getDataLayout().getPointerSize());
1357 // Mark end of matrix.
1358 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1364 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1365 StringRef TableName) {
1366 Accel.FinalizeTable(Asm, TableName);
1367 emitSectionSym(Asm, Section);
1369 // Emit the full data.
1370 Accel.emit(Asm, Section->getBeginSymbol(), this);
1373 // Emit visible names into a hashed accelerator table section.
1374 void DwarfDebug::emitAccelNames() {
1375 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1379 // Emit objective C classes and categories into a hashed accelerator table
1381 void DwarfDebug::emitAccelObjC() {
1382 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1386 // Emit namespace dies into a hashed accelerator table.
1387 void DwarfDebug::emitAccelNamespaces() {
1388 emitAccel(AccelNamespace,
1389 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1393 // Emit type dies into a hashed accelerator table.
1394 void DwarfDebug::emitAccelTypes() {
1395 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1399 // Public name handling.
1400 // The format for the various pubnames:
1402 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1403 // for the DIE that is named.
1405 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1406 // into the CU and the index value is computed according to the type of value
1407 // for the DIE that is named.
1409 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1410 // it's the offset within the debug_info/debug_types dwo section, however, the
1411 // reference in the pubname header doesn't change.
1413 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1414 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1416 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1418 // We could have a specification DIE that has our most of our knowledge,
1419 // look for that now.
1420 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1422 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1423 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1424 Linkage = dwarf::GIEL_EXTERNAL;
1425 } else if (Die->findAttribute(dwarf::DW_AT_external))
1426 Linkage = dwarf::GIEL_EXTERNAL;
1428 switch (Die->getTag()) {
1429 case dwarf::DW_TAG_class_type:
1430 case dwarf::DW_TAG_structure_type:
1431 case dwarf::DW_TAG_union_type:
1432 case dwarf::DW_TAG_enumeration_type:
1433 return dwarf::PubIndexEntryDescriptor(
1434 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1435 ? dwarf::GIEL_STATIC
1436 : dwarf::GIEL_EXTERNAL);
1437 case dwarf::DW_TAG_typedef:
1438 case dwarf::DW_TAG_base_type:
1439 case dwarf::DW_TAG_subrange_type:
1440 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1441 case dwarf::DW_TAG_namespace:
1442 return dwarf::GIEK_TYPE;
1443 case dwarf::DW_TAG_subprogram:
1444 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1445 case dwarf::DW_TAG_variable:
1446 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1447 case dwarf::DW_TAG_enumerator:
1448 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1449 dwarf::GIEL_STATIC);
1451 return dwarf::GIEK_NONE;
1455 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1457 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1458 const MCSection *PSec =
1459 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1460 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1462 emitDebugPubSection(GnuStyle, PSec, "Names",
1463 &DwarfCompileUnit::getGlobalNames);
1466 void DwarfDebug::emitDebugPubSection(
1467 bool GnuStyle, const MCSection *PSec, StringRef Name,
1468 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1469 for (const auto &NU : CUMap) {
1470 DwarfCompileUnit *TheU = NU.second;
1472 const auto &Globals = (TheU->*Accessor)();
1474 if (Globals.empty())
1477 if (auto *Skeleton = TheU->getSkeleton())
1479 unsigned ID = TheU->getUniqueID();
1481 // Start the dwarf pubnames section.
1482 Asm->OutStreamer.SwitchSection(PSec);
1485 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1486 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1487 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1488 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1490 Asm->OutStreamer.EmitLabel(BeginLabel);
1492 Asm->OutStreamer.AddComment("DWARF Version");
1493 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1495 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1496 Asm->emitSectionOffset(TheU->getLabelBegin());
1498 Asm->OutStreamer.AddComment("Compilation Unit Length");
1499 Asm->EmitInt32(TheU->getLength());
1501 // Emit the pubnames for this compilation unit.
1502 for (const auto &GI : Globals) {
1503 const char *Name = GI.getKeyData();
1504 const DIE *Entity = GI.second;
1506 Asm->OutStreamer.AddComment("DIE offset");
1507 Asm->EmitInt32(Entity->getOffset());
1510 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1511 Asm->OutStreamer.AddComment(
1512 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1513 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1514 Asm->EmitInt8(Desc.toBits());
1517 Asm->OutStreamer.AddComment("External Name");
1518 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1521 Asm->OutStreamer.AddComment("End Mark");
1523 Asm->OutStreamer.EmitLabel(EndLabel);
1527 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1528 const MCSection *PSec =
1529 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1530 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1532 emitDebugPubSection(GnuStyle, PSec, "Types",
1533 &DwarfCompileUnit::getGlobalTypes);
1536 // Emit visible names into a debug str section.
1537 void DwarfDebug::emitDebugStr() {
1538 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1539 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1543 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1544 const DebugLocEntry &Entry) {
1545 auto Comment = Entry.getComments().begin();
1546 auto End = Entry.getComments().end();
1547 for (uint8_t Byte : Entry.getDWARFBytes())
1548 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1551 static void emitDebugLocValue(const AsmPrinter &AP,
1552 const DITypeIdentifierMap &TypeIdentifierMap,
1553 ByteStreamer &Streamer,
1554 const DebugLocEntry::Value &Value,
1555 unsigned PieceOffsetInBits) {
1556 DIVariable DV = Value.getVariable();
1557 DebugLocDwarfExpression DwarfExpr(
1558 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1559 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1561 if (Value.isInt()) {
1562 DIBasicType BTy(DV.getType().resolve(TypeIdentifierMap));
1563 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1564 BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1565 DwarfExpr.AddSignedConstant(Value.getInt());
1567 DwarfExpr.AddUnsignedConstant(Value.getInt());
1568 } else if (Value.isLocation()) {
1569 MachineLocation Loc = Value.getLoc();
1570 DIExpression Expr = Value.getExpression();
1571 if (!Expr || (Expr.getNumElements() == 0))
1573 AP.EmitDwarfRegOp(Streamer, Loc);
1575 // Complex address entry.
1576 if (Loc.getOffset()) {
1577 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1578 DwarfExpr.AddExpression(Expr.begin(), Expr.end(), PieceOffsetInBits);
1580 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1584 // else ... ignore constant fp. There is not any good way to
1585 // to represent them here in dwarf.
1590 void DebugLocEntry::finalize(const AsmPrinter &AP,
1591 const DITypeIdentifierMap &TypeIdentifierMap) {
1592 BufferByteStreamer Streamer(DWARFBytes, Comments);
1593 const DebugLocEntry::Value Value = Values[0];
1594 if (Value.isBitPiece()) {
1595 // Emit all pieces that belong to the same variable and range.
1596 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1597 return P.isBitPiece();
1598 }) && "all values are expected to be pieces");
1599 assert(std::is_sorted(Values.begin(), Values.end()) &&
1600 "pieces are expected to be sorted");
1602 unsigned Offset = 0;
1603 for (auto Piece : Values) {
1604 DIExpression Expr = Piece.getExpression();
1605 unsigned PieceOffset = Expr.getBitPieceOffset();
1606 unsigned PieceSize = Expr.getBitPieceSize();
1607 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1608 if (Offset < PieceOffset) {
1609 // The DWARF spec seriously mandates pieces with no locations for gaps.
1610 DebugLocDwarfExpression Expr(
1611 *AP.TM.getSubtargetImpl()->getRegisterInfo(),
1612 AP.getDwarfDebug()->getDwarfVersion(), Streamer);
1613 Expr.AddOpPiece(PieceOffset-Offset, 0);
1614 Offset += PieceOffset-Offset;
1616 Offset += PieceSize;
1619 DIVariable Var = Piece.getVariable();
1620 unsigned VarSize = Var.getSizeInBits(TypeIdentifierMap);
1621 assert(PieceSize+PieceOffset <= VarSize
1622 && "piece is larger than or outside of variable");
1623 assert(PieceSize != VarSize
1624 && "piece covers entire variable");
1626 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Piece, PieceOffset);
1629 assert(Values.size() == 1 && "only pieces may have >1 value");
1630 emitDebugLocValue(AP, TypeIdentifierMap, Streamer, Value, 0);
1635 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1636 Asm->OutStreamer.AddComment("Loc expr size");
1637 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1638 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1639 Asm->EmitLabelDifference(end, begin, 2);
1640 Asm->OutStreamer.EmitLabel(begin);
1642 APByteStreamer Streamer(*Asm);
1643 emitDebugLocEntry(Streamer, Entry);
1645 Asm->OutStreamer.EmitLabel(end);
1648 // Emit locations into the debug loc section.
1649 void DwarfDebug::emitDebugLoc() {
1650 // Start the dwarf loc section.
1651 Asm->OutStreamer.SwitchSection(
1652 Asm->getObjFileLowering().getDwarfLocSection());
1653 unsigned char Size = Asm->getDataLayout().getPointerSize();
1654 for (const auto &DebugLoc : DotDebugLocEntries) {
1655 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1656 const DwarfCompileUnit *CU = DebugLoc.CU;
1657 for (const auto &Entry : DebugLoc.List) {
1658 // Set up the range. This range is relative to the entry point of the
1659 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1660 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1661 if (auto *Base = CU->getBaseAddress()) {
1662 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1663 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1665 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1666 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1669 emitDebugLocEntryLocation(Entry);
1671 Asm->OutStreamer.EmitIntValue(0, Size);
1672 Asm->OutStreamer.EmitIntValue(0, Size);
1676 void DwarfDebug::emitDebugLocDWO() {
1677 Asm->OutStreamer.SwitchSection(
1678 Asm->getObjFileLowering().getDwarfLocDWOSection());
1679 for (const auto &DebugLoc : DotDebugLocEntries) {
1680 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1681 for (const auto &Entry : DebugLoc.List) {
1682 // Just always use start_length for now - at least that's one address
1683 // rather than two. We could get fancier and try to, say, reuse an
1684 // address we know we've emitted elsewhere (the start of the function?
1685 // The start of the CU or CU subrange that encloses this range?)
1686 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1687 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1688 Asm->EmitULEB128(idx);
1689 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1691 emitDebugLocEntryLocation(Entry);
1693 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1698 const MCSymbol *Start, *End;
1701 // Emit a debug aranges section, containing a CU lookup for any
1702 // address we can tie back to a CU.
1703 void DwarfDebug::emitDebugARanges() {
1704 // Provides a unique id per text section.
1705 MapVector<const MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1707 // Filter labels by section.
1708 for (const SymbolCU &SCU : ArangeLabels) {
1709 if (SCU.Sym->isInSection()) {
1710 // Make a note of this symbol and it's section.
1711 const MCSection *Section = &SCU.Sym->getSection();
1712 if (!Section->getKind().isMetadata())
1713 SectionMap[Section].push_back(SCU);
1715 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1716 // appear in the output. This sucks as we rely on sections to build
1717 // arange spans. We can do it without, but it's icky.
1718 SectionMap[nullptr].push_back(SCU);
1722 // Add terminating symbols for each section.
1724 for (const auto &I : SectionMap) {
1725 const MCSection *Section = I.first;
1726 MCSymbol *Sym = nullptr;
1729 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1730 // if we know the section name up-front. For user-created sections, the
1731 // resulting label may not be valid to use as a label. (section names can
1732 // use a greater set of characters on some systems)
1733 Sym = Asm->GetTempSymbol("debug_end", ID);
1734 Asm->OutStreamer.SwitchSection(Section);
1735 Asm->OutStreamer.EmitLabel(Sym);
1738 // Insert a final terminator.
1739 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1743 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1745 for (auto &I : SectionMap) {
1746 const MCSection *Section = I.first;
1747 SmallVector<SymbolCU, 8> &List = I.second;
1748 if (List.size() < 2)
1751 // If we have no section (e.g. common), just write out
1752 // individual spans for each symbol.
1754 for (const SymbolCU &Cur : List) {
1756 Span.Start = Cur.Sym;
1759 Spans[Cur.CU].push_back(Span);
1764 // Sort the symbols by offset within the section.
1765 std::sort(List.begin(), List.end(),
1766 [&](const SymbolCU &A, const SymbolCU &B) {
1767 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1768 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1770 // Symbols with no order assigned should be placed at the end.
1771 // (e.g. section end labels)
1779 // Build spans between each label.
1780 const MCSymbol *StartSym = List[0].Sym;
1781 for (size_t n = 1, e = List.size(); n < e; n++) {
1782 const SymbolCU &Prev = List[n - 1];
1783 const SymbolCU &Cur = List[n];
1785 // Try and build the longest span we can within the same CU.
1786 if (Cur.CU != Prev.CU) {
1788 Span.Start = StartSym;
1790 Spans[Prev.CU].push_back(Span);
1796 // Start the dwarf aranges section.
1797 Asm->OutStreamer.SwitchSection(
1798 Asm->getObjFileLowering().getDwarfARangesSection());
1800 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1802 // Build a list of CUs used.
1803 std::vector<DwarfCompileUnit *> CUs;
1804 for (const auto &it : Spans) {
1805 DwarfCompileUnit *CU = it.first;
1809 // Sort the CU list (again, to ensure consistent output order).
1810 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1811 return A->getUniqueID() < B->getUniqueID();
1814 // Emit an arange table for each CU we used.
1815 for (DwarfCompileUnit *CU : CUs) {
1816 std::vector<ArangeSpan> &List = Spans[CU];
1818 // Describe the skeleton CU's offset and length, not the dwo file's.
1819 if (auto *Skel = CU->getSkeleton())
1822 // Emit size of content not including length itself.
1823 unsigned ContentSize =
1824 sizeof(int16_t) + // DWARF ARange version number
1825 sizeof(int32_t) + // Offset of CU in the .debug_info section
1826 sizeof(int8_t) + // Pointer Size (in bytes)
1827 sizeof(int8_t); // Segment Size (in bytes)
1829 unsigned TupleSize = PtrSize * 2;
1831 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1833 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1835 ContentSize += Padding;
1836 ContentSize += (List.size() + 1) * TupleSize;
1838 // For each compile unit, write the list of spans it covers.
1839 Asm->OutStreamer.AddComment("Length of ARange Set");
1840 Asm->EmitInt32(ContentSize);
1841 Asm->OutStreamer.AddComment("DWARF Arange version number");
1842 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1843 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1844 Asm->emitSectionOffset(CU->getLabelBegin());
1845 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1846 Asm->EmitInt8(PtrSize);
1847 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1850 Asm->OutStreamer.EmitFill(Padding, 0xff);
1852 for (const ArangeSpan &Span : List) {
1853 Asm->EmitLabelReference(Span.Start, PtrSize);
1855 // Calculate the size as being from the span start to it's end.
1857 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1859 // For symbols without an end marker (e.g. common), we
1860 // write a single arange entry containing just that one symbol.
1861 uint64_t Size = SymSize[Span.Start];
1865 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1869 Asm->OutStreamer.AddComment("ARange terminator");
1870 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1871 Asm->OutStreamer.EmitIntValue(0, PtrSize);
1875 // Emit visible names into a debug ranges section.
1876 void DwarfDebug::emitDebugRanges() {
1877 // Start the dwarf ranges section.
1878 Asm->OutStreamer.SwitchSection(
1879 Asm->getObjFileLowering().getDwarfRangesSection());
1881 // Size for our labels.
1882 unsigned char Size = Asm->getDataLayout().getPointerSize();
1884 // Grab the specific ranges for the compile units in the module.
1885 for (const auto &I : CUMap) {
1886 DwarfCompileUnit *TheCU = I.second;
1888 if (auto *Skel = TheCU->getSkeleton())
1891 // Iterate over the misc ranges for the compile units in the module.
1892 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1893 // Emit our symbol so we can find the beginning of the range.
1894 Asm->OutStreamer.EmitLabel(List.getSym());
1896 for (const RangeSpan &Range : List.getRanges()) {
1897 const MCSymbol *Begin = Range.getStart();
1898 const MCSymbol *End = Range.getEnd();
1899 assert(Begin && "Range without a begin symbol?");
1900 assert(End && "Range without an end symbol?");
1901 if (auto *Base = TheCU->getBaseAddress()) {
1902 Asm->EmitLabelDifference(Begin, Base, Size);
1903 Asm->EmitLabelDifference(End, Base, Size);
1905 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1906 Asm->OutStreamer.EmitSymbolValue(End, Size);
1910 // And terminate the list with two 0 values.
1911 Asm->OutStreamer.EmitIntValue(0, Size);
1912 Asm->OutStreamer.EmitIntValue(0, Size);
1917 // DWARF5 Experimental Separate Dwarf emitters.
1919 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1920 std::unique_ptr<DwarfUnit> NewU) {
1921 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1922 U.getCUNode().getSplitDebugFilename());
1924 if (!CompilationDir.empty())
1925 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1927 addGnuPubAttributes(*NewU, Die);
1929 SkeletonHolder.addUnit(std::move(NewU));
1932 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1933 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1934 // DW_AT_addr_base, DW_AT_ranges_base.
1935 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1937 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1938 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1939 DwarfCompileUnit &NewCU = *OwnedUnit;
1940 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1942 NewCU.initStmtList();
1944 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1949 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1950 // compile units that would normally be in debug_info.
1951 void DwarfDebug::emitDebugInfoDWO() {
1952 assert(useSplitDwarf() && "No split dwarf debug info?");
1953 // Don't emit relocations into the dwo file.
1954 InfoHolder.emitUnits(/* UseOffsets */ true);
1957 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1958 // abbreviations for the .debug_info.dwo section.
1959 void DwarfDebug::emitDebugAbbrevDWO() {
1960 assert(useSplitDwarf() && "No split dwarf?");
1961 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1964 void DwarfDebug::emitDebugLineDWO() {
1965 assert(useSplitDwarf() && "No split dwarf?");
1966 Asm->OutStreamer.SwitchSection(
1967 Asm->getObjFileLowering().getDwarfLineDWOSection());
1968 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
1971 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1972 // string section and is identical in format to traditional .debug_str
1974 void DwarfDebug::emitDebugStrDWO() {
1975 assert(useSplitDwarf() && "No split dwarf?");
1976 const MCSection *OffSec =
1977 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1978 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1982 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1983 if (!useSplitDwarf())
1986 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
1987 return &SplitTypeUnitFileTable;
1990 static uint64_t makeTypeSignature(StringRef Identifier) {
1992 Hash.update(Identifier);
1993 // ... take the least significant 8 bytes and return those. Our MD5
1994 // implementation always returns its results in little endian, swap bytes
1996 MD5::MD5Result Result;
1998 return support::endian::read64le(Result + 8);
2001 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2002 StringRef Identifier, DIE &RefDie,
2003 DICompositeType CTy) {
2004 // Fast path if we're building some type units and one has already used the
2005 // address pool we know we're going to throw away all this work anyway, so
2006 // don't bother building dependent types.
2007 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2010 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2012 CU.addDIETypeSignature(RefDie, *TU);
2016 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2017 AddrPool.resetUsedFlag();
2019 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2020 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2021 this, &InfoHolder, getDwoLineTable(CU));
2022 DwarfTypeUnit &NewTU = *OwnedUnit;
2023 DIE &UnitDie = NewTU.getUnitDie();
2025 TypeUnitsUnderConstruction.push_back(
2026 std::make_pair(std::move(OwnedUnit), CTy));
2028 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2031 uint64_t Signature = makeTypeSignature(Identifier);
2032 NewTU.setTypeSignature(Signature);
2034 if (useSplitDwarf())
2035 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2037 CU.applyStmtList(UnitDie);
2039 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2042 NewTU.setType(NewTU.createTypeDIE(CTy));
2045 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2046 TypeUnitsUnderConstruction.clear();
2048 // Types referencing entries in the address table cannot be placed in type
2050 if (AddrPool.hasBeenUsed()) {
2052 // Remove all the types built while building this type.
2053 // This is pessimistic as some of these types might not be dependent on
2054 // the type that used an address.
2055 for (const auto &TU : TypeUnitsToAdd)
2056 DwarfTypeUnits.erase(TU.second);
2058 // Construct this type in the CU directly.
2059 // This is inefficient because all the dependent types will be rebuilt
2060 // from scratch, including building them in type units, discovering that
2061 // they depend on addresses, throwing them out and rebuilding them.
2062 CU.constructTypeDIE(RefDie, CTy);
2066 // If the type wasn't dependent on fission addresses, finish adding the type
2067 // and all its dependent types.
2068 for (auto &TU : TypeUnitsToAdd)
2069 InfoHolder.addUnit(std::move(TU.first));
2071 CU.addDIETypeSignature(RefDie, NewTU);
2074 // Accelerator table mutators - add each name along with its companion
2075 // DIE to the proper table while ensuring that the name that we're going
2076 // to reference is in the string table. We do this since the names we
2077 // add may not only be identical to the names in the DIE.
2078 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2079 if (!useDwarfAccelTables())
2081 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2085 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2086 if (!useDwarfAccelTables())
2088 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2092 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2093 if (!useDwarfAccelTables())
2095 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2099 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2100 if (!useDwarfAccelTables())
2102 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),