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 AbsDef = &SPMap[SP]->constructAbstractSubprogramScopeDIE(Scope);
351 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
352 if (!GenerateGnuPubSections)
355 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
358 // Create new DwarfCompileUnit for the given metadata node with tag
359 // DW_TAG_compile_unit.
360 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
361 StringRef FN = DIUnit.getFilename();
362 CompilationDir = DIUnit.getDirectory();
364 auto OwnedUnit = make_unique<DwarfCompileUnit>(
365 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
366 DwarfCompileUnit &NewCU = *OwnedUnit;
367 DIE &Die = NewCU.getUnitDie();
368 InfoHolder.addUnit(std::move(OwnedUnit));
370 // LTO with assembly output shares a single line table amongst multiple CUs.
371 // To avoid the compilation directory being ambiguous, let the line table
372 // explicitly describe the directory of all files, never relying on the
373 // compilation directory.
374 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
375 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
376 NewCU.getUniqueID(), CompilationDir);
378 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
379 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
380 DIUnit.getLanguage());
381 NewCU.addString(Die, dwarf::DW_AT_name, FN);
383 if (!useSplitDwarf()) {
384 NewCU.initStmtList(DwarfLineSectionSym);
386 // If we're using split dwarf the compilation dir is going to be in the
387 // skeleton CU and so we don't need to duplicate it here.
388 if (!CompilationDir.empty())
389 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
391 addGnuPubAttributes(NewCU, Die);
394 if (DIUnit.isOptimized())
395 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
397 StringRef Flags = DIUnit.getFlags();
399 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
401 if (unsigned RVer = DIUnit.getRunTimeVersion())
402 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
403 dwarf::DW_FORM_data1, RVer);
408 if (useSplitDwarf()) {
409 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
410 DwarfInfoDWOSectionSym);
411 NewCU.setSkeleton(constructSkeletonCU(NewCU));
413 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
414 DwarfInfoSectionSym);
416 CUMap.insert(std::make_pair(DIUnit, &NewCU));
417 CUDieMap.insert(std::make_pair(&Die, &NewCU));
421 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
423 DIImportedEntity Module(N);
424 assert(Module.Verify());
425 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
426 D->addChild(TheCU.constructImportedEntityDIE(Module));
429 // Emit all Dwarf sections that should come prior to the content. Create
430 // global DIEs and emit initial debug info sections. This is invoked by
431 // the target AsmPrinter.
432 void DwarfDebug::beginModule() {
433 if (DisableDebugInfoPrinting)
436 const Module *M = MMI->getModule();
438 FunctionDIs = makeSubprogramMap(*M);
440 // If module has named metadata anchors then use them, otherwise scan the
441 // module using debug info finder to collect debug info.
442 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
445 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
447 // Emit initial sections so we can reference labels later.
450 SingleCU = CU_Nodes->getNumOperands() == 1;
452 for (MDNode *N : CU_Nodes->operands()) {
453 DICompileUnit CUNode(N);
454 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
455 DIArray ImportedEntities = CUNode.getImportedEntities();
456 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
457 ScopesWithImportedEntities.push_back(std::make_pair(
458 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
459 ImportedEntities.getElement(i)));
460 std::sort(ScopesWithImportedEntities.begin(),
461 ScopesWithImportedEntities.end(), less_first());
462 DIArray GVs = CUNode.getGlobalVariables();
463 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
464 CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
465 DIArray SPs = CUNode.getSubprograms();
466 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
467 SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
468 DIArray EnumTypes = CUNode.getEnumTypes();
469 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
470 DIType Ty(EnumTypes.getElement(i));
471 // The enum types array by design contains pointers to
472 // MDNodes rather than DIRefs. Unique them here.
473 DIType UniqueTy(resolve(Ty.getRef()));
474 CU.getOrCreateTypeDIE(UniqueTy);
476 DIArray RetainedTypes = CUNode.getRetainedTypes();
477 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
478 DIType Ty(RetainedTypes.getElement(i));
479 // The retained 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 // Emit imported_modules last so that the relevant context is already
486 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
487 constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
490 // Tell MMI that we have debug info.
491 MMI->setDebugInfoAvailability(true);
493 // Prime section data.
494 SectionMap[Asm->getObjFileLowering().getTextSection()];
497 void DwarfDebug::finishVariableDefinitions() {
498 for (const auto &Var : ConcreteVariables) {
499 DIE *VariableDie = Var->getDIE();
501 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
502 // in the ConcreteVariables list, rather than looking it up again here.
503 // DIE::getUnit isn't simple - it walks parent pointers, etc.
504 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
506 DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
507 if (AbsVar && AbsVar->getDIE()) {
508 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
511 Unit->applyVariableAttributes(*Var, *VariableDie);
515 void DwarfDebug::finishSubprogramDefinitions() {
516 for (const auto &P : SPMap)
517 P.second->finishSubprogramDefinition(DISubprogram(P.first));
521 // Collect info for variables that were optimized out.
522 void DwarfDebug::collectDeadVariables() {
523 const Module *M = MMI->getModule();
525 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
526 for (MDNode *N : CU_Nodes->operands()) {
527 DICompileUnit TheCU(N);
528 // Construct subprogram DIE and add variables DIEs.
529 DwarfCompileUnit *SPCU =
530 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
531 assert(SPCU && "Unable to find Compile Unit!");
532 DIArray Subprograms = TheCU.getSubprograms();
533 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
534 DISubprogram SP(Subprograms.getElement(i));
535 if (ProcessedSPNodes.count(SP) != 0)
537 assert(SP.isSubprogram() &&
538 "CU's subprogram list contains a non-subprogram");
539 assert(SP.isDefinition() &&
540 "CU's subprogram list contains a subprogram declaration");
541 DIArray Variables = SP.getVariables();
542 if (Variables.getNumElements() == 0)
545 DIE *SPDIE = AbstractSPDies.lookup(SP);
547 SPDIE = SPCU->getDIE(SP);
549 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
550 DIVariable DV(Variables.getElement(vi));
551 assert(DV.isVariable());
552 DbgVariable NewVar(DV, DIExpression(nullptr), this);
553 auto VariableDie = SPCU->constructVariableDIE(NewVar);
554 SPCU->applyVariableAttributes(NewVar, *VariableDie);
555 SPDIE->addChild(std::move(VariableDie));
562 void DwarfDebug::finalizeModuleInfo() {
563 finishSubprogramDefinitions();
565 finishVariableDefinitions();
567 // Collect info for variables that were optimized out.
568 collectDeadVariables();
570 // Handle anything that needs to be done on a per-unit basis after
571 // all other generation.
572 for (const auto &TheU : getUnits()) {
573 // Emit DW_AT_containing_type attribute to connect types with their
574 // vtable holding type.
575 TheU->constructContainingTypeDIEs();
577 // Add CU specific attributes if we need to add any.
578 if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
579 // If we're splitting the dwarf out now that we've got the entire
580 // CU then add the dwo id to it.
581 DwarfCompileUnit *SkCU =
582 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
583 if (useSplitDwarf()) {
584 // Emit a unique identifier for this CU.
585 uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
586 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
587 dwarf::DW_FORM_data8, ID);
588 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
589 dwarf::DW_FORM_data8, ID);
591 // We don't keep track of which addresses are used in which CU so this
592 // is a bit pessimistic under LTO.
593 if (!AddrPool.isEmpty())
594 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
595 DwarfAddrSectionSym, DwarfAddrSectionSym);
596 if (!TheU->getRangeLists().empty())
597 SkCU->addSectionLabel(
598 SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
599 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
602 // If we have code split among multiple sections or non-contiguous
603 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
604 // remain in the .o file, otherwise add a DW_AT_low_pc.
605 // FIXME: We should use ranges allow reordering of code ala
606 // .subsections_via_symbols in mach-o. This would mean turning on
607 // ranges for all subprogram DIEs for mach-o.
608 DwarfCompileUnit &U =
609 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
610 unsigned NumRanges = TheU->getRanges().size();
613 U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_ranges,
614 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
615 DwarfDebugRangeSectionSym);
617 // A DW_AT_low_pc attribute may also be specified in combination with
618 // DW_AT_ranges to specify the default base address for use in
619 // location lists (see Section 2.6.2) and range lists (see Section
621 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
624 RangeSpan &Range = TheU->getRanges().back();
625 U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
631 // Compute DIE offsets and sizes.
632 InfoHolder.computeSizeAndOffsets();
634 SkeletonHolder.computeSizeAndOffsets();
637 void DwarfDebug::endSections() {
638 // Filter labels by section.
639 for (const SymbolCU &SCU : ArangeLabels) {
640 if (SCU.Sym->isInSection()) {
641 // Make a note of this symbol and it's section.
642 const MCSection *Section = &SCU.Sym->getSection();
643 if (!Section->getKind().isMetadata())
644 SectionMap[Section].push_back(SCU);
646 // Some symbols (e.g. common/bss on mach-o) can have no section but still
647 // appear in the output. This sucks as we rely on sections to build
648 // arange spans. We can do it without, but it's icky.
649 SectionMap[nullptr].push_back(SCU);
653 // Build a list of sections used.
654 std::vector<const MCSection *> Sections;
655 for (const auto &it : SectionMap) {
656 const MCSection *Section = it.first;
657 Sections.push_back(Section);
660 // Sort the sections into order.
661 // This is only done to ensure consistent output order across different runs.
662 std::sort(Sections.begin(), Sections.end(), SectionSort);
664 // Add terminating symbols for each section.
665 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
666 const MCSection *Section = Sections[ID];
667 MCSymbol *Sym = nullptr;
670 // We can't call MCSection::getLabelEndName, as it's only safe to do so
671 // if we know the section name up-front. For user-created sections, the
672 // resulting label may not be valid to use as a label. (section names can
673 // use a greater set of characters on some systems)
674 Sym = Asm->GetTempSymbol("debug_end", ID);
675 Asm->OutStreamer.SwitchSection(Section);
676 Asm->OutStreamer.EmitLabel(Sym);
679 // Insert a final terminator.
680 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
684 // Emit all Dwarf sections that should come after the content.
685 void DwarfDebug::endModule() {
686 assert(CurFn == nullptr);
687 assert(CurMI == nullptr);
692 // End any existing sections.
693 // TODO: Does this need to happen?
696 // Finalize the debug info for the module.
697 finalizeModuleInfo();
701 // Emit all the DIEs into a debug info section.
704 // Corresponding abbreviations into a abbrev section.
707 // Emit info into a debug aranges section.
708 if (GenerateARangeSection)
711 // Emit info into a debug ranges section.
714 if (useSplitDwarf()) {
717 emitDebugAbbrevDWO();
720 // Emit DWO addresses.
721 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
723 // Emit info into a debug loc section.
726 // Emit info into the dwarf accelerator table sections.
727 if (useDwarfAccelTables()) {
730 emitAccelNamespaces();
734 // Emit the pubnames and pubtypes sections if requested.
735 if (HasDwarfPubSections) {
736 emitDebugPubNames(GenerateGnuPubSections);
737 emitDebugPubTypes(GenerateGnuPubSections);
742 AbstractVariables.clear();
744 // Reset these for the next Module if we have one.
748 // Find abstract variable, if any, associated with Var.
749 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
750 DIVariable &Cleansed) {
751 LLVMContext &Ctx = DV->getContext();
752 // More then one inlined variable corresponds to one abstract variable.
753 // FIXME: This duplication of variables when inlining should probably be
754 // removed. It's done to allow each DIVariable to describe its location
755 // because the DebugLoc on the dbg.value/declare isn't accurate. We should
756 // make it accurate then remove this duplication/cleansing stuff.
757 Cleansed = cleanseInlinedVariable(DV, Ctx);
758 auto I = AbstractVariables.find(Cleansed);
759 if (I != AbstractVariables.end())
760 return I->second.get();
764 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
766 return getExistingAbstractVariable(DV, Cleansed);
769 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
770 LexicalScope *Scope) {
771 auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
772 addScopeVariable(Scope, AbsDbgVariable.get());
773 AbstractVariables[Var] = std::move(AbsDbgVariable);
776 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
777 const MDNode *ScopeNode) {
778 DIVariable Cleansed = DV;
779 if (getExistingAbstractVariable(DV, Cleansed))
782 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
786 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
787 const MDNode *ScopeNode) {
788 DIVariable Cleansed = DV;
789 if (getExistingAbstractVariable(DV, Cleansed))
792 if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
793 createAbstractVariable(Cleansed, Scope);
796 // If Var is a current function argument then add it to CurrentFnArguments list.
797 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
798 if (!LScopes.isCurrentFunctionScope(Scope))
800 DIVariable DV = Var->getVariable();
801 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
803 unsigned ArgNo = DV.getArgNumber();
807 size_t Size = CurrentFnArguments.size();
809 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
810 // llvm::Function argument size is not good indicator of how many
811 // arguments does the function have at source level.
813 CurrentFnArguments.resize(ArgNo * 2);
814 assert(!CurrentFnArguments[ArgNo - 1]);
815 CurrentFnArguments[ArgNo - 1] = Var;
819 // Collect variable information from side table maintained by MMI.
820 void DwarfDebug::collectVariableInfoFromMMITable(
821 SmallPtrSetImpl<const MDNode *> &Processed) {
822 for (const auto &VI : MMI->getVariableDbgInfo()) {
825 Processed.insert(VI.Var);
826 DIVariable DV(VI.Var);
827 DIExpression Expr(VI.Expr);
828 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
830 // If variable scope is not found then skip this variable.
834 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
835 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
836 DbgVariable *RegVar = ConcreteVariables.back().get();
837 RegVar->setFrameIndex(VI.Slot);
838 addScopeVariable(Scope, RegVar);
842 // Get .debug_loc entry for the instruction range starting at MI.
843 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
844 const MDNode *Expr = MI->getDebugExpression();
845 const MDNode *Var = MI->getDebugVariable();
847 assert(MI->getNumOperands() == 4);
848 if (MI->getOperand(0).isReg()) {
849 MachineLocation MLoc;
850 // If the second operand is an immediate, this is a
851 // register-indirect address.
852 if (!MI->getOperand(1).isImm())
853 MLoc.set(MI->getOperand(0).getReg());
855 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
856 return DebugLocEntry::Value(Var, Expr, MLoc);
858 if (MI->getOperand(0).isImm())
859 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
860 if (MI->getOperand(0).isFPImm())
861 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
862 if (MI->getOperand(0).isCImm())
863 return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
865 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
868 /// Determine whether two variable pieces overlap.
869 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
870 if (!P1.isVariablePiece() || !P2.isVariablePiece())
872 unsigned l1 = P1.getPieceOffset();
873 unsigned l2 = P2.getPieceOffset();
874 unsigned r1 = l1 + P1.getPieceSize();
875 unsigned r2 = l2 + P2.getPieceSize();
876 // True where [l1,r1[ and [r1,r2[ overlap.
877 return (l1 < r2) && (l2 < r1);
880 /// Build the location list for all DBG_VALUEs in the function that
881 /// describe the same variable. If the ranges of several independent
882 /// pieces of the same variable overlap partially, split them up and
883 /// combine the ranges. The resulting DebugLocEntries are will have
884 /// strict monotonically increasing begin addresses and will never
889 // Ranges History [var, loc, piece ofs size]
890 // 0 | [x, (reg0, piece 0, 32)]
891 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
893 // 3 | [clobber reg0]
894 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
898 // [0-1] [x, (reg0, piece 0, 32)]
899 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
900 // [3-4] [x, (reg1, piece 32, 32)]
901 // [4- ] [x, (mem, piece 0, 64)]
903 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
904 const DbgValueHistoryMap::InstrRanges &Ranges) {
905 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
907 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
908 const MachineInstr *Begin = I->first;
909 const MachineInstr *End = I->second;
910 assert(Begin->isDebugValue() && "Invalid History entry");
912 // Check if a variable is inaccessible in this range.
913 if (Begin->getNumOperands() > 1 &&
914 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
919 // If this piece overlaps with any open ranges, truncate them.
920 DIExpression DIExpr = Begin->getDebugExpression();
921 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
922 [&](DebugLocEntry::Value R) {
923 return piecesOverlap(DIExpr, R.getExpression());
925 OpenRanges.erase(Last, OpenRanges.end());
927 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
928 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
930 const MCSymbol *EndLabel;
932 EndLabel = getLabelAfterInsn(End);
933 else if (std::next(I) == Ranges.end())
934 EndLabel = FunctionEndSym;
936 EndLabel = getLabelBeforeInsn(std::next(I)->first);
937 assert(EndLabel && "Forgot label after instruction ending a range!");
939 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
941 auto Value = getDebugLocValue(Begin);
942 DebugLocEntry Loc(StartLabel, EndLabel, Value);
943 bool couldMerge = false;
945 // If this is a piece, it may belong to the current DebugLocEntry.
946 if (DIExpr.isVariablePiece()) {
947 // Add this value to the list of open ranges.
948 OpenRanges.push_back(Value);
950 // Attempt to add the piece to the last entry.
951 if (!DebugLoc.empty())
952 if (DebugLoc.back().MergeValues(Loc))
957 // Need to add a new DebugLocEntry. Add all values from still
958 // valid non-overlapping pieces.
959 if (OpenRanges.size())
960 Loc.addValues(OpenRanges);
962 DebugLoc.push_back(std::move(Loc));
965 // Attempt to coalesce the ranges of two otherwise identical
967 auto CurEntry = DebugLoc.rbegin();
968 auto PrevEntry = std::next(CurEntry);
969 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
973 dbgs() << CurEntry->getValues().size() << " Values:\n";
974 for (auto Value : CurEntry->getValues()) {
975 Value.getVariable()->dump();
976 Value.getExpression()->dump();
984 // Find variables for each lexical scope.
986 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
987 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
988 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
990 // Grab the variable info that was squirreled away in the MMI side-table.
991 collectVariableInfoFromMMITable(Processed);
993 for (const auto &I : DbgValues) {
994 DIVariable DV(I.first);
995 if (Processed.count(DV))
998 // Instruction ranges, specifying where DV is accessible.
999 const auto &Ranges = I.second;
1003 LexicalScope *Scope = nullptr;
1004 if (MDNode *IA = DV.getInlinedAt()) {
1005 DebugLoc DL = DebugLoc::getFromDILocation(IA);
1006 Scope = LScopes.findInlinedScope(DebugLoc::get(
1007 DL.getLine(), DL.getCol(), DV.getContext(), IA));
1009 Scope = LScopes.findLexicalScope(DV.getContext());
1010 // If variable scope is not found then skip this variable.
1014 Processed.insert(DV);
1015 const MachineInstr *MInsn = Ranges.front().first;
1016 assert(MInsn->isDebugValue() && "History must begin with debug value");
1017 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1018 ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1019 DbgVariable *RegVar = ConcreteVariables.back().get();
1020 addScopeVariable(Scope, RegVar);
1022 // Check if the first DBG_VALUE is valid for the rest of the function.
1023 if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1026 // Handle multiple DBG_VALUE instructions describing one variable.
1027 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1029 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1030 DebugLocList &LocList = DotDebugLocEntries.back();
1033 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1035 // Build the location list for this variable.
1036 buildLocationList(LocList.List, Ranges);
1039 // Collect info for variables that were optimized out.
1040 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1041 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1042 DIVariable DV(Variables.getElement(i));
1043 assert(DV.isVariable());
1044 if (!Processed.insert(DV))
1046 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1047 ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1048 DIExpression NoExpr;
1049 ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1050 addScopeVariable(Scope, ConcreteVariables.back().get());
1055 // Return Label preceding the instruction.
1056 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1057 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1058 assert(Label && "Didn't insert label before instruction");
1062 // Return Label immediately following the instruction.
1063 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1064 return LabelsAfterInsn.lookup(MI);
1067 // Process beginning of an instruction.
1068 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1069 assert(CurMI == nullptr);
1071 // Check if source location changes, but ignore DBG_VALUE locations.
1072 if (!MI->isDebugValue()) {
1073 DebugLoc DL = MI->getDebugLoc();
1074 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1077 if (DL == PrologEndLoc) {
1078 Flags |= DWARF2_FLAG_PROLOGUE_END;
1079 PrologEndLoc = DebugLoc();
1081 if (PrologEndLoc.isUnknown())
1082 Flags |= DWARF2_FLAG_IS_STMT;
1084 if (!DL.isUnknown()) {
1085 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1086 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1088 recordSourceLine(0, 0, nullptr, 0);
1092 // Insert labels where requested.
1093 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1094 LabelsBeforeInsn.find(MI);
1097 if (I == LabelsBeforeInsn.end())
1100 // Label already assigned.
1105 PrevLabel = MMI->getContext().CreateTempSymbol();
1106 Asm->OutStreamer.EmitLabel(PrevLabel);
1108 I->second = PrevLabel;
1111 // Process end of an instruction.
1112 void DwarfDebug::endInstruction() {
1113 assert(CurMI != nullptr);
1114 // Don't create a new label after DBG_VALUE instructions.
1115 // They don't generate code.
1116 if (!CurMI->isDebugValue())
1117 PrevLabel = nullptr;
1119 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1120 LabelsAfterInsn.find(CurMI);
1124 if (I == LabelsAfterInsn.end())
1127 // Label already assigned.
1131 // We need a label after this instruction.
1133 PrevLabel = MMI->getContext().CreateTempSymbol();
1134 Asm->OutStreamer.EmitLabel(PrevLabel);
1136 I->second = PrevLabel;
1139 // Each LexicalScope has first instruction and last instruction to mark
1140 // beginning and end of a scope respectively. Create an inverse map that list
1141 // scopes starts (and ends) with an instruction. One instruction may start (or
1142 // end) multiple scopes. Ignore scopes that are not reachable.
1143 void DwarfDebug::identifyScopeMarkers() {
1144 SmallVector<LexicalScope *, 4> WorkList;
1145 WorkList.push_back(LScopes.getCurrentFunctionScope());
1146 while (!WorkList.empty()) {
1147 LexicalScope *S = WorkList.pop_back_val();
1149 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1150 if (!Children.empty())
1151 WorkList.append(Children.begin(), Children.end());
1153 if (S->isAbstractScope())
1156 for (const InsnRange &R : S->getRanges()) {
1157 assert(R.first && "InsnRange does not have first instruction!");
1158 assert(R.second && "InsnRange does not have second instruction!");
1159 requestLabelBeforeInsn(R.first);
1160 requestLabelAfterInsn(R.second);
1165 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1166 // First known non-DBG_VALUE and non-frame setup location marks
1167 // the beginning of the function body.
1168 for (const auto &MBB : *MF)
1169 for (const auto &MI : MBB)
1170 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1171 !MI.getDebugLoc().isUnknown())
1172 return MI.getDebugLoc();
1176 // Gather pre-function debug information. Assumes being called immediately
1177 // after the function entry point has been emitted.
1178 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1181 // If there's no debug info for the function we're not going to do anything.
1182 if (!MMI->hasDebugInfo())
1185 auto DI = FunctionDIs.find(MF->getFunction());
1186 if (DI == FunctionDIs.end())
1189 // Grab the lexical scopes for the function, if we don't have any of those
1190 // then we're not going to be able to do anything.
1191 LScopes.initialize(*MF);
1192 if (LScopes.empty())
1195 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1197 // Make sure that each lexical scope will have a begin/end label.
1198 identifyScopeMarkers();
1200 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1201 // belongs to so that we add to the correct per-cu line table in the
1203 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1204 // FnScope->getScopeNode() and DI->second should represent the same function,
1205 // though they may not be the same MDNode due to inline functions merged in
1206 // LTO where the debug info metadata still differs (either due to distinct
1207 // written differences - two versions of a linkonce_odr function
1208 // written/copied into two separate files, or some sub-optimal metadata that
1209 // isn't structurally identical (see: file path/name info from clang, which
1210 // includes the directory of the cpp file being built, even when the file name
1211 // is absolute (such as an <> lookup header)))
1212 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1213 assert(TheCU && "Unable to find compile unit!");
1214 if (Asm->OutStreamer.hasRawTextSupport())
1215 // Use a single line table if we are generating assembly.
1216 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1218 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1220 // Emit a label for the function so that we have a beginning address.
1221 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1222 // Assumes in correct section after the entry point.
1223 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1225 // Calculate history for local variables.
1226 calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1229 // Request labels for the full history.
1230 for (const auto &I : DbgValues) {
1231 const auto &Ranges = I.second;
1235 // The first mention of a function argument gets the FunctionBeginSym
1236 // label, so arguments are visible when breaking at function entry.
1237 DIVariable DIVar(Ranges.front().first->getDebugVariable());
1238 if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1239 getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1240 LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1241 if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1242 // Mark all non-overlapping initial pieces.
1243 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1244 DIExpression Piece = I->first->getDebugExpression();
1245 if (std::all_of(Ranges.begin(), I,
1246 [&](DbgValueHistoryMap::InstrRange Pred) {
1247 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1249 LabelsBeforeInsn[I->first] = FunctionBeginSym;
1256 for (const auto &Range : Ranges) {
1257 requestLabelBeforeInsn(Range.first);
1259 requestLabelAfterInsn(Range.second);
1263 PrevInstLoc = DebugLoc();
1264 PrevLabel = FunctionBeginSym;
1266 // Record beginning of function.
1267 PrologEndLoc = findPrologueEndLoc(MF);
1268 if (!PrologEndLoc.isUnknown()) {
1269 DebugLoc FnStartDL =
1270 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1272 FnStartDL.getLine(), FnStartDL.getCol(),
1273 FnStartDL.getScope(MF->getFunction()->getContext()),
1274 // We'd like to list the prologue as "not statements" but GDB behaves
1275 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1276 DWARF2_FLAG_IS_STMT);
1280 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1281 if (addCurrentFnArgument(Var, LS))
1283 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1284 DIVariable DV = Var->getVariable();
1285 // Variables with positive arg numbers are parameters.
1286 if (unsigned ArgNum = DV.getArgNumber()) {
1287 // Keep all parameters in order at the start of the variable list to ensure
1288 // function types are correct (no out-of-order parameters)
1290 // This could be improved by only doing it for optimized builds (unoptimized
1291 // builds have the right order to begin with), searching from the back (this
1292 // would catch the unoptimized case quickly), or doing a binary search
1293 // rather than linear search.
1294 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1295 while (I != Vars.end()) {
1296 unsigned CurNum = (*I)->getVariable().getArgNumber();
1297 // A local (non-parameter) variable has been found, insert immediately
1301 // A later indexed parameter has been found, insert immediately before it.
1302 if (CurNum > ArgNum)
1306 Vars.insert(I, Var);
1310 Vars.push_back(Var);
1313 // Gather and emit post-function debug information.
1314 void DwarfDebug::endFunction(const MachineFunction *MF) {
1315 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1316 // though the beginFunction may not be called at all.
1317 // We should handle both cases.
1321 assert(CurFn == MF);
1322 assert(CurFn != nullptr);
1324 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1325 !FunctionDIs.count(MF->getFunction())) {
1326 // If we don't have a lexical scope for this function then there will
1327 // be a hole in the range information. Keep note of this by setting the
1328 // previously used section to nullptr.
1334 // Define end label for subprogram.
1335 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1336 // Assumes in correct section after the entry point.
1337 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1339 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1340 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1342 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1343 collectVariableInfo(ProcessedVars);
1345 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1346 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1348 // Add the range of this function to the list of ranges for the CU.
1349 TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1351 // Under -gmlt, skip building the subprogram if there are no inlined
1352 // subroutines inside it.
1353 if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1354 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1355 assert(ScopeVariables.empty());
1356 assert(CurrentFnArguments.empty());
1357 assert(DbgValues.empty());
1358 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1359 // by a -gmlt CU. Add a test and remove this assertion.
1360 assert(AbstractVariables.empty());
1361 LabelsBeforeInsn.clear();
1362 LabelsAfterInsn.clear();
1363 PrevLabel = nullptr;
1368 // Construct abstract scopes.
1369 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1370 DISubprogram SP(AScope->getScopeNode());
1371 assert(SP.isSubprogram());
1372 // Collect info for variables that were optimized out.
1373 DIArray Variables = SP.getVariables();
1374 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1375 DIVariable DV(Variables.getElement(i));
1376 assert(DV && DV.isVariable());
1377 if (!ProcessedVars.insert(DV))
1379 ensureAbstractVariableIsCreated(DV, DV.getContext());
1381 constructAbstractSubprogramScopeDIE(AScope);
1384 TheCU.constructSubprogramScopeDIE(FnScope);
1387 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1388 // DbgVariables except those that are also in AbstractVariables (since they
1389 // can be used cross-function)
1390 ScopeVariables.clear();
1391 CurrentFnArguments.clear();
1393 LabelsBeforeInsn.clear();
1394 LabelsAfterInsn.clear();
1395 PrevLabel = nullptr;
1399 // Register a source line with debug info. Returns the unique label that was
1400 // emitted and which provides correspondence to the source line list.
1401 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1406 unsigned Discriminator = 0;
1407 if (DIScope Scope = DIScope(S)) {
1408 assert(Scope.isScope());
1409 Fn = Scope.getFilename();
1410 Dir = Scope.getDirectory();
1411 if (Scope.isLexicalBlockFile())
1412 Discriminator = DILexicalBlockFile(S).getDiscriminator();
1414 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1415 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1416 .getOrCreateSourceID(Fn, Dir);
1418 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1422 //===----------------------------------------------------------------------===//
1424 //===----------------------------------------------------------------------===//
1426 // Emit initial Dwarf sections with a label at the start of each one.
1427 void DwarfDebug::emitSectionLabels() {
1428 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1430 // Dwarf sections base addresses.
1431 DwarfInfoSectionSym =
1432 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1433 if (useSplitDwarf()) {
1434 DwarfInfoDWOSectionSym =
1435 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1436 DwarfTypesDWOSectionSym =
1437 emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1439 DwarfAbbrevSectionSym =
1440 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1441 if (useSplitDwarf())
1442 DwarfAbbrevDWOSectionSym = emitSectionSym(
1443 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1444 if (GenerateARangeSection)
1445 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1447 DwarfLineSectionSym =
1448 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1449 if (GenerateGnuPubSections) {
1450 DwarfGnuPubNamesSectionSym =
1451 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1452 DwarfGnuPubTypesSectionSym =
1453 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1454 } else if (HasDwarfPubSections) {
1455 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1456 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1459 DwarfStrSectionSym =
1460 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1461 if (useSplitDwarf()) {
1462 DwarfStrDWOSectionSym =
1463 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1464 DwarfAddrSectionSym =
1465 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1466 DwarfDebugLocSectionSym =
1467 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1469 DwarfDebugLocSectionSym =
1470 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1471 DwarfDebugRangeSectionSym =
1472 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1475 // Recursively emits a debug information entry.
1476 void DwarfDebug::emitDIE(DIE &Die) {
1477 // Get the abbreviation for this DIE.
1478 const DIEAbbrev &Abbrev = Die.getAbbrev();
1480 // Emit the code (index) for the abbreviation.
1481 if (Asm->isVerbose())
1482 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1483 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1484 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1485 dwarf::TagString(Abbrev.getTag()));
1486 Asm->EmitULEB128(Abbrev.getNumber());
1488 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1489 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1491 // Emit the DIE attribute values.
1492 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1493 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1494 dwarf::Form Form = AbbrevData[i].getForm();
1495 assert(Form && "Too many attributes for DIE (check abbreviation)");
1497 if (Asm->isVerbose()) {
1498 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1499 if (Attr == dwarf::DW_AT_accessibility)
1500 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1501 cast<DIEInteger>(Values[i])->getValue()));
1504 // Emit an attribute using the defined form.
1505 Values[i]->EmitValue(Asm, Form);
1508 // Emit the DIE children if any.
1509 if (Abbrev.hasChildren()) {
1510 for (auto &Child : Die.getChildren())
1513 Asm->OutStreamer.AddComment("End Of Children Mark");
1518 // Emit the debug info section.
1519 void DwarfDebug::emitDebugInfo() {
1520 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1522 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1525 // Emit the abbreviation section.
1526 void DwarfDebug::emitAbbreviations() {
1527 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1529 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1532 // Emit the last address of the section and the end of the line matrix.
1533 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1534 // Define last address of section.
1535 Asm->OutStreamer.AddComment("Extended Op");
1538 Asm->OutStreamer.AddComment("Op size");
1539 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1540 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1541 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1543 Asm->OutStreamer.AddComment("Section end label");
1545 Asm->OutStreamer.EmitSymbolValue(
1546 Asm->GetTempSymbol("section_end", SectionEnd),
1547 Asm->getDataLayout().getPointerSize());
1549 // Mark end of matrix.
1550 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1556 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1557 StringRef TableName, StringRef SymName) {
1558 Accel.FinalizeTable(Asm, TableName);
1559 Asm->OutStreamer.SwitchSection(Section);
1560 auto *SectionBegin = Asm->GetTempSymbol(SymName);
1561 Asm->OutStreamer.EmitLabel(SectionBegin);
1563 // Emit the full data.
1564 Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1567 // Emit visible names into a hashed accelerator table section.
1568 void DwarfDebug::emitAccelNames() {
1569 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1570 "Names", "names_begin");
1573 // Emit objective C classes and categories into a hashed accelerator table
1575 void DwarfDebug::emitAccelObjC() {
1576 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1577 "ObjC", "objc_begin");
1580 // Emit namespace dies into a hashed accelerator table.
1581 void DwarfDebug::emitAccelNamespaces() {
1582 emitAccel(AccelNamespace,
1583 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1584 "namespac", "namespac_begin");
1587 // Emit type dies into a hashed accelerator table.
1588 void DwarfDebug::emitAccelTypes() {
1589 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1590 "types", "types_begin");
1593 // Public name handling.
1594 // The format for the various pubnames:
1596 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1597 // for the DIE that is named.
1599 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1600 // into the CU and the index value is computed according to the type of value
1601 // for the DIE that is named.
1603 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1604 // it's the offset within the debug_info/debug_types dwo section, however, the
1605 // reference in the pubname header doesn't change.
1607 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1608 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1610 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1612 // We could have a specification DIE that has our most of our knowledge,
1613 // look for that now.
1614 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1616 DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1617 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1618 Linkage = dwarf::GIEL_EXTERNAL;
1619 } else if (Die->findAttribute(dwarf::DW_AT_external))
1620 Linkage = dwarf::GIEL_EXTERNAL;
1622 switch (Die->getTag()) {
1623 case dwarf::DW_TAG_class_type:
1624 case dwarf::DW_TAG_structure_type:
1625 case dwarf::DW_TAG_union_type:
1626 case dwarf::DW_TAG_enumeration_type:
1627 return dwarf::PubIndexEntryDescriptor(
1628 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1629 ? dwarf::GIEL_STATIC
1630 : dwarf::GIEL_EXTERNAL);
1631 case dwarf::DW_TAG_typedef:
1632 case dwarf::DW_TAG_base_type:
1633 case dwarf::DW_TAG_subrange_type:
1634 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1635 case dwarf::DW_TAG_namespace:
1636 return dwarf::GIEK_TYPE;
1637 case dwarf::DW_TAG_subprogram:
1638 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1639 case dwarf::DW_TAG_constant:
1640 case dwarf::DW_TAG_variable:
1641 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1642 case dwarf::DW_TAG_enumerator:
1643 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1644 dwarf::GIEL_STATIC);
1646 return dwarf::GIEK_NONE;
1650 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1652 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1653 const MCSection *PSec =
1654 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1655 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1657 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1660 void DwarfDebug::emitDebugPubSection(
1661 bool GnuStyle, const MCSection *PSec, StringRef Name,
1662 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1663 for (const auto &NU : CUMap) {
1664 DwarfCompileUnit *TheU = NU.second;
1666 const auto &Globals = (TheU->*Accessor)();
1668 if (Globals.empty())
1671 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1673 unsigned ID = TheU->getUniqueID();
1675 // Start the dwarf pubnames section.
1676 Asm->OutStreamer.SwitchSection(PSec);
1679 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1680 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1681 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1682 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1684 Asm->OutStreamer.EmitLabel(BeginLabel);
1686 Asm->OutStreamer.AddComment("DWARF Version");
1687 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1689 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1690 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1692 Asm->OutStreamer.AddComment("Compilation Unit Length");
1693 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1695 // Emit the pubnames for this compilation unit.
1696 for (const auto &GI : Globals) {
1697 const char *Name = GI.getKeyData();
1698 const DIE *Entity = GI.second;
1700 Asm->OutStreamer.AddComment("DIE offset");
1701 Asm->EmitInt32(Entity->getOffset());
1704 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1705 Asm->OutStreamer.AddComment(
1706 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1707 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1708 Asm->EmitInt8(Desc.toBits());
1711 Asm->OutStreamer.AddComment("External Name");
1712 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1715 Asm->OutStreamer.AddComment("End Mark");
1717 Asm->OutStreamer.EmitLabel(EndLabel);
1721 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1722 const MCSection *PSec =
1723 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1724 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1726 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
1729 // Emit visible names into a debug str section.
1730 void DwarfDebug::emitDebugStr() {
1731 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1732 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1735 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1736 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1737 const DITypeIdentifierMap &Map,
1738 ArrayRef<DebugLocEntry::Value> Values) {
1739 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1740 return P.isVariablePiece();
1741 }) && "all values are expected to be pieces");
1742 assert(std::is_sorted(Values.begin(), Values.end()) &&
1743 "pieces are expected to be sorted");
1745 unsigned Offset = 0;
1746 for (auto Piece : Values) {
1747 DIExpression Expr = Piece.getExpression();
1748 unsigned PieceOffset = Expr.getPieceOffset();
1749 unsigned PieceSize = Expr.getPieceSize();
1750 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1751 if (Offset < PieceOffset) {
1752 // The DWARF spec seriously mandates pieces with no locations for gaps.
1753 Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
1754 Offset += PieceOffset-Offset;
1757 Offset += PieceSize;
1759 const unsigned SizeOfByte = 8;
1761 DIVariable Var = Piece.getVariable();
1762 assert(!Var.isIndirect() && "indirect address for piece");
1763 unsigned VarSize = Var.getSizeInBits(Map);
1764 assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1765 && "piece is larger than or outside of variable");
1766 assert(PieceSize*SizeOfByte != VarSize
1767 && "piece covers entire variable");
1769 if (Piece.isLocation() && Piece.getLoc().isReg())
1770 Asm->EmitDwarfRegOpPiece(Streamer,
1772 PieceSize*SizeOfByte);
1774 emitDebugLocValue(Streamer, Piece);
1775 Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1781 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1782 const DebugLocEntry &Entry) {
1783 const DebugLocEntry::Value Value = Entry.getValues()[0];
1784 if (Value.isVariablePiece())
1785 // Emit all pieces that belong to the same variable and range.
1786 return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1788 assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1789 emitDebugLocValue(Streamer, Value);
1792 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1793 const DebugLocEntry::Value &Value) {
1794 DIVariable DV = Value.getVariable();
1796 if (Value.isInt()) {
1797 DIBasicType BTy(resolve(DV.getType()));
1798 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1799 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1800 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
1801 Streamer.EmitSLEB128(Value.getInt());
1803 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
1804 Streamer.EmitULEB128(Value.getInt());
1806 } else if (Value.isLocation()) {
1807 MachineLocation Loc = Value.getLoc();
1808 DIExpression Expr = Value.getExpression();
1811 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1813 // Complex address entry.
1814 unsigned N = Expr.getNumElements();
1816 if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1817 if (Loc.getOffset()) {
1819 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1820 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1821 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1822 Streamer.EmitSLEB128(Expr.getElement(1));
1824 // If first address element is OpPlus then emit
1825 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1826 MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1827 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1831 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1834 // Emit remaining complex address elements.
1835 for (; i < N; ++i) {
1836 uint64_t Element = Expr.getElement(i);
1837 if (Element == dwarf::DW_OP_plus) {
1838 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1839 Streamer.EmitULEB128(Expr.getElement(++i));
1840 } else if (Element == dwarf::DW_OP_deref) {
1842 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1843 } else if (Element == dwarf::DW_OP_piece) {
1845 // handled in emitDebugLocEntry.
1847 llvm_unreachable("unknown Opcode found in complex address");
1851 // else ... ignore constant fp. There is not any good way to
1852 // to represent them here in dwarf.
1856 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1857 Asm->OutStreamer.AddComment("Loc expr size");
1858 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1859 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1860 Asm->EmitLabelDifference(end, begin, 2);
1861 Asm->OutStreamer.EmitLabel(begin);
1863 APByteStreamer Streamer(*Asm);
1864 emitDebugLocEntry(Streamer, Entry);
1866 Asm->OutStreamer.EmitLabel(end);
1869 // Emit locations into the debug loc section.
1870 void DwarfDebug::emitDebugLoc() {
1871 // Start the dwarf loc section.
1872 Asm->OutStreamer.SwitchSection(
1873 Asm->getObjFileLowering().getDwarfLocSection());
1874 unsigned char Size = Asm->getDataLayout().getPointerSize();
1875 for (const auto &DebugLoc : DotDebugLocEntries) {
1876 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1877 const DwarfCompileUnit *CU = DebugLoc.CU;
1878 assert(!CU->getRanges().empty());
1879 for (const auto &Entry : DebugLoc.List) {
1880 // Set up the range. This range is relative to the entry point of the
1881 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1882 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1883 if (CU->getRanges().size() == 1) {
1884 // Grab the begin symbol from the first range as our base.
1885 const MCSymbol *Base = CU->getRanges()[0].getStart();
1886 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1887 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1889 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1890 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1893 emitDebugLocEntryLocation(Entry);
1895 Asm->OutStreamer.EmitIntValue(0, Size);
1896 Asm->OutStreamer.EmitIntValue(0, Size);
1900 void DwarfDebug::emitDebugLocDWO() {
1901 Asm->OutStreamer.SwitchSection(
1902 Asm->getObjFileLowering().getDwarfLocDWOSection());
1903 for (const auto &DebugLoc : DotDebugLocEntries) {
1904 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1905 for (const auto &Entry : DebugLoc.List) {
1906 // Just always use start_length for now - at least that's one address
1907 // rather than two. We could get fancier and try to, say, reuse an
1908 // address we know we've emitted elsewhere (the start of the function?
1909 // The start of the CU or CU subrange that encloses this range?)
1910 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1911 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1912 Asm->EmitULEB128(idx);
1913 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1915 emitDebugLocEntryLocation(Entry);
1917 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1922 const MCSymbol *Start, *End;
1925 // Emit a debug aranges section, containing a CU lookup for any
1926 // address we can tie back to a CU.
1927 void DwarfDebug::emitDebugARanges() {
1928 // Start the dwarf aranges section.
1929 Asm->OutStreamer.SwitchSection(
1930 Asm->getObjFileLowering().getDwarfARangesSection());
1932 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1936 // Build a list of sections used.
1937 std::vector<const MCSection *> Sections;
1938 for (const auto &it : SectionMap) {
1939 const MCSection *Section = it.first;
1940 Sections.push_back(Section);
1943 // Sort the sections into order.
1944 // This is only done to ensure consistent output order across different runs.
1945 std::sort(Sections.begin(), Sections.end(), SectionSort);
1947 // Build a set of address spans, sorted by CU.
1948 for (const MCSection *Section : Sections) {
1949 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1950 if (List.size() < 2)
1953 // Sort the symbols by offset within the section.
1954 std::sort(List.begin(), List.end(),
1955 [&](const SymbolCU &A, const SymbolCU &B) {
1956 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1957 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1959 // Symbols with no order assigned should be placed at the end.
1960 // (e.g. section end labels)
1968 // If we have no section (e.g. common), just write out
1969 // individual spans for each symbol.
1971 for (const SymbolCU &Cur : List) {
1973 Span.Start = Cur.Sym;
1976 Spans[Cur.CU].push_back(Span);
1979 // Build spans between each label.
1980 const MCSymbol *StartSym = List[0].Sym;
1981 for (size_t n = 1, e = List.size(); n < e; n++) {
1982 const SymbolCU &Prev = List[n - 1];
1983 const SymbolCU &Cur = List[n];
1985 // Try and build the longest span we can within the same CU.
1986 if (Cur.CU != Prev.CU) {
1988 Span.Start = StartSym;
1990 Spans[Prev.CU].push_back(Span);
1997 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1999 // Build a list of CUs used.
2000 std::vector<DwarfCompileUnit *> CUs;
2001 for (const auto &it : Spans) {
2002 DwarfCompileUnit *CU = it.first;
2006 // Sort the CU list (again, to ensure consistent output order).
2007 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2008 return A->getUniqueID() < B->getUniqueID();
2011 // Emit an arange table for each CU we used.
2012 for (DwarfCompileUnit *CU : CUs) {
2013 std::vector<ArangeSpan> &List = Spans[CU];
2015 // Emit size of content not including length itself.
2016 unsigned ContentSize =
2017 sizeof(int16_t) + // DWARF ARange version number
2018 sizeof(int32_t) + // Offset of CU in the .debug_info section
2019 sizeof(int8_t) + // Pointer Size (in bytes)
2020 sizeof(int8_t); // Segment Size (in bytes)
2022 unsigned TupleSize = PtrSize * 2;
2024 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2026 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2028 ContentSize += Padding;
2029 ContentSize += (List.size() + 1) * TupleSize;
2031 // For each compile unit, write the list of spans it covers.
2032 Asm->OutStreamer.AddComment("Length of ARange Set");
2033 Asm->EmitInt32(ContentSize);
2034 Asm->OutStreamer.AddComment("DWARF Arange version number");
2035 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2036 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2037 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2038 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2039 Asm->EmitInt8(PtrSize);
2040 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2043 Asm->OutStreamer.EmitFill(Padding, 0xff);
2045 for (const ArangeSpan &Span : List) {
2046 Asm->EmitLabelReference(Span.Start, PtrSize);
2048 // Calculate the size as being from the span start to it's end.
2050 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2052 // For symbols without an end marker (e.g. common), we
2053 // write a single arange entry containing just that one symbol.
2054 uint64_t Size = SymSize[Span.Start];
2058 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2062 Asm->OutStreamer.AddComment("ARange terminator");
2063 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2064 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2068 // Emit visible names into a debug ranges section.
2069 void DwarfDebug::emitDebugRanges() {
2070 // Start the dwarf ranges section.
2071 Asm->OutStreamer.SwitchSection(
2072 Asm->getObjFileLowering().getDwarfRangesSection());
2074 // Size for our labels.
2075 unsigned char Size = Asm->getDataLayout().getPointerSize();
2077 // Grab the specific ranges for the compile units in the module.
2078 for (const auto &I : CUMap) {
2079 DwarfCompileUnit *TheCU = I.second;
2081 // Iterate over the misc ranges for the compile units in the module.
2082 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2083 // Emit our symbol so we can find the beginning of the range.
2084 Asm->OutStreamer.EmitLabel(List.getSym());
2086 for (const RangeSpan &Range : List.getRanges()) {
2087 const MCSymbol *Begin = Range.getStart();
2088 const MCSymbol *End = Range.getEnd();
2089 assert(Begin && "Range without a begin symbol?");
2090 assert(End && "Range without an end symbol?");
2091 if (TheCU->getRanges().size() == 1) {
2092 // Grab the begin symbol from the first range as our base.
2093 const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2094 Asm->EmitLabelDifference(Begin, Base, Size);
2095 Asm->EmitLabelDifference(End, Base, Size);
2097 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2098 Asm->OutStreamer.EmitSymbolValue(End, Size);
2102 // And terminate the list with two 0 values.
2103 Asm->OutStreamer.EmitIntValue(0, Size);
2104 Asm->OutStreamer.EmitIntValue(0, Size);
2107 // Now emit a range for the CU itself.
2108 if (TheCU->getRanges().size() > 1) {
2109 Asm->OutStreamer.EmitLabel(
2110 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2111 for (const RangeSpan &Range : TheCU->getRanges()) {
2112 const MCSymbol *Begin = Range.getStart();
2113 const MCSymbol *End = Range.getEnd();
2114 assert(Begin && "Range without a begin symbol?");
2115 assert(End && "Range without an end symbol?");
2116 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2117 Asm->OutStreamer.EmitSymbolValue(End, Size);
2119 // And terminate the list with two 0 values.
2120 Asm->OutStreamer.EmitIntValue(0, Size);
2121 Asm->OutStreamer.EmitIntValue(0, Size);
2126 // DWARF5 Experimental Separate Dwarf emitters.
2128 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2129 std::unique_ptr<DwarfUnit> NewU) {
2130 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2131 U.getCUNode().getSplitDebugFilename());
2133 if (!CompilationDir.empty())
2134 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2136 addGnuPubAttributes(*NewU, Die);
2138 SkeletonHolder.addUnit(std::move(NewU));
2141 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2142 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2143 // DW_AT_addr_base, DW_AT_ranges_base.
2144 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2146 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2147 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2148 DwarfCompileUnit &NewCU = *OwnedUnit;
2149 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2150 DwarfInfoSectionSym);
2152 NewCU.initStmtList(DwarfLineSectionSym);
2154 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2159 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2160 // compile units that would normally be in debug_info.
2161 void DwarfDebug::emitDebugInfoDWO() {
2162 assert(useSplitDwarf() && "No split dwarf debug info?");
2163 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2164 // emit relocations into the dwo file.
2165 InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2168 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2169 // abbreviations for the .debug_info.dwo section.
2170 void DwarfDebug::emitDebugAbbrevDWO() {
2171 assert(useSplitDwarf() && "No split dwarf?");
2172 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2175 void DwarfDebug::emitDebugLineDWO() {
2176 assert(useSplitDwarf() && "No split dwarf?");
2177 Asm->OutStreamer.SwitchSection(
2178 Asm->getObjFileLowering().getDwarfLineDWOSection());
2179 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2182 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2183 // string section and is identical in format to traditional .debug_str
2185 void DwarfDebug::emitDebugStrDWO() {
2186 assert(useSplitDwarf() && "No split dwarf?");
2187 const MCSection *OffSec =
2188 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2189 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2193 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2194 if (!useSplitDwarf())
2197 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2198 return &SplitTypeUnitFileTable;
2201 static uint64_t makeTypeSignature(StringRef Identifier) {
2203 Hash.update(Identifier);
2204 // ... take the least significant 8 bytes and return those. Our MD5
2205 // implementation always returns its results in little endian, swap bytes
2207 MD5::MD5Result Result;
2209 return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2212 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2213 StringRef Identifier, DIE &RefDie,
2214 DICompositeType CTy) {
2215 // Fast path if we're building some type units and one has already used the
2216 // address pool we know we're going to throw away all this work anyway, so
2217 // don't bother building dependent types.
2218 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2221 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2223 CU.addDIETypeSignature(RefDie, *TU);
2227 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2228 AddrPool.resetUsedFlag();
2230 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2231 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2232 this, &InfoHolder, getDwoLineTable(CU));
2233 DwarfTypeUnit &NewTU = *OwnedUnit;
2234 DIE &UnitDie = NewTU.getUnitDie();
2236 TypeUnitsUnderConstruction.push_back(
2237 std::make_pair(std::move(OwnedUnit), CTy));
2239 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2242 uint64_t Signature = makeTypeSignature(Identifier);
2243 NewTU.setTypeSignature(Signature);
2245 if (useSplitDwarf())
2246 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2247 DwarfTypesDWOSectionSym);
2249 CU.applyStmtList(UnitDie);
2251 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2254 NewTU.setType(NewTU.createTypeDIE(CTy));
2257 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2258 TypeUnitsUnderConstruction.clear();
2260 // Types referencing entries in the address table cannot be placed in type
2262 if (AddrPool.hasBeenUsed()) {
2264 // Remove all the types built while building this type.
2265 // This is pessimistic as some of these types might not be dependent on
2266 // the type that used an address.
2267 for (const auto &TU : TypeUnitsToAdd)
2268 DwarfTypeUnits.erase(TU.second);
2270 // Construct this type in the CU directly.
2271 // This is inefficient because all the dependent types will be rebuilt
2272 // from scratch, including building them in type units, discovering that
2273 // they depend on addresses, throwing them out and rebuilding them.
2274 CU.constructTypeDIE(RefDie, CTy);
2278 // If the type wasn't dependent on fission addresses, finish adding the type
2279 // and all its dependent types.
2280 for (auto &TU : TypeUnitsToAdd)
2281 InfoHolder.addUnit(std::move(TU.first));
2283 CU.addDIETypeSignature(RefDie, NewTU);
2286 // Accelerator table mutators - add each name along with its companion
2287 // DIE to the proper table while ensuring that the name that we're going
2288 // to reference is in the string table. We do this since the names we
2289 // add may not only be identical to the names in the DIE.
2290 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2291 if (!useDwarfAccelTables())
2293 AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2297 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2298 if (!useDwarfAccelTables())
2300 AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2304 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2305 if (!useDwarfAccelTables())
2307 AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2311 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2312 if (!useDwarfAccelTables())
2314 AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),