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"
16 #include "ByteStreamer.h"
17 #include "DwarfCompileUnit.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/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 //===----------------------------------------------------------------------===//
110 /// resolve - Look in the DwarfDebug map for the MDNode that
111 /// corresponds to the reference.
112 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
113 return DD->resolve(Ref);
116 bool DbgVariable::isBlockByrefVariable() const {
117 assert(Var.isVariable() && "Invalid complex DbgVariable!");
118 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type)
154 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156 DIArray Elements = DICompositeType(subType).getElements();
157 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
158 DIDerivedType DT(Elements.getElement(i));
159 if (getName() == DT.getName())
160 return (resolve(DT.getTypeDerivedFrom()));
166 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
167 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
168 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
169 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
172 : Asm(A), MMI(Asm->MMI), FirstCU(nullptr), PrevLabel(nullptr),
173 GlobalRangeCount(0), InfoHolder(A, "info_string", DIEValueAllocator),
174 UsedNonDefaultText(false),
175 SkeletonHolder(A, "skel_string", DIEValueAllocator),
176 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
177 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
178 dwarf::DW_FORM_data4)),
179 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
180 dwarf::DW_FORM_data4)),
181 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
182 dwarf::DW_FORM_data4)),
183 AccelTypes(TypeAtoms) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
187 DwarfLineSectionSym = nullptr;
188 DwarfAddrSectionSym = nullptr;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
190 FunctionBeginSym = FunctionEndSym = nullptr;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
212 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
213 : MMI->getModule()->getDwarfVersion();
215 Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
224 DwarfDebug::~DwarfDebug() { }
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = nullptr) {
230 Asm->OutStreamer.SwitchSection(Section);
234 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
235 Asm->OutStreamer.EmitLabel(TmpSym);
239 static bool isObjCClass(StringRef Name) {
240 return Name.startswith("+") || Name.startswith("-");
243 static bool hasObjCCategory(StringRef Name) {
244 if (!isObjCClass(Name))
247 return Name.find(") ") != StringRef::npos;
250 static void getObjCClassCategory(StringRef In, StringRef &Class,
251 StringRef &Category) {
252 if (!hasObjCCategory(In)) {
253 Class = In.slice(In.find('[') + 1, In.find(' '));
258 Class = In.slice(In.find('[') + 1, In.find('('));
259 Category = In.slice(In.find('[') + 1, In.find(' '));
263 static StringRef getObjCMethodName(StringRef In) {
264 return In.slice(In.find(' ') + 1, In.find(']'));
267 // Helper for sorting sections into a stable output order.
268 static bool SectionSort(const MCSection *A, const MCSection *B) {
269 std::string LA = (A ? A->getLabelBeginName() : "");
270 std::string LB = (B ? B->getLabelBeginName() : "");
274 // Add the various names to the Dwarf accelerator table names.
275 // TODO: Determine whether or not we should add names for programs
276 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
277 // is only slightly different than the lookup of non-standard ObjC names.
278 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
279 if (!SP.isDefinition())
281 addAccelName(SP.getName(), Die);
283 // If the linkage name is different than the name, go ahead and output
284 // that as well into the name table.
285 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
286 addAccelName(SP.getLinkageName(), Die);
288 // If this is an Objective-C selector name add it to the ObjC accelerator
290 if (isObjCClass(SP.getName())) {
291 StringRef Class, Category;
292 getObjCClassCategory(SP.getName(), Class, Category);
293 addAccelObjC(Class, Die);
295 addAccelObjC(Category, Die);
296 // Also add the base method name to the name table.
297 addAccelName(getObjCMethodName(SP.getName()), Die);
301 /// isSubprogramContext - Return true if Context is either a subprogram
302 /// or another context nested inside a subprogram.
303 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
306 DIDescriptor D(Context);
307 if (D.isSubprogram())
310 return isSubprogramContext(resolve(DIType(Context).getContext()));
314 /// Check whether we should create a DIE for the given Scope, return true
315 /// if we don't create a DIE (the corresponding DIE is null).
316 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
317 if (Scope->isAbstractScope())
320 // We don't create a DIE if there is no Range.
321 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
325 if (Ranges.size() > 1)
328 // We don't create a DIE if we have a single Range and the end label
330 return !getLabelAfterInsn(Ranges.front().second);
333 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
334 assert(Scope && Scope->getScopeNode());
335 assert(Scope->isAbstractScope());
336 assert(!Scope->getInlinedAt());
338 const MDNode *SP = Scope->getScopeNode();
340 DIE *&AbsDef = AbstractSPDies[SP];
344 ProcessedSPNodes.insert(SP);
346 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
347 // was inlined from another compile unit.
348 DwarfCompileUnit &SPCU = *SPMap[SP];
350 AbsDef = &SPCU.constructAbstractSubprogramScopeDIE(Scope);
353 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
354 if (!GenerateGnuPubSections)
357 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
360 // Create new DwarfCompileUnit for the given metadata node with tag
361 // DW_TAG_compile_unit.
362 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
363 StringRef FN = DIUnit.getFilename();
364 CompilationDir = DIUnit.getDirectory();
366 auto OwnedUnit = make_unique<DwarfCompileUnit>(
367 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
368 DwarfCompileUnit &NewCU = *OwnedUnit;
369 DIE &Die = NewCU.getUnitDie();
370 InfoHolder.addUnit(std::move(OwnedUnit));
372 // LTO with assembly output shares a single line table amongst multiple CUs.
373 // To avoid the compilation directory being ambiguous, let the line table
374 // explicitly describe the directory of all files, never relying on the
375 // compilation directory.
376 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
377 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
378 NewCU.getUniqueID(), CompilationDir);
380 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
381 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
382 DIUnit.getLanguage());
383 NewCU.addString(Die, dwarf::DW_AT_name, FN);
385 if (!useSplitDwarf()) {
386 NewCU.initStmtList(DwarfLineSectionSym);
388 // If we're using split dwarf the compilation dir is going to be in the
389 // skeleton CU and so we don't need to duplicate it here.
390 if (!CompilationDir.empty())
391 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
393 addGnuPubAttributes(NewCU, Die);
396 if (DIUnit.isOptimized())
397 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
399 StringRef Flags = DIUnit.getFlags();
401 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
403 if (unsigned RVer = DIUnit.getRunTimeVersion())
404 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
405 dwarf::DW_FORM_data1, RVer);
410 if (useSplitDwarf()) {
411 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
412 DwarfInfoDWOSectionSym);
413 NewCU.setSkeleton(constructSkeletonCU(NewCU));
415 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
416 DwarfInfoSectionSym);
418 CUMap.insert(std::make_pair(DIUnit, &NewCU));
419 CUDieMap.insert(std::make_pair(&Die, &NewCU));
423 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
425 DIImportedEntity Module(N);
426 assert(Module.Verify());
427 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
428 D->addChild(TheCU.constructImportedEntityDIE(Module));
431 // Emit all Dwarf sections that should come prior to the content. Create
432 // global DIEs and emit initial debug info sections. This is invoked by
433 // the target AsmPrinter.
434 void DwarfDebug::beginModule() {
435 if (DisableDebugInfoPrinting)
438 const Module *M = MMI->getModule();
440 FunctionDIs = makeSubprogramMap(*M);
442 // If module has named metadata anchors then use them, otherwise scan the
443 // module using debug info finder to collect debug info.
444 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
447 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
449 // Emit initial sections so we can reference labels later.
452 SingleCU = CU_Nodes->getNumOperands() == 1;
454 for (MDNode *N : CU_Nodes->operands()) {
455 DICompileUnit CUNode(N);
456 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
457 DIArray ImportedEntities = CUNode.getImportedEntities();
458 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
459 ScopesWithImportedEntities.push_back(std::make_pair(
460 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
461 ImportedEntities.getElement(i)));
462 std::sort(ScopesWithImportedEntities.begin(),
463 ScopesWithImportedEntities.end(), less_first());
464 DIArray GVs = CUNode.getGlobalVariables();
465 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
466 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
467 DIArray SPs = CUNode.getSubprograms();
468 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
469 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
470 DIArray EnumTypes = CUNode.getEnumTypes();
471 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
472 DIType Ty(EnumTypes.getElement(i));
473 // The enum types array by design contains pointers to
474 // MDNodes rather than DIRefs. Unique them here.
475 DIType UniqueTy(resolve(Ty.getRef()));
476 CU.getOrCreateTypeDIE(UniqueTy);
478 DIArray RetainedTypes = CUNode.getRetainedTypes();
479 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
480 DIType Ty(RetainedTypes.getElement(i));
481 // The retained types array by design contains pointers to
482 // MDNodes rather than DIRefs. Unique them here.
483 DIType UniqueTy(resolve(Ty.getRef()));
484 CU.getOrCreateTypeDIE(UniqueTy);
486 // Emit imported_modules last so that the relevant context is already
488 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
489 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
492 // Tell MMI that we have debug info.
493 MMI->setDebugInfoAvailability(true);
495 // Prime section data.
496 SectionMap[Asm->getObjFileLowering().getTextSection()];
499 void DwarfDebug::finishVariableDefinitions() {
500 for (const auto &Var : ConcreteVariables) {
501 DIE *VariableDie = Var->getDIE();
503 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
504 // in the ConcreteVariables list, rather than looking it up again here.
505 // DIE::getUnit isn't simple - it walks parent pointers, etc.
506 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
508 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
509 if (AbsVar && AbsVar->getDIE()) {
510 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
513 Unit->applyVariableAttributes(*Var, *VariableDie);
517 void DwarfDebug::finishSubprogramDefinitions() {
518 const Module *M = MMI->getModule();
520 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
521 for (MDNode *N : CU_Nodes->operands()) {
522 DICompileUnit TheCU(N);
523 // Construct subprogram DIE and add variables DIEs.
524 DwarfCompileUnit *SPCU =
525 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
526 DIArray Subprograms = TheCU.getSubprograms();
527 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
528 DISubprogram SP(Subprograms.getElement(i));
529 // Perhaps the subprogram is in another CU (such as due to comdat
530 // folding, etc), in which case ignore it here.
531 if (SPMap[SP] != SPCU)
533 SPCU->finishSubprogramDefinition(SP);
539 // Collect info for variables that were optimized out.
540 void DwarfDebug::collectDeadVariables() {
541 const Module *M = MMI->getModule();
543 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
544 for (MDNode *N : CU_Nodes->operands()) {
545 DICompileUnit TheCU(N);
546 // Construct subprogram DIE and add variables DIEs.
547 DwarfCompileUnit *SPCU =
548 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
549 assert(SPCU && "Unable to find Compile Unit!");
550 DIArray Subprograms = TheCU.getSubprograms();
551 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
552 DISubprogram SP(Subprograms.getElement(i));
553 if (ProcessedSPNodes.count(SP) != 0)
555 assert(SP.isSubprogram() &&
556 "CU's subprogram list contains a non-subprogram");
557 assert(SP.isDefinition() &&
558 "CU's subprogram list contains a subprogram declaration");
559 DIArray Variables = SP.getVariables();
560 if (Variables.getNumElements() == 0)
563 DIE *SPDIE = AbstractSPDies.lookup(SP);
565 SPDIE = SPCU->getDIE(SP);
567 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
568 DIVariable DV(Variables.getElement(vi));
569 assert(DV.isVariable());
570 DbgVariable NewVar(DV, DIExpression(nullptr), this);
571 auto VariableDie = SPCU->constructVariableDIE(NewVar);
572 SPCU->applyVariableAttributes(NewVar, *VariableDie);
573 SPDIE->addChild(std::move(VariableDie));
580 void DwarfDebug::finalizeModuleInfo() {
581 finishSubprogramDefinitions();
583 finishVariableDefinitions();
585 // Collect info for variables that were optimized out.
586 collectDeadVariables();
588 // Handle anything that needs to be done on a per-unit basis after
589 // all other generation.
590 for (const auto &TheU : getUnits()) {
591 // Emit DW_AT_containing_type attribute to connect types with their
592 // vtable holding type.
593 TheU->constructContainingTypeDIEs();
595 // Add CU specific attributes if we need to add any.
596 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
597 // If we're splitting the dwarf out now that we've got the entire
598 // CU then add the dwo id to it.
599 DwarfCompileUnit *SkCU =
600 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
601 if (useSplitDwarf()) {
602 // Emit a unique identifier for this CU.
603 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
604 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
605 dwarf::DW_FORM_data8, ID);
606 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
607 dwarf::DW_FORM_data8, ID);
609 // We don't keep track of which addresses are used in which CU so this
610 // is a bit pessimistic under LTO.
611 if (!AddrPool.isEmpty())
612 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
613 DwarfAddrSectionSym, DwarfAddrSectionSym);
614 if (!TheU->getRangeLists().empty())
615 SkCU->addSectionLabel(
616 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
617 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
620 // If we have code split among multiple sections or non-contiguous
621 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
622 // remain in the .o file, otherwise add a DW_AT_low_pc.
623 // FIXME: We should use ranges allow reordering of code ala
624 // .subsections_via_symbols in mach-o. This would mean turning on
625 // ranges for all subprogram DIEs for mach-o.
626 DwarfCompileUnit &U =
627 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
628 unsigned NumRanges = TheU->getRanges().size();
631 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
632 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
633 DwarfDebugRangeSectionSym);
635 // A DW_AT_low_pc attribute may also be specified in combination with
636 // DW_AT_ranges to specify the default base address for use in
637 // location lists (see Section 2.6.2) and range lists (see Section
639 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
642 RangeSpan &Range = TheU->getRanges().back();
643 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
649 // Compute DIE offsets and sizes.
650 InfoHolder.computeSizeAndOffsets();
652 SkeletonHolder.computeSizeAndOffsets();
655 void DwarfDebug::endSections() {
656 // Filter labels by section.
657 for (const SymbolCU &SCU : ArangeLabels) {
658 if (SCU.Sym->isInSection()) {
659 // Make a note of this symbol and it's section.
660 const MCSection *Section = &SCU.Sym->getSection();
661 if (!Section->getKind().isMetadata())
662 SectionMap[Section].push_back(SCU);
664 // Some symbols (e.g. common/bss on mach-o) can have no section but still
665 // appear in the output. This sucks as we rely on sections to build
666 // arange spans. We can do it without, but it's icky.
667 SectionMap[nullptr].push_back(SCU);
671 // Build a list of sections used.
672 std::vector<const MCSection *> Sections;
673 for (const auto &it : SectionMap) {
674 const MCSection *Section = it.first;
675 Sections.push_back(Section);
678 // Sort the sections into order.
679 // This is only done to ensure consistent output order across different runs.
680 std::sort(Sections.begin(), Sections.end(), SectionSort);
682 // Add terminating symbols for each section.
683 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
684 const MCSection *Section = Sections[ID];
685 MCSymbol *Sym = nullptr;
688 // We can't call MCSection::getLabelEndName, as it's only safe to do so
689 // if we know the section name up-front. For user-created sections, the
690 // resulting label may not be valid to use as a label. (section names can
691 // use a greater set of characters on some systems)
692 Sym = Asm->GetTempSymbol("debug_end", ID);
693 Asm->OutStreamer.SwitchSection(Section);
694 Asm->OutStreamer.EmitLabel(Sym);
697 // Insert a final terminator.
698 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
702 // Emit all Dwarf sections that should come after the content.
703 void DwarfDebug::endModule() {
704 assert(CurFn == nullptr);
705 assert(CurMI == nullptr);
710 // End any existing sections.
711 // TODO: Does this need to happen?
714 // Finalize the debug info for the module.
715 finalizeModuleInfo();
719 // Emit all the DIEs into a debug info section.
722 // Corresponding abbreviations into a abbrev section.
725 // Emit info into a debug aranges section.
726 if (GenerateARangeSection)
729 // Emit info into a debug ranges section.
732 if (useSplitDwarf()) {
735 emitDebugAbbrevDWO();
738 // Emit DWO addresses.
739 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
741 // Emit info into a debug loc section.
744 // Emit info into the dwarf accelerator table sections.
745 if (useDwarfAccelTables()) {
748 emitAccelNamespaces();
752 // Emit the pubnames and pubtypes sections if requested.
753 if (HasDwarfPubSections) {
754 emitDebugPubNames(GenerateGnuPubSections);
755 emitDebugPubTypes(GenerateGnuPubSections);
760 AbstractVariables.clear();
762 // Reset these for the next Module if we have one.
766 // Find abstract variable, if any, associated with Var.
767 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
768 DIVariable &Cleansed) {
769 LLVMContext &Ctx = DV->getContext();
770 // More then one inlined variable corresponds to one abstract variable.
771 // FIXME: This duplication of variables when inlining should probably be
772 // removed. It's done to allow each DIVariable to describe its location
773 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
774 // make it accurate then remove this duplication/cleansing stuff.
775 Cleansed = cleanseInlinedVariable(DV, Ctx);
776 auto I = AbstractVariables.find(Cleansed);
777 if (I != AbstractVariables.end())
778 return I->second.get();
782 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
784 return getExistingAbstractVariable(DV, Cleansed);
787 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
788 LexicalScope *Scope) {
789 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
790 addScopeVariable(Scope, AbsDbgVariable.get());
791 AbstractVariables[Var] = std::move(AbsDbgVariable);
794 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
795 const MDNode *ScopeNode) {
796 DIVariable Cleansed = DV;
797 if (getExistingAbstractVariable(DV, Cleansed))
800 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
804 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
805 const MDNode *ScopeNode) {
806 DIVariable Cleansed = DV;
807 if (getExistingAbstractVariable(DV, Cleansed))
810 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
811 createAbstractVariable(Cleansed, Scope);
814 // If Var is a current function argument then add it to CurrentFnArguments list.
815 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
816 if (!LScopes.isCurrentFunctionScope(Scope))
818 DIVariable DV = Var->getVariable();
819 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
821 unsigned ArgNo = DV.getArgNumber();
825 size_t Size = CurrentFnArguments.size();
827 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
828 // llvm::Function argument size is not good indicator of how many
829 // arguments does the function have at source level.
831 CurrentFnArguments.resize(ArgNo * 2);
832 assert(!CurrentFnArguments[ArgNo - 1]);
833 CurrentFnArguments[ArgNo - 1] = Var;
837 // Collect variable information from side table maintained by MMI.
838 void DwarfDebug::collectVariableInfoFromMMITable(
839 SmallPtrSetImpl<const MDNode *> &Processed) {
840 for (const auto &VI : MMI->getVariableDbgInfo()) {
843 Processed.insert(VI.Var);
844 DIVariable DV(VI.Var);
845 DIExpression Expr(VI.Expr);
846 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
848 // If variable scope is not found then skip this variable.
852 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
853 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
854 DbgVariable *RegVar = ConcreteVariables.back().get();
855 RegVar->setFrameIndex(VI.Slot);
856 addScopeVariable(Scope, RegVar);
860 // Get .debug_loc entry for the instruction range starting at MI.
861 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
862 const MDNode *Expr = MI->getDebugExpression();
863 const MDNode *Var = MI->getDebugVariable();
865 assert(MI->getNumOperands() == 4);
866 if (MI->getOperand(0).isReg()) {
867 MachineLocation MLoc;
868 // If the second operand is an immediate, this is a
869 // register-indirect address.
870 if (!MI->getOperand(1).isImm())
871 MLoc.set(MI->getOperand(0).getReg());
873 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
874 return DebugLocEntry::Value(Var, Expr, MLoc);
876 if (MI->getOperand(0).isImm())
877 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
878 if (MI->getOperand(0).isFPImm())
879 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
880 if (MI->getOperand(0).isCImm())
881 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
883 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
886 /// Determine whether two variable pieces overlap.
887 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
888 if (!P1.isVariablePiece() || !P2.isVariablePiece())
890 unsigned l1 = P1.getPieceOffset();
891 unsigned l2 = P2.getPieceOffset();
892 unsigned r1 = l1 + P1.getPieceSize();
893 unsigned r2 = l2 + P2.getPieceSize();
894 // True where [l1,r1[ and [r1,r2[ overlap.
895 return (l1 < r2) && (l2 < r1);
898 /// Build the location list for all DBG_VALUEs in the function that
899 /// describe the same variable. If the ranges of several independent
900 /// pieces of the same variable overlap partially, split them up and
901 /// combine the ranges. The resulting DebugLocEntries are will have
902 /// strict monotonically increasing begin addresses and will never
907 // Ranges History [var, loc, piece ofs size]
908 // 0 | [x, (reg0, piece 0, 32)]
909 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
911 // 3 | [clobber reg0]
912 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
916 // [0-1] [x, (reg0, piece 0, 32)]
917 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
918 // [3-4] [x, (reg1, piece 32, 32)]
919 // [4- ] [x, (mem, piece 0, 64)]
921 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
922 const DbgValueHistoryMap::InstrRanges &Ranges) {
923 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
925 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
926 const MachineInstr *Begin = I->first;
927 const MachineInstr *End = I->second;
928 assert(Begin->isDebugValue() && "Invalid History entry");
930 // Check if a variable is inaccessible in this range.
931 if (Begin->getNumOperands() > 1 &&
932 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
937 // If this piece overlaps with any open ranges, truncate them.
938 DIExpression DIExpr = Begin->getDebugExpression();
939 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
940 [&](DebugLocEntry::Value R) {
941 return piecesOverlap(DIExpr, R.getExpression());
943 OpenRanges.erase(Last, OpenRanges.end());
945 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
946 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
948 const MCSymbol *EndLabel;
950 EndLabel = getLabelAfterInsn(End);
951 else if (std::next(I) == Ranges.end())
952 EndLabel = FunctionEndSym;
954 EndLabel = getLabelBeforeInsn(std::next(I)->first);
955 assert(EndLabel && "Forgot label after instruction ending a range!");
957 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
959 auto Value = getDebugLocValue(Begin);
960 DebugLocEntry Loc(StartLabel, EndLabel, Value);
961 bool couldMerge = false;
963 // If this is a piece, it may belong to the current DebugLocEntry.
964 if (DIExpr.isVariablePiece()) {
965 // Add this value to the list of open ranges.
966 OpenRanges.push_back(Value);
968 // Attempt to add the piece to the last entry.
969 if (!DebugLoc.empty())
970 if (DebugLoc.back().MergeValues(Loc))
975 // Need to add a new DebugLocEntry. Add all values from still
976 // valid non-overlapping pieces.
977 if (OpenRanges.size())
978 Loc.addValues(OpenRanges);
980 DebugLoc.push_back(std::move(Loc));
983 // Attempt to coalesce the ranges of two otherwise identical
985 auto CurEntry = DebugLoc.rbegin();
986 auto PrevEntry = std::next(CurEntry);
987 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
991 dbgs() << CurEntry->getValues().size() << " Values:\n";
992 for (auto Value : CurEntry->getValues()) {
993 Value.getVariable()->dump();
994 Value.getExpression()->dump();
1002 // Find variables for each lexical scope.
1004 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1005 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1006 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1008 // Grab the variable info that was squirreled away in the MMI side-table.
1009 collectVariableInfoFromMMITable(Processed);
1011 for (const auto &I : DbgValues) {
1012 DIVariable DV(I.first);
1013 if (Processed.count(DV))
1016 // Instruction ranges, specifying where DV is accessible.
1017 const auto &Ranges = I.second;
1021 LexicalScope *Scope = nullptr;
1022 if (MDNode *IA = DV.getInlinedAt()) {
1023 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1024 Scope = LScopes.findInlinedScope(DebugLoc::get(
1025 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1027 Scope = LScopes.findLexicalScope(DV.getContext());
1028 // If variable scope is not found then skip this variable.
1032 Processed.insert(DV);
1033 const MachineInstr *MInsn = Ranges.front().first;
1034 assert(MInsn->isDebugValue() && "History must begin with debug value");
1035 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1036 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1037 DbgVariable *RegVar = ConcreteVariables.back().get();
1038 addScopeVariable(Scope, RegVar);
1040 // Check if the first DBG_VALUE is valid for the rest of the function.
1041 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1044 // Handle multiple DBG_VALUE instructions describing one variable.
1045 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1047 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1048 DebugLocList &LocList = DotDebugLocEntries.back();
1051 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1053 // Build the location list for this variable.
1054 buildLocationList(LocList.List, Ranges);
1057 // Collect info for variables that were optimized out.
1058 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1059 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1060 DIVariable DV(Variables.getElement(i));
1061 assert(DV.isVariable());
1062 if (!Processed.insert(DV))
1064 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1065 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1066 DIExpression NoExpr;
1067 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1068 addScopeVariable(Scope, ConcreteVariables.back().get());
1073 // Return Label preceding the instruction.
1074 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1075 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1076 assert(Label && "Didn't insert label before instruction");
1080 // Return Label immediately following the instruction.
1081 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1082 return LabelsAfterInsn.lookup(MI);
1085 // Process beginning of an instruction.
1086 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1087 assert(CurMI == nullptr);
1089 // Check if source location changes, but ignore DBG_VALUE locations.
1090 if (!MI->isDebugValue()) {
1091 DebugLoc DL = MI->getDebugLoc();
1092 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1095 if (DL == PrologEndLoc) {
1096 Flags |= DWARF2_FLAG_PROLOGUE_END;
1097 PrologEndLoc = DebugLoc();
1099 if (PrologEndLoc.isUnknown())
1100 Flags |= DWARF2_FLAG_IS_STMT;
1102 if (!DL.isUnknown()) {
1103 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1104 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1106 recordSourceLine(0, 0, nullptr, 0);
1110 // Insert labels where requested.
1111 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1112 LabelsBeforeInsn.find(MI);
1115 if (I == LabelsBeforeInsn.end())
1118 // Label already assigned.
1123 PrevLabel = MMI->getContext().CreateTempSymbol();
1124 Asm->OutStreamer.EmitLabel(PrevLabel);
1126 I->second = PrevLabel;
1129 // Process end of an instruction.
1130 void DwarfDebug::endInstruction() {
1131 assert(CurMI != nullptr);
1132 // Don't create a new label after DBG_VALUE instructions.
1133 // They don't generate code.
1134 if (!CurMI->isDebugValue())
1135 PrevLabel = nullptr;
1137 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1138 LabelsAfterInsn.find(CurMI);
1142 if (I == LabelsAfterInsn.end())
1145 // Label already assigned.
1149 // We need a label after this instruction.
1151 PrevLabel = MMI->getContext().CreateTempSymbol();
1152 Asm->OutStreamer.EmitLabel(PrevLabel);
1154 I->second = PrevLabel;
1157 // Each LexicalScope has first instruction and last instruction to mark
1158 // beginning and end of a scope respectively. Create an inverse map that list
1159 // scopes starts (and ends) with an instruction. One instruction may start (or
1160 // end) multiple scopes. Ignore scopes that are not reachable.
1161 void DwarfDebug::identifyScopeMarkers() {
1162 SmallVector<LexicalScope *, 4> WorkList;
1163 WorkList.push_back(LScopes.getCurrentFunctionScope());
1164 while (!WorkList.empty()) {
1165 LexicalScope *S = WorkList.pop_back_val();
1167 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1168 if (!Children.empty())
1169 WorkList.append(Children.begin(), Children.end());
1171 if (S->isAbstractScope())
1174 for (const InsnRange &R : S->getRanges()) {
1175 assert(R.first && "InsnRange does not have first instruction!");
1176 assert(R.second && "InsnRange does not have second instruction!");
1177 requestLabelBeforeInsn(R.first);
1178 requestLabelAfterInsn(R.second);
1183 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1184 // First known non-DBG_VALUE and non-frame setup location marks
1185 // the beginning of the function body.
1186 for (const auto &MBB : *MF)
1187 for (const auto &MI : MBB)
1188 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1189 !MI.getDebugLoc().isUnknown())
1190 return MI.getDebugLoc();
1194 // Gather pre-function debug information. Assumes being called immediately
1195 // after the function entry point has been emitted.
1196 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1199 // If there's no debug info for the function we're not going to do anything.
1200 if (!MMI->hasDebugInfo())
1203 auto DI = FunctionDIs.find(MF->getFunction());
1204 if (DI == FunctionDIs.end())
1207 // Grab the lexical scopes for the function, if we don't have any of those
1208 // then we're not going to be able to do anything.
1209 LScopes.initialize(*MF);
1210 if (LScopes.empty())
1213 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1215 // Make sure that each lexical scope will have a begin/end label.
1216 identifyScopeMarkers();
1218 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1219 // belongs to so that we add to the correct per-cu line table in the
1221 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1222 // FnScope->getScopeNode() and DI->second should represent the same function,
1223 // though they may not be the same MDNode due to inline functions merged in
1224 // LTO where the debug info metadata still differs (either due to distinct
1225 // written differences - two versions of a linkonce_odr function
1226 // written/copied into two separate files, or some sub-optimal metadata that
1227 // isn't structurally identical (see: file path/name info from clang, which
1228 // includes the directory of the cpp file being built, even when the file name
1229 // is absolute (such as an <> lookup header)))
1230 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1231 assert(TheCU && "Unable to find compile unit!");
1232 if (Asm->OutStreamer.hasRawTextSupport())
1233 // Use a single line table if we are generating assembly.
1234 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1236 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1238 // Emit a label for the function so that we have a beginning address.
1239 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1240 // Assumes in correct section after the entry point.
1241 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1243 // Calculate history for local variables.
1244 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1247 // Request labels for the full history.
1248 for (const auto &I : DbgValues) {
1249 const auto &Ranges = I.second;
1253 // The first mention of a function argument gets the FunctionBeginSym
1254 // label, so arguments are visible when breaking at function entry.
1255 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1256 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1257 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1258 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1259 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1260 // Mark all non-overlapping initial pieces.
1261 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1262 DIExpression Piece = I->first->getDebugExpression();
1263 if (std::all_of(Ranges.begin(), I,
1264 [&](DbgValueHistoryMap::InstrRange Pred) {
1265 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1267 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1274 for (const auto &Range : Ranges) {
1275 requestLabelBeforeInsn(Range.first);
1277 requestLabelAfterInsn(Range.second);
1281 PrevInstLoc = DebugLoc();
1282 PrevLabel = FunctionBeginSym;
1284 // Record beginning of function.
1285 PrologEndLoc = findPrologueEndLoc(MF);
1286 if (!PrologEndLoc.isUnknown()) {
1287 DebugLoc FnStartDL =
1288 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1290 FnStartDL.getLine(), FnStartDL.getCol(),
1291 FnStartDL.getScope(MF->getFunction()->getContext()),
1292 // We'd like to list the prologue as "not statements" but GDB behaves
1293 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1294 DWARF2_FLAG_IS_STMT);
1298 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1299 if (addCurrentFnArgument(Var, LS))
1301 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1302 DIVariable DV = Var->getVariable();
1303 // Variables with positive arg numbers are parameters.
1304 if (unsigned ArgNum = DV.getArgNumber()) {
1305 // Keep all parameters in order at the start of the variable list to ensure
1306 // function types are correct (no out-of-order parameters)
1308 // This could be improved by only doing it for optimized builds (unoptimized
1309 // builds have the right order to begin with), searching from the back (this
1310 // would catch the unoptimized case quickly), or doing a binary search
1311 // rather than linear search.
1312 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1313 while (I != Vars.end()) {
1314 unsigned CurNum = (*I)->getVariable().getArgNumber();
1315 // A local (non-parameter) variable has been found, insert immediately
1319 // A later indexed parameter has been found, insert immediately before it.
1320 if (CurNum > ArgNum)
1324 Vars.insert(I, Var);
1328 Vars.push_back(Var);
1331 // Gather and emit post-function debug information.
1332 void DwarfDebug::endFunction(const MachineFunction *MF) {
1333 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1334 // though the beginFunction may not be called at all.
1335 // We should handle both cases.
1339 assert(CurFn == MF);
1340 assert(CurFn != nullptr);
1342 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1343 !FunctionDIs.count(MF->getFunction())) {
1344 // If we don't have a lexical scope for this function then there will
1345 // be a hole in the range information. Keep note of this by setting the
1346 // previously used section to nullptr.
1352 // Define end label for subprogram.
1353 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1354 // Assumes in correct section after the entry point.
1355 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1357 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1358 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1360 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1361 collectVariableInfo(ProcessedVars);
1363 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1364 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1366 // Add the range of this function to the list of ranges for the CU.
1367 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1369 // Under -gmlt, skip building the subprogram if there are no inlined
1370 // subroutines inside it.
1371 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1372 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1373 assert(ScopeVariables.empty());
1374 assert(CurrentFnArguments.empty());
1375 assert(DbgValues.empty());
1376 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1377 // by a -gmlt CU. Add a test and remove this assertion.
1378 assert(AbstractVariables.empty());
1379 LabelsBeforeInsn.clear();
1380 LabelsAfterInsn.clear();
1381 PrevLabel = nullptr;
1386 // Construct abstract scopes.
1387 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1388 DISubprogram SP(AScope->getScopeNode());
1389 assert(SP.isSubprogram());
1390 // Collect info for variables that were optimized out.
1391 DIArray Variables = SP.getVariables();
1392 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1393 DIVariable DV(Variables.getElement(i));
1394 assert(DV && DV.isVariable());
1395 if (!ProcessedVars.insert(DV))
1397 ensureAbstractVariableIsCreated(DV, DV.getContext());
1399 constructAbstractSubprogramScopeDIE(AScope);
1402 TheCU.constructSubprogramScopeDIE(FnScope);
1405 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1406 // DbgVariables except those that are also in AbstractVariables (since they
1407 // can be used cross-function)
1408 ScopeVariables.clear();
1409 CurrentFnArguments.clear();
1411 LabelsBeforeInsn.clear();
1412 LabelsAfterInsn.clear();
1413 PrevLabel = nullptr;
1417 // Register a source line with debug info. Returns the unique label that was
1418 // emitted and which provides correspondence to the source line list.
1419 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1424 unsigned Discriminator = 0;
1425 if (DIScope Scope = DIScope(S)) {
1426 assert(Scope.isScope());
1427 Fn = Scope.getFilename();
1428 Dir = Scope.getDirectory();
1429 if (Scope.isLexicalBlockFile())
1430 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1432 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1433 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1434 .getOrCreateSourceID(Fn, Dir);
1436 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1440 //===----------------------------------------------------------------------===//
1442 //===----------------------------------------------------------------------===//
1444 // Emit initial Dwarf sections with a label at the start of each one.
1445 void DwarfDebug::emitSectionLabels() {
1446 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1448 // Dwarf sections base addresses.
1449 DwarfInfoSectionSym =
1450 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1451 if (useSplitDwarf()) {
1452 DwarfInfoDWOSectionSym =
1453 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1454 DwarfTypesDWOSectionSym =
1455 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1457 DwarfAbbrevSectionSym =
1458 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1459 if (useSplitDwarf())
1460 DwarfAbbrevDWOSectionSym = emitSectionSym(
1461 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1462 if (GenerateARangeSection)
1463 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1465 DwarfLineSectionSym =
1466 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1467 if (GenerateGnuPubSections) {
1468 DwarfGnuPubNamesSectionSym =
1469 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1470 DwarfGnuPubTypesSectionSym =
1471 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1472 } else if (HasDwarfPubSections) {
1473 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1474 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1477 DwarfStrSectionSym =
1478 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1479 if (useSplitDwarf()) {
1480 DwarfStrDWOSectionSym =
1481 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1482 DwarfAddrSectionSym =
1483 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1484 DwarfDebugLocSectionSym =
1485 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1487 DwarfDebugLocSectionSym =
1488 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1489 DwarfDebugRangeSectionSym =
1490 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1493 // Recursively emits a debug information entry.
1494 void DwarfDebug::emitDIE(DIE &Die) {
1495 // Get the abbreviation for this DIE.
1496 const DIEAbbrev &Abbrev = Die.getAbbrev();
1498 // Emit the code (index) for the abbreviation.
1499 if (Asm->isVerbose())
1500 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1501 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1502 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1503 dwarf::TagString(Abbrev.getTag()));
1504 Asm->EmitULEB128(Abbrev.getNumber());
1506 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1507 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1509 // Emit the DIE attribute values.
1510 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1511 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1512 dwarf::Form Form = AbbrevData[i].getForm();
1513 assert(Form && "Too many attributes for DIE (check abbreviation)");
1515 if (Asm->isVerbose()) {
1516 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1517 if (Attr == dwarf::DW_AT_accessibility)
1518 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1519 cast<DIEInteger>(Values[i])->getValue()));
1522 // Emit an attribute using the defined form.
1523 Values[i]->EmitValue(Asm, Form);
1526 // Emit the DIE children if any.
1527 if (Abbrev.hasChildren()) {
1528 for (auto &Child : Die.getChildren())
1531 Asm->OutStreamer.AddComment("End Of Children Mark");
1536 // Emit the debug info section.
1537 void DwarfDebug::emitDebugInfo() {
1538 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1540 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1543 // Emit the abbreviation section.
1544 void DwarfDebug::emitAbbreviations() {
1545 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1547 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1550 // Emit the last address of the section and the end of the line matrix.
1551 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1552 // Define last address of section.
1553 Asm->OutStreamer.AddComment("Extended Op");
1556 Asm->OutStreamer.AddComment("Op size");
1557 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1558 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1559 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1561 Asm->OutStreamer.AddComment("Section end label");
1563 Asm->OutStreamer.EmitSymbolValue(
1564 Asm->GetTempSymbol("section_end", SectionEnd),
1565 Asm->getDataLayout().getPointerSize());
1567 // Mark end of matrix.
1568 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1574 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1575 StringRef TableName, StringRef SymName) {
1576 Accel.FinalizeTable(Asm, TableName);
1577 Asm->OutStreamer.SwitchSection(Section);
1578 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1579 Asm->OutStreamer.EmitLabel(SectionBegin);
1581 // Emit the full data.
1582 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1585 // Emit visible names into a hashed accelerator table section.
1586 void DwarfDebug::emitAccelNames() {
1587 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1588 "Names", "names_begin");
1591 // Emit objective C classes and categories into a hashed accelerator table
1593 void DwarfDebug::emitAccelObjC() {
1594 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1595 "ObjC", "objc_begin");
1598 // Emit namespace dies into a hashed accelerator table.
1599 void DwarfDebug::emitAccelNamespaces() {
1600 emitAccel(AccelNamespace,
1601 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1602 "namespac", "namespac_begin");
1605 // Emit type dies into a hashed accelerator table.
1606 void DwarfDebug::emitAccelTypes() {
1607 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1608 "types", "types_begin");
1611 // Public name handling.
1612 // The format for the various pubnames:
1614 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1615 // for the DIE that is named.
1617 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1618 // into the CU and the index value is computed according to the type of value
1619 // for the DIE that is named.
1621 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1622 // it's the offset within the debug_info/debug_types dwo section, however, the
1623 // reference in the pubname header doesn't change.
1625 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1626 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1628 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1630 // We could have a specification DIE that has our most of our knowledge,
1631 // look for that now.
1632 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1634 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1635 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1636 Linkage = dwarf::GIEL_EXTERNAL;
1637 } else if (Die->findAttribute(dwarf::DW_AT_external))
1638 Linkage = dwarf::GIEL_EXTERNAL;
1640 switch (Die->getTag()) {
1641 case dwarf::DW_TAG_class_type:
1642 case dwarf::DW_TAG_structure_type:
1643 case dwarf::DW_TAG_union_type:
1644 case dwarf::DW_TAG_enumeration_type:
1645 return dwarf::PubIndexEntryDescriptor(
1646 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1647 ? dwarf::GIEL_STATIC
1648 : dwarf::GIEL_EXTERNAL);
1649 case dwarf::DW_TAG_typedef:
1650 case dwarf::DW_TAG_base_type:
1651 case dwarf::DW_TAG_subrange_type:
1652 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1653 case dwarf::DW_TAG_namespace:
1654 return dwarf::GIEK_TYPE;
1655 case dwarf::DW_TAG_subprogram:
1656 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1657 case dwarf::DW_TAG_constant:
1658 case dwarf::DW_TAG_variable:
1659 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1660 case dwarf::DW_TAG_enumerator:
1661 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1662 dwarf::GIEL_STATIC);
1664 return dwarf::GIEK_NONE;
1668 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1670 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1671 const MCSection *PSec =
1672 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1673 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1675 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1678 void DwarfDebug::emitDebugPubSection(
1679 bool GnuStyle, const MCSection *PSec, StringRef Name,
1680 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1681 for (const auto &NU : CUMap) {
1682 DwarfCompileUnit *TheU = NU.second;
1684 const auto &Globals = (TheU->*Accessor)();
1686 if (Globals.empty())
1689 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1691 unsigned ID = TheU->getUniqueID();
1693 // Start the dwarf pubnames section.
1694 Asm->OutStreamer.SwitchSection(PSec);
1697 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1698 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1699 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1700 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1702 Asm->OutStreamer.EmitLabel(BeginLabel);
1704 Asm->OutStreamer.AddComment("DWARF Version");
1705 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1707 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1708 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1710 Asm->OutStreamer.AddComment("Compilation Unit Length");
1711 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1713 // Emit the pubnames for this compilation unit.
1714 for (const auto &GI : Globals) {
1715 const char *Name = GI.getKeyData();
1716 const DIE *Entity = GI.second;
1718 Asm->OutStreamer.AddComment("DIE offset");
1719 Asm->EmitInt32(Entity->getOffset());
1722 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1723 Asm->OutStreamer.AddComment(
1724 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1725 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1726 Asm->EmitInt8(Desc.toBits());
1729 Asm->OutStreamer.AddComment("External Name");
1730 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1733 Asm->OutStreamer.AddComment("End Mark");
1735 Asm->OutStreamer.EmitLabel(EndLabel);
1739 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1740 const MCSection *PSec =
1741 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1742 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1744 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1747 // Emit visible names into a debug str section.
1748 void DwarfDebug::emitDebugStr() {
1749 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1750 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1753 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1754 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1755 const DITypeIdentifierMap &Map,
1756 ArrayRef<DebugLocEntry::Value> Values) {
1757 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1758 return P.isVariablePiece();
1759 }) && "all values are expected to be pieces");
1760 assert(std::is_sorted(Values.begin(), Values.end()) &&
1761 "pieces are expected to be sorted");
1763 unsigned Offset = 0;
1764 for (auto Piece : Values) {
1765 DIExpression Expr = Piece.getExpression();
1766 unsigned PieceOffset = Expr.getPieceOffset();
1767 unsigned PieceSize = Expr.getPieceSize();
1768 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1769 if (Offset < PieceOffset) {
1770 // The DWARF spec seriously mandates pieces with no locations for gaps.
1771 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1772 Offset += PieceOffset-Offset;
1775 Offset += PieceSize;
1777 const unsigned SizeOfByte = 8;
1779 DIVariable Var = Piece.getVariable();
1780 assert(!Var.isIndirect() && "indirect address for piece");
1781 unsigned VarSize = Var.getSizeInBits(Map);
1782 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1783 && "piece is larger than or outside of variable");
1784 assert(PieceSize*SizeOfByte != VarSize
1785 && "piece covers entire variable");
1787 if (Piece.isLocation() && Piece.getLoc().isReg())
1788 Asm->EmitDwarfRegOpPiece(Streamer,
1790 PieceSize*SizeOfByte);
1792 emitDebugLocValue(Streamer, Piece);
1793 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1799 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1800 const DebugLocEntry &Entry) {
1801 const DebugLocEntry::Value Value = Entry.getValues()[0];
1802 if (Value.isVariablePiece())
1803 // Emit all pieces that belong to the same variable and range.
1804 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1806 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1807 emitDebugLocValue(Streamer, Value);
1810 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1811 const DebugLocEntry::Value &Value) {
1812 DIVariable DV = Value.getVariable();
1814 if (Value.isInt()) {
1815 DIBasicType BTy(resolve(DV.getType()));
1816 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1817 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1818 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1819 Streamer.EmitSLEB128(Value.getInt());
1821 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1822 Streamer.EmitULEB128(Value.getInt());
1824 } else if (Value.isLocation()) {
1825 MachineLocation Loc = Value.getLoc();
1826 DIExpression Expr = Value.getExpression();
1829 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1831 // Complex address entry.
1832 unsigned N = Expr.getNumElements();
1834 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1835 if (Loc.getOffset()) {
1837 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1838 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1839 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1840 Streamer.EmitSLEB128(Expr.getElement(1));
1842 // If first address element is OpPlus then emit
1843 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1844 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1845 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1849 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1852 // Emit remaining complex address elements.
1853 for (; i < N; ++i) {
1854 uint64_t Element = Expr.getElement(i);
1855 if (Element == dwarf::DW_OP_plus) {
1856 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1857 Streamer.EmitULEB128(Expr.getElement(++i));
1858 } else if (Element == dwarf::DW_OP_deref) {
1860 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1861 } else if (Element == dwarf::DW_OP_piece) {
1863 // handled in emitDebugLocEntry.
1865 llvm_unreachable("unknown Opcode found in complex address");
1869 // else ... ignore constant fp. There is not any good way to
1870 // to represent them here in dwarf.
1874 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1875 Asm->OutStreamer.AddComment("Loc expr size");
1876 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1877 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1878 Asm->EmitLabelDifference(end, begin, 2);
1879 Asm->OutStreamer.EmitLabel(begin);
1881 APByteStreamer Streamer(*Asm);
1882 emitDebugLocEntry(Streamer, Entry);
1884 Asm->OutStreamer.EmitLabel(end);
1887 // Emit locations into the debug loc section.
1888 void DwarfDebug::emitDebugLoc() {
1889 // Start the dwarf loc section.
1890 Asm->OutStreamer.SwitchSection(
1891 Asm->getObjFileLowering().getDwarfLocSection());
1892 unsigned char Size = Asm->getDataLayout().getPointerSize();
1893 for (const auto &DebugLoc : DotDebugLocEntries) {
1894 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1895 const DwarfCompileUnit *CU = DebugLoc.CU;
1896 assert(!CU->getRanges().empty());
1897 for (const auto &Entry : DebugLoc.List) {
1898 // Set up the range. This range is relative to the entry point of the
1899 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1900 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1901 if (CU->getRanges().size() == 1) {
1902 // Grab the begin symbol from the first range as our base.
1903 const MCSymbol *Base = CU->getRanges()[0].getStart();
1904 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1905 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1907 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1908 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1911 emitDebugLocEntryLocation(Entry);
1913 Asm->OutStreamer.EmitIntValue(0, Size);
1914 Asm->OutStreamer.EmitIntValue(0, Size);
1918 void DwarfDebug::emitDebugLocDWO() {
1919 Asm->OutStreamer.SwitchSection(
1920 Asm->getObjFileLowering().getDwarfLocDWOSection());
1921 for (const auto &DebugLoc : DotDebugLocEntries) {
1922 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1923 for (const auto &Entry : DebugLoc.List) {
1924 // Just always use start_length for now - at least that's one address
1925 // rather than two. We could get fancier and try to, say, reuse an
1926 // address we know we've emitted elsewhere (the start of the function?
1927 // The start of the CU or CU subrange that encloses this range?)
1928 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1929 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1930 Asm->EmitULEB128(idx);
1931 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1933 emitDebugLocEntryLocation(Entry);
1935 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1940 const MCSymbol *Start, *End;
1943 // Emit a debug aranges section, containing a CU lookup for any
1944 // address we can tie back to a CU.
1945 void DwarfDebug::emitDebugARanges() {
1946 // Start the dwarf aranges section.
1947 Asm->OutStreamer.SwitchSection(
1948 Asm->getObjFileLowering().getDwarfARangesSection());
1950 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1954 // Build a list of sections used.
1955 std::vector<const MCSection *> Sections;
1956 for (const auto &it : SectionMap) {
1957 const MCSection *Section = it.first;
1958 Sections.push_back(Section);
1961 // Sort the sections into order.
1962 // This is only done to ensure consistent output order across different runs.
1963 std::sort(Sections.begin(), Sections.end(), SectionSort);
1965 // Build a set of address spans, sorted by CU.
1966 for (const MCSection *Section : Sections) {
1967 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1968 if (List.size() < 2)
1971 // Sort the symbols by offset within the section.
1972 std::sort(List.begin(), List.end(),
1973 [&](const SymbolCU &A, const SymbolCU &B) {
1974 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1975 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1977 // Symbols with no order assigned should be placed at the end.
1978 // (e.g. section end labels)
1986 // If we have no section (e.g. common), just write out
1987 // individual spans for each symbol.
1989 for (const SymbolCU &Cur : List) {
1991 Span.Start = Cur.Sym;
1994 Spans[Cur.CU].push_back(Span);
1997 // Build spans between each label.
1998 const MCSymbol *StartSym = List[0].Sym;
1999 for (size_t n = 1, e = List.size(); n < e; n++) {
2000 const SymbolCU &Prev = List[n - 1];
2001 const SymbolCU &Cur = List[n];
2003 // Try and build the longest span we can within the same CU.
2004 if (Cur.CU != Prev.CU) {
2006 Span.Start = StartSym;
2008 Spans[Prev.CU].push_back(Span);
2015 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2017 // Build a list of CUs used.
2018 std::vector<DwarfCompileUnit *> CUs;
2019 for (const auto &it : Spans) {
2020 DwarfCompileUnit *CU = it.first;
2024 // Sort the CU list (again, to ensure consistent output order).
2025 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2026 return A->getUniqueID() < B->getUniqueID();
2029 // Emit an arange table for each CU we used.
2030 for (DwarfCompileUnit *CU : CUs) {
2031 std::vector<ArangeSpan> &List = Spans[CU];
2033 // Emit size of content not including length itself.
2034 unsigned ContentSize =
2035 sizeof(int16_t) + // DWARF ARange version number
2036 sizeof(int32_t) + // Offset of CU in the .debug_info section
2037 sizeof(int8_t) + // Pointer Size (in bytes)
2038 sizeof(int8_t); // Segment Size (in bytes)
2040 unsigned TupleSize = PtrSize * 2;
2042 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2044 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2046 ContentSize += Padding;
2047 ContentSize += (List.size() + 1) * TupleSize;
2049 // For each compile unit, write the list of spans it covers.
2050 Asm->OutStreamer.AddComment("Length of ARange Set");
2051 Asm->EmitInt32(ContentSize);
2052 Asm->OutStreamer.AddComment("DWARF Arange version number");
2053 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2054 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2055 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2056 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2057 Asm->EmitInt8(PtrSize);
2058 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2061 Asm->OutStreamer.EmitFill(Padding, 0xff);
2063 for (const ArangeSpan &Span : List) {
2064 Asm->EmitLabelReference(Span.Start, PtrSize);
2066 // Calculate the size as being from the span start to it's end.
2068 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2070 // For symbols without an end marker (e.g. common), we
2071 // write a single arange entry containing just that one symbol.
2072 uint64_t Size = SymSize[Span.Start];
2076 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2080 Asm->OutStreamer.AddComment("ARange terminator");
2081 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2082 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2086 // Emit visible names into a debug ranges section.
2087 void DwarfDebug::emitDebugRanges() {
2088 // Start the dwarf ranges section.
2089 Asm->OutStreamer.SwitchSection(
2090 Asm->getObjFileLowering().getDwarfRangesSection());
2092 // Size for our labels.
2093 unsigned char Size = Asm->getDataLayout().getPointerSize();
2095 // Grab the specific ranges for the compile units in the module.
2096 for (const auto &I : CUMap) {
2097 DwarfCompileUnit *TheCU = I.second;
2099 // Iterate over the misc ranges for the compile units in the module.
2100 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2101 // Emit our symbol so we can find the beginning of the range.
2102 Asm->OutStreamer.EmitLabel(List.getSym());
2104 for (const RangeSpan &Range : List.getRanges()) {
2105 const MCSymbol *Begin = Range.getStart();
2106 const MCSymbol *End = Range.getEnd();
2107 assert(Begin && "Range without a begin symbol?");
2108 assert(End && "Range without an end symbol?");
2109 if (TheCU->getRanges().size() == 1) {
2110 // Grab the begin symbol from the first range as our base.
2111 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2112 Asm->EmitLabelDifference(Begin, Base, Size);
2113 Asm->EmitLabelDifference(End, Base, Size);
2115 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2116 Asm->OutStreamer.EmitSymbolValue(End, Size);
2120 // And terminate the list with two 0 values.
2121 Asm->OutStreamer.EmitIntValue(0, Size);
2122 Asm->OutStreamer.EmitIntValue(0, Size);
2125 // Now emit a range for the CU itself.
2126 if (TheCU->getRanges().size() > 1) {
2127 Asm->OutStreamer.EmitLabel(
2128 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2129 for (const RangeSpan &Range : TheCU->getRanges()) {
2130 const MCSymbol *Begin = Range.getStart();
2131 const MCSymbol *End = Range.getEnd();
2132 assert(Begin && "Range without a begin symbol?");
2133 assert(End && "Range without an end symbol?");
2134 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2135 Asm->OutStreamer.EmitSymbolValue(End, Size);
2137 // And terminate the list with two 0 values.
2138 Asm->OutStreamer.EmitIntValue(0, Size);
2139 Asm->OutStreamer.EmitIntValue(0, Size);
2144 // DWARF5 Experimental Separate Dwarf emitters.
2146 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2147 std::unique_ptr<DwarfUnit> NewU) {
2148 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2149 U.getCUNode().getSplitDebugFilename());
2151 if (!CompilationDir.empty())
2152 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2154 addGnuPubAttributes(*NewU, Die);
2156 SkeletonHolder.addUnit(std::move(NewU));
2159 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2160 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2161 // DW_AT_addr_base, DW_AT_ranges_base.
2162 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2164 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2165 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2166 DwarfCompileUnit &NewCU = *OwnedUnit;
2167 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2168 DwarfInfoSectionSym);
2170 NewCU.initStmtList(DwarfLineSectionSym);
2172 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2177 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2178 // compile units that would normally be in debug_info.
2179 void DwarfDebug::emitDebugInfoDWO() {
2180 assert(useSplitDwarf() && "No split dwarf debug info?");
2181 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2182 // emit relocations into the dwo file.
2183 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2186 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2187 // abbreviations for the .debug_info.dwo section.
2188 void DwarfDebug::emitDebugAbbrevDWO() {
2189 assert(useSplitDwarf() && "No split dwarf?");
2190 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2193 void DwarfDebug::emitDebugLineDWO() {
2194 assert(useSplitDwarf() && "No split dwarf?");
2195 Asm->OutStreamer.SwitchSection(
2196 Asm->getObjFileLowering().getDwarfLineDWOSection());
2197 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2200 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2201 // string section and is identical in format to traditional .debug_str
2203 void DwarfDebug::emitDebugStrDWO() {
2204 assert(useSplitDwarf() && "No split dwarf?");
2205 const MCSection *OffSec =
2206 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2207 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2211 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2212 if (!useSplitDwarf())
2215 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2216 return &SplitTypeUnitFileTable;
2219 static uint64_t makeTypeSignature(StringRef Identifier) {
2221 Hash.update(Identifier);
2222 // ... take the least significant 8 bytes and return those. Our MD5
2223 // implementation always returns its results in little endian, swap bytes
2225 MD5::MD5Result Result;
2227 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2230 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2231 StringRef Identifier, DIE &RefDie,
2232 DICompositeType CTy) {
2233 // Fast path if we're building some type units and one has already used the
2234 // address pool we know we're going to throw away all this work anyway, so
2235 // don't bother building dependent types.
2236 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2239 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2241 CU.addDIETypeSignature(RefDie, *TU);
2245 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2246 AddrPool.resetUsedFlag();
2248 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2249 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2250 this, &InfoHolder, getDwoLineTable(CU));
2251 DwarfTypeUnit &NewTU = *OwnedUnit;
2252 DIE &UnitDie = NewTU.getUnitDie();
2254 TypeUnitsUnderConstruction.push_back(
2255 std::make_pair(std::move(OwnedUnit), CTy));
2257 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2260 uint64_t Signature = makeTypeSignature(Identifier);
2261 NewTU.setTypeSignature(Signature);
2263 if (useSplitDwarf())
2264 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2265 DwarfTypesDWOSectionSym);
2267 CU.applyStmtList(UnitDie);
2269 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2272 NewTU.setType(NewTU.createTypeDIE(CTy));
2275 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2276 TypeUnitsUnderConstruction.clear();
2278 // Types referencing entries in the address table cannot be placed in type
2280 if (AddrPool.hasBeenUsed()) {
2282 // Remove all the types built while building this type.
2283 // This is pessimistic as some of these types might not be dependent on
2284 // the type that used an address.
2285 for (const auto &TU : TypeUnitsToAdd)
2286 DwarfTypeUnits.erase(TU.second);
2288 // Construct this type in the CU directly.
2289 // This is inefficient because all the dependent types will be rebuilt
2290 // from scratch, including building them in type units, discovering that
2291 // they depend on addresses, throwing them out and rebuilding them.
2292 CU.constructTypeDIE(RefDie, CTy);
2296 // If the type wasn't dependent on fission addresses, finish adding the type
2297 // and all its dependent types.
2298 for (auto &TU : TypeUnitsToAdd)
2299 InfoHolder.addUnit(std::move(TU.first));
2301 CU.addDIETypeSignature(RefDie, NewTU);
2304 // Accelerator table mutators - add each name along with its companion
2305 // DIE to the proper table while ensuring that the name that we're going
2306 // to reference is in the string table. We do this since the names we
2307 // add may not only be identical to the names in the DIE.
2308 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2309 if (!useDwarfAccelTables())
2311 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2315 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2316 if (!useDwarfAccelTables())
2318 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2322 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2323 if (!useDwarfAccelTables())
2325 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2329 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2330 if (!useDwarfAccelTables())
2332 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),