1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #include "DwarfDebug.h"
15 #include "ByteStreamer.h"
17 #include "DebugLocEntry.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.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/DIE.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCDwarf.h"
37 #include "llvm/MC/MCSection.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/Dwarf.h"
43 #include "llvm/Support/Endian.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/LEB128.h"
47 #include "llvm/Support/MD5.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/Timer.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Target/TargetFrameLowering.h"
52 #include "llvm/Target/TargetLoweringObjectFile.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Target/TargetRegisterInfo.h"
56 #include "llvm/Target/TargetSubtargetInfo.h"
59 #define DEBUG_TYPE "dwarfdebug"
62 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
63 cl::desc("Disable debug info printing"));
65 static cl::opt<bool> UnknownLocations(
66 "use-unknown-locations", cl::Hidden,
67 cl::desc("Make an absence of debug location information explicit."),
71 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
72 cl::desc("Generate GNU-style pubnames and pubtypes"),
75 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
77 cl::desc("Generate dwarf aranges"),
81 enum DefaultOnOff { Default, Enable, Disable };
84 static cl::opt<DefaultOnOff>
85 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
86 cl::desc("Output prototype dwarf accelerator tables."),
87 cl::values(clEnumVal(Default, "Default for platform"),
88 clEnumVal(Enable, "Enabled"),
89 clEnumVal(Disable, "Disabled"), clEnumValEnd),
92 static cl::opt<DefaultOnOff>
93 SplitDwarf("split-dwarf", cl::Hidden,
94 cl::desc("Output DWARF5 split debug info."),
95 cl::values(clEnumVal(Default, "Default for platform"),
96 clEnumVal(Enable, "Enabled"),
97 clEnumVal(Disable, "Disabled"), clEnumValEnd),
100 static cl::opt<DefaultOnOff>
101 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
102 cl::desc("Generate DWARF pubnames and pubtypes sections"),
103 cl::values(clEnumVal(Default, "Default for platform"),
104 clEnumVal(Enable, "Enabled"),
105 clEnumVal(Disable, "Disabled"), clEnumValEnd),
108 static cl::opt<DefaultOnOff>
109 DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
110 cl::desc("Emit DWARF linkage-name attributes."),
111 cl::values(clEnumVal(Default, "Default for platform"),
112 clEnumVal(Enable, "Enabled"),
113 clEnumVal(Disable, "Disabled"), clEnumValEnd),
116 static const char *const DWARFGroupName = "DWARF Emission";
117 static const char *const DbgTimerName = "DWARF Debug Writer";
119 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
121 Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
122 : dwarf::OperationEncodingString(Op));
125 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
126 BS.EmitSLEB128(Value, Twine(Value));
129 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
130 BS.EmitULEB128(Value, Twine(Value));
133 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
134 // This information is not available while emitting .debug_loc entries.
138 //===----------------------------------------------------------------------===//
140 /// resolve - Look in the DwarfDebug map for the MDNode that
141 /// corresponds to the reference.
142 template <typename T> T *DbgVariable::resolve(TypedDINodeRef<T> Ref) const {
143 return DD->resolve(Ref);
146 bool DbgVariable::isBlockByrefVariable() const {
147 assert(Var && "Invalid complex DbgVariable!");
148 return Var->getType()
149 .resolve(DD->getTypeIdentifierMap())
150 ->isBlockByrefStruct();
153 const DIType *DbgVariable::getType() const {
154 DIType *Ty = Var->getType().resolve(DD->getTypeIdentifierMap());
155 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
156 // addresses instead.
157 if (Ty->isBlockByrefStruct()) {
158 /* Byref variables, in Blocks, are declared by the programmer as
159 "SomeType VarName;", but the compiler creates a
160 __Block_byref_x_VarName struct, and gives the variable VarName
161 either the struct, or a pointer to the struct, as its type. This
162 is necessary for various behind-the-scenes things the compiler
163 needs to do with by-reference variables in blocks.
165 However, as far as the original *programmer* is concerned, the
166 variable should still have type 'SomeType', as originally declared.
168 The following function dives into the __Block_byref_x_VarName
169 struct to find the original type of the variable. This will be
170 passed back to the code generating the type for the Debug
171 Information Entry for the variable 'VarName'. 'VarName' will then
172 have the original type 'SomeType' in its debug information.
174 The original type 'SomeType' will be the type of the field named
175 'VarName' inside the __Block_byref_x_VarName struct.
177 NOTE: In order for this to not completely fail on the debugger
178 side, the Debug Information Entry for the variable VarName needs to
179 have a DW_AT_location that tells the debugger how to unwind through
180 the pointers and __Block_byref_x_VarName struct to find the actual
181 value of the variable. The function addBlockByrefType does this. */
182 DIType *subType = Ty;
183 uint16_t tag = Ty->getTag();
185 if (tag == dwarf::DW_TAG_pointer_type)
186 subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
188 auto Elements = cast<DICompositeType>(subType)->getElements();
189 for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
190 auto *DT = cast<DIDerivedType>(Elements[i]);
191 if (getName() == DT->getName())
192 return resolve(DT->getBaseType());
198 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
199 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
200 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
201 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
203 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
204 : Asm(A), MMI(Asm->MMI), DebugLocs(A->OutStreamer->isVerboseAsm()),
205 PrevLabel(nullptr), InfoHolder(A, "info_string", DIEValueAllocator),
206 SkeletonHolder(A, "skel_string", DIEValueAllocator),
207 IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
208 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
209 dwarf::DW_FORM_data4)),
210 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
211 dwarf::DW_FORM_data4)),
212 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
213 dwarf::DW_FORM_data4)),
214 AccelTypes(TypeAtoms), DebuggerTuning(DebuggerKind::Default) {
218 Triple TT(Asm->getTargetTriple());
220 // Make sure we know our "debugger tuning." The target option takes
221 // precedence; fall back to triple-based defaults.
222 if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
223 DebuggerTuning = Asm->TM.Options.DebuggerTuning;
225 DebuggerTuning = DebuggerKind::LLDB;
226 else if (TT.isPS4CPU())
227 DebuggerTuning = DebuggerKind::SCE;
229 DebuggerTuning = DebuggerKind::GDB;
231 // Turn on accelerator tables for LLDB by default.
232 if (DwarfAccelTables == Default)
233 HasDwarfAccelTables = tuneForLLDB();
235 HasDwarfAccelTables = DwarfAccelTables == Enable;
237 // Handle split DWARF. Off by default for now.
238 if (SplitDwarf == Default)
239 HasSplitDwarf = false;
241 HasSplitDwarf = SplitDwarf == Enable;
243 // Pubnames/pubtypes on by default for GDB.
244 if (DwarfPubSections == Default)
245 HasDwarfPubSections = tuneForGDB();
247 HasDwarfPubSections = DwarfPubSections == Enable;
249 // SCE does not use linkage names.
250 if (DwarfLinkageNames == Default)
251 UseLinkageNames = !tuneForSCE();
253 UseLinkageNames = DwarfLinkageNames == Enable;
255 unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
256 DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
257 : MMI->getModule()->getDwarfVersion();
258 // Use dwarf 4 by default if nothing is requested.
259 DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
261 // Work around a GDB bug. GDB doesn't support the standard opcode;
262 // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
263 // is defined as of DWARF 3.
264 // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
265 // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
266 UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
268 Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
271 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
276 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
277 DwarfDebug::~DwarfDebug() { }
279 static bool isObjCClass(StringRef Name) {
280 return Name.startswith("+") || Name.startswith("-");
283 static bool hasObjCCategory(StringRef Name) {
284 if (!isObjCClass(Name))
287 return Name.find(") ") != StringRef::npos;
290 static void getObjCClassCategory(StringRef In, StringRef &Class,
291 StringRef &Category) {
292 if (!hasObjCCategory(In)) {
293 Class = In.slice(In.find('[') + 1, In.find(' '));
298 Class = In.slice(In.find('[') + 1, In.find('('));
299 Category = In.slice(In.find('[') + 1, In.find(' '));
303 static StringRef getObjCMethodName(StringRef In) {
304 return In.slice(In.find(' ') + 1, In.find(']'));
307 // Add the various names to the Dwarf accelerator table names.
308 // TODO: Determine whether or not we should add names for programs
309 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
310 // is only slightly different than the lookup of non-standard ObjC names.
311 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
312 if (!SP->isDefinition())
314 addAccelName(SP->getName(), Die);
316 // If the linkage name is different than the name, go ahead and output
317 // that as well into the name table.
318 if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
319 addAccelName(SP->getLinkageName(), Die);
321 // If this is an Objective-C selector name add it to the ObjC accelerator
323 if (isObjCClass(SP->getName())) {
324 StringRef Class, Category;
325 getObjCClassCategory(SP->getName(), Class, Category);
326 addAccelObjC(Class, Die);
328 addAccelObjC(Category, Die);
329 // Also add the base method name to the name table.
330 addAccelName(getObjCMethodName(SP->getName()), Die);
334 /// Check whether we should create a DIE for the given Scope, return true
335 /// if we don't create a DIE (the corresponding DIE is null).
336 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
337 if (Scope->isAbstractScope())
340 // We don't create a DIE if there is no Range.
341 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
345 if (Ranges.size() > 1)
348 // We don't create a DIE if we have a single Range and the end label
350 return !getLabelAfterInsn(Ranges.front().second);
353 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
355 if (auto *SkelCU = CU.getSkeleton())
359 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
360 assert(Scope && Scope->getScopeNode());
361 assert(Scope->isAbstractScope());
362 assert(!Scope->getInlinedAt());
364 const MDNode *SP = Scope->getScopeNode();
366 ProcessedSPNodes.insert(SP);
368 // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
369 // was inlined from another compile unit.
370 auto &CU = SPMap[SP];
371 forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
372 CU.constructAbstractSubprogramScopeDIE(Scope);
376 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
377 if (!GenerateGnuPubSections)
380 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
383 // Create new DwarfCompileUnit for the given metadata node with tag
384 // DW_TAG_compile_unit.
386 DwarfDebug::constructDwarfCompileUnit(const DICompileUnit *DIUnit) {
387 StringRef FN = DIUnit->getFilename();
388 CompilationDir = DIUnit->getDirectory();
390 auto OwnedUnit = make_unique<DwarfCompileUnit>(
391 InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
392 DwarfCompileUnit &NewCU = *OwnedUnit;
393 DIE &Die = NewCU.getUnitDie();
394 InfoHolder.addUnit(std::move(OwnedUnit));
396 NewCU.setSkeleton(constructSkeletonCU(NewCU));
398 // LTO with assembly output shares a single line table amongst multiple CUs.
399 // To avoid the compilation directory being ambiguous, let the line table
400 // explicitly describe the directory of all files, never relying on the
401 // compilation directory.
402 if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
403 Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
404 NewCU.getUniqueID(), CompilationDir);
406 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit->getProducer());
407 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
408 DIUnit->getSourceLanguage());
409 NewCU.addString(Die, dwarf::DW_AT_name, FN);
411 if (!useSplitDwarf()) {
412 NewCU.initStmtList();
414 // If we're using split dwarf the compilation dir is going to be in the
415 // skeleton CU and so we don't need to duplicate it here.
416 if (!CompilationDir.empty())
417 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
419 addGnuPubAttributes(NewCU, Die);
422 if (DIUnit->isOptimized())
423 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
425 StringRef Flags = DIUnit->getFlags();
427 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
429 if (unsigned RVer = DIUnit->getRuntimeVersion())
430 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
431 dwarf::DW_FORM_data1, RVer);
434 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
436 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
438 if (DIUnit->getDWOId()) {
439 // This CU is either a clang module DWO or a skeleton CU.
440 NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
442 if (!DIUnit->getSplitDebugFilename().empty())
443 // This is a prefabricated skeleton CU.
444 NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
445 DIUnit->getSplitDebugFilename());
448 CUMap.insert(std::make_pair(DIUnit, &NewCU));
449 CUDieMap.insert(std::make_pair(&Die, &NewCU));
453 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
454 const DIImportedEntity *N) {
455 if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
456 D->addChild(TheCU.constructImportedEntityDIE(N));
459 // Emit all Dwarf sections that should come prior to the content. Create
460 // global DIEs and emit initial debug info sections. This is invoked by
461 // the target AsmPrinter.
462 void DwarfDebug::beginModule() {
463 if (DisableDebugInfoPrinting)
466 const Module *M = MMI->getModule();
468 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
471 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
473 SingleCU = CU_Nodes->getNumOperands() == 1;
475 for (MDNode *N : CU_Nodes->operands()) {
476 auto *CUNode = cast<DICompileUnit>(N);
477 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
478 for (auto *IE : CUNode->getImportedEntities())
479 CU.addImportedEntity(IE);
480 for (auto *GV : CUNode->getGlobalVariables())
481 CU.getOrCreateGlobalVariableDIE(GV);
482 for (auto *SP : CUNode->getSubprograms())
483 SPMap.insert(std::make_pair(SP, &CU));
484 for (auto *Ty : CUNode->getEnumTypes()) {
485 // The enum types array by design contains pointers to
486 // MDNodes rather than DIRefs. Unique them here.
487 CU.getOrCreateTypeDIE(cast<DIType>(resolve(Ty->getRef())));
489 for (auto *Ty : CUNode->getRetainedTypes()) {
490 // The retained types array by design contains pointers to
491 // MDNodes rather than DIRefs. Unique them here.
492 DIType *RT = cast<DIType>(resolve(Ty->getRef()));
493 if (!RT->isExternalTypeRef())
494 // There is no point in force-emitting a forward declaration.
495 CU.getOrCreateTypeDIE(RT);
497 // Emit imported_modules last so that the relevant context is already
499 for (auto *IE : CUNode->getImportedEntities())
500 constructAndAddImportedEntityDIE(CU, IE);
503 // Tell MMI that we have debug info.
504 MMI->setDebugInfoAvailability(true);
507 void DwarfDebug::finishVariableDefinitions() {
508 for (const auto &Var : ConcreteVariables) {
509 DIE *VariableDie = Var->getDIE();
511 // FIXME: Consider the time-space tradeoff of just storing the unit pointer
512 // in the ConcreteVariables list, rather than looking it up again here.
513 // DIE::getUnit isn't simple - it walks parent pointers, etc.
514 DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
516 DbgVariable *AbsVar = getExistingAbstractVariable(
517 InlinedVariable(Var->getVariable(), Var->getInlinedAt()));
518 if (AbsVar && AbsVar->getDIE()) {
519 Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
522 Unit->applyVariableAttributes(*Var, *VariableDie);
526 void DwarfDebug::finishSubprogramDefinitions() {
527 for (const auto &P : SPMap)
528 forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
529 CU.finishSubprogramDefinition(cast<DISubprogram>(P.first));
534 // Collect info for variables that were optimized out.
535 void DwarfDebug::collectDeadVariables() {
536 const Module *M = MMI->getModule();
538 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
539 for (MDNode *N : CU_Nodes->operands()) {
540 auto *TheCU = cast<DICompileUnit>(N);
541 // Construct subprogram DIE and add variables DIEs.
542 DwarfCompileUnit *SPCU =
543 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
544 assert(SPCU && "Unable to find Compile Unit!");
545 for (auto *SP : TheCU->getSubprograms()) {
546 if (ProcessedSPNodes.count(SP) != 0)
548 SPCU->collectDeadVariables(SP);
554 void DwarfDebug::finalizeModuleInfo() {
555 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
557 finishSubprogramDefinitions();
559 finishVariableDefinitions();
561 // Collect info for variables that were optimized out.
562 collectDeadVariables();
564 unsigned MacroOffset = 0;
565 std::unique_ptr<AsmStreamerBase> AS(new SizeReporterAsmStreamer(Asm));
566 // Handle anything that needs to be done on a per-unit basis after
567 // all other generation.
568 for (const auto &P : CUMap) {
569 auto &TheCU = *P.second;
570 // Emit DW_AT_containing_type attribute to connect types with their
571 // vtable holding type.
572 TheCU.constructContainingTypeDIEs();
574 // Add CU specific attributes if we need to add any.
575 // If we're splitting the dwarf out now that we've got the entire
576 // CU then add the dwo id to it.
577 auto *SkCU = TheCU.getSkeleton();
578 if (useSplitDwarf()) {
579 // Emit a unique identifier for this CU.
580 uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
581 TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
582 dwarf::DW_FORM_data8, ID);
583 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
584 dwarf::DW_FORM_data8, ID);
586 // We don't keep track of which addresses are used in which CU so this
587 // is a bit pessimistic under LTO.
588 if (!AddrPool.isEmpty()) {
589 const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
590 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
593 if (!SkCU->getRangeLists().empty()) {
594 const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
595 SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
600 // If we have code split among multiple sections or non-contiguous
601 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
602 // remain in the .o file, otherwise add a DW_AT_low_pc.
603 // FIXME: We should use ranges allow reordering of code ala
604 // .subsections_via_symbols in mach-o. This would mean turning on
605 // ranges for all subprogram DIEs for mach-o.
606 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
607 if (unsigned NumRanges = TheCU.getRanges().size()) {
609 // A DW_AT_low_pc attribute may also be specified in combination with
610 // DW_AT_ranges to specify the default base address for use in
611 // location lists (see Section 2.6.2) and range lists (see Section
613 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
615 U.setBaseAddress(TheCU.getRanges().front().getStart());
616 U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
619 auto *CUNode = cast<DICompileUnit>(P.first);
620 if (CUNode->getMacros()) {
621 // Compile Unit has macros, emit "DW_AT_macro_info" attribute.
622 U.addUInt(U.getUnitDie(), dwarf::DW_AT_macro_info,
623 dwarf::DW_FORM_sec_offset, MacroOffset);
624 // Update macro section offset
625 MacroOffset += handleMacroNodes(AS.get(), CUNode->getMacros(), U);
629 // Compute DIE offsets and sizes.
630 InfoHolder.computeSizeAndOffsets();
632 SkeletonHolder.computeSizeAndOffsets();
635 // Emit all Dwarf sections that should come after the content.
636 void DwarfDebug::endModule() {
637 assert(CurFn == nullptr);
638 assert(CurMI == nullptr);
640 // If we aren't actually generating debug info (check beginModule -
641 // conditionalized on !DisableDebugInfoPrinting and the presence of the
642 // llvm.dbg.cu metadata node)
643 if (!MMI->hasDebugInfo())
646 // Finalize the debug info for the module.
647 finalizeModuleInfo();
654 // Emit info into a debug loc section.
657 // Corresponding abbreviations into a abbrev section.
660 // Emit all the DIEs into a debug info section.
663 // Emit info into a debug aranges section.
664 if (GenerateARangeSection)
667 // Emit info into a debug ranges section.
670 // Emit info into a debug macinfo section.
673 if (useSplitDwarf()) {
676 emitDebugAbbrevDWO();
678 // Emit DWO addresses.
679 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
682 // Emit info into the dwarf accelerator table sections.
683 if (useDwarfAccelTables()) {
686 emitAccelNamespaces();
690 // Emit the pubnames and pubtypes sections if requested.
691 if (HasDwarfPubSections) {
692 emitDebugPubNames(GenerateGnuPubSections);
693 emitDebugPubTypes(GenerateGnuPubSections);
698 AbstractVariables.clear();
701 // Find abstract variable, if any, associated with Var.
703 DwarfDebug::getExistingAbstractVariable(InlinedVariable IV,
704 const DILocalVariable *&Cleansed) {
705 // More then one inlined variable corresponds to one abstract variable.
707 auto I = AbstractVariables.find(Cleansed);
708 if (I != AbstractVariables.end())
709 return I->second.get();
713 DbgVariable *DwarfDebug::getExistingAbstractVariable(InlinedVariable IV) {
714 const DILocalVariable *Cleansed;
715 return getExistingAbstractVariable(IV, Cleansed);
718 void DwarfDebug::createAbstractVariable(const DILocalVariable *Var,
719 LexicalScope *Scope) {
720 auto AbsDbgVariable = make_unique<DbgVariable>(Var, /* IA */ nullptr, this);
721 InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
722 AbstractVariables[Var] = std::move(AbsDbgVariable);
725 void DwarfDebug::ensureAbstractVariableIsCreated(InlinedVariable IV,
726 const MDNode *ScopeNode) {
727 const DILocalVariable *Cleansed = nullptr;
728 if (getExistingAbstractVariable(IV, Cleansed))
731 createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
732 cast<DILocalScope>(ScopeNode)));
735 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(
736 InlinedVariable IV, const MDNode *ScopeNode) {
737 const DILocalVariable *Cleansed = nullptr;
738 if (getExistingAbstractVariable(IV, Cleansed))
741 if (LexicalScope *Scope =
742 LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
743 createAbstractVariable(Cleansed, Scope);
746 // Collect variable information from side table maintained by MMI.
747 void DwarfDebug::collectVariableInfoFromMMITable(
748 DenseSet<InlinedVariable> &Processed) {
749 for (const auto &VI : MMI->getVariableDbgInfo()) {
752 assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
753 "Expected inlined-at fields to agree");
755 InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
756 Processed.insert(Var);
757 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
759 // If variable scope is not found then skip this variable.
763 ensureAbstractVariableIsCreatedIfScoped(Var, Scope->getScopeNode());
764 auto RegVar = make_unique<DbgVariable>(Var.first, Var.second, this);
765 RegVar->initializeMMI(VI.Expr, VI.Slot);
766 if (InfoHolder.addScopeVariable(Scope, RegVar.get()))
767 ConcreteVariables.push_back(std::move(RegVar));
771 // Get .debug_loc entry for the instruction range starting at MI.
772 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
773 const DIExpression *Expr = MI->getDebugExpression();
775 assert(MI->getNumOperands() == 4);
776 if (MI->getOperand(0).isReg()) {
777 MachineLocation MLoc;
778 // If the second operand is an immediate, this is a
779 // register-indirect address.
780 if (!MI->getOperand(1).isImm())
781 MLoc.set(MI->getOperand(0).getReg());
783 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
784 return DebugLocEntry::Value(Expr, MLoc);
786 if (MI->getOperand(0).isImm())
787 return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
788 if (MI->getOperand(0).isFPImm())
789 return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
790 if (MI->getOperand(0).isCImm())
791 return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
793 llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
796 /// Determine whether two variable pieces overlap.
797 static bool piecesOverlap(const DIExpression *P1, const DIExpression *P2) {
798 if (!P1->isBitPiece() || !P2->isBitPiece())
800 unsigned l1 = P1->getBitPieceOffset();
801 unsigned l2 = P2->getBitPieceOffset();
802 unsigned r1 = l1 + P1->getBitPieceSize();
803 unsigned r2 = l2 + P2->getBitPieceSize();
804 // True where [l1,r1[ and [r1,r2[ overlap.
805 return (l1 < r2) && (l2 < r1);
808 /// \brief If this and Next are describing different pieces of the same
809 /// variable, merge them by appending Next's values to the current
811 /// Return true if the merge was successful.
812 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
813 if (Begin == Next.Begin) {
814 auto *Expr = cast_or_null<DIExpression>(Values[0].Expression);
815 auto *NextExpr = cast_or_null<DIExpression>(Next.Values[0].Expression);
816 if (Expr->isBitPiece() && NextExpr->isBitPiece() &&
817 !piecesOverlap(Expr, NextExpr)) {
818 addValues(Next.Values);
826 /// Build the location list for all DBG_VALUEs in the function that
827 /// describe the same variable. If the ranges of several independent
828 /// pieces of the same variable overlap partially, split them up and
829 /// combine the ranges. The resulting DebugLocEntries are will have
830 /// strict monotonically increasing begin addresses and will never
835 // Ranges History [var, loc, piece ofs size]
836 // 0 | [x, (reg0, piece 0, 32)]
837 // 1 | | [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
839 // 3 | [clobber reg0]
840 // 4 [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of
845 // [0-1] [x, (reg0, piece 0, 32)]
846 // [1-3] [x, (reg0, piece 0, 32), (reg1, piece 32, 32)]
847 // [3-4] [x, (reg1, piece 32, 32)]
848 // [4- ] [x, (mem, piece 0, 64)]
850 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
851 const DbgValueHistoryMap::InstrRanges &Ranges) {
852 SmallVector<DebugLocEntry::Value, 4> OpenRanges;
854 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
855 const MachineInstr *Begin = I->first;
856 const MachineInstr *End = I->second;
857 assert(Begin->isDebugValue() && "Invalid History entry");
859 // Check if a variable is inaccessible in this range.
860 if (Begin->getNumOperands() > 1 &&
861 Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
866 // If this piece overlaps with any open ranges, truncate them.
867 const DIExpression *DIExpr = Begin->getDebugExpression();
868 auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
869 [&](DebugLocEntry::Value R) {
870 return piecesOverlap(DIExpr, R.getExpression());
872 OpenRanges.erase(Last, OpenRanges.end());
874 const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
875 assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
877 const MCSymbol *EndLabel;
879 EndLabel = getLabelAfterInsn(End);
880 else if (std::next(I) == Ranges.end())
881 EndLabel = Asm->getFunctionEnd();
883 EndLabel = getLabelBeforeInsn(std::next(I)->first);
884 assert(EndLabel && "Forgot label after instruction ending a range!");
886 DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
888 auto Value = getDebugLocValue(Begin);
889 DebugLocEntry Loc(StartLabel, EndLabel, Value);
890 bool couldMerge = false;
892 // If this is a piece, it may belong to the current DebugLocEntry.
893 if (DIExpr->isBitPiece()) {
894 // Add this value to the list of open ranges.
895 OpenRanges.push_back(Value);
897 // Attempt to add the piece to the last entry.
898 if (!DebugLoc.empty())
899 if (DebugLoc.back().MergeValues(Loc))
904 // Need to add a new DebugLocEntry. Add all values from still
905 // valid non-overlapping pieces.
906 if (OpenRanges.size())
907 Loc.addValues(OpenRanges);
909 DebugLoc.push_back(std::move(Loc));
912 // Attempt to coalesce the ranges of two otherwise identical
914 auto CurEntry = DebugLoc.rbegin();
916 dbgs() << CurEntry->getValues().size() << " Values:\n";
917 for (auto &Value : CurEntry->getValues())
918 Value.getExpression()->dump();
922 auto PrevEntry = std::next(CurEntry);
923 if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
928 DbgVariable *DwarfDebug::createConcreteVariable(LexicalScope &Scope,
929 InlinedVariable IV) {
930 ensureAbstractVariableIsCreatedIfScoped(IV, Scope.getScopeNode());
931 ConcreteVariables.push_back(
932 make_unique<DbgVariable>(IV.first, IV.second, this));
933 InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
934 return ConcreteVariables.back().get();
937 // Find variables for each lexical scope.
938 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
939 const DISubprogram *SP,
940 DenseSet<InlinedVariable> &Processed) {
941 // Grab the variable info that was squirreled away in the MMI side-table.
942 collectVariableInfoFromMMITable(Processed);
944 for (const auto &I : DbgValues) {
945 InlinedVariable IV = I.first;
946 if (Processed.count(IV))
949 // Instruction ranges, specifying where IV is accessible.
950 const auto &Ranges = I.second;
954 LexicalScope *Scope = nullptr;
955 if (const DILocation *IA = IV.second)
956 Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
958 Scope = LScopes.findLexicalScope(IV.first->getScope());
959 // If variable scope is not found then skip this variable.
963 Processed.insert(IV);
964 DbgVariable *RegVar = createConcreteVariable(*Scope, IV);
966 const MachineInstr *MInsn = Ranges.front().first;
967 assert(MInsn->isDebugValue() && "History must begin with debug value");
969 // Check if the first DBG_VALUE is valid for the rest of the function.
970 if (Ranges.size() == 1 && Ranges.front().second == nullptr) {
971 RegVar->initializeDbgValue(MInsn);
975 // Handle multiple DBG_VALUE instructions describing one variable.
976 DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
978 // Build the location list for this variable.
979 SmallVector<DebugLocEntry, 8> Entries;
980 buildLocationList(Entries, Ranges);
982 // If the variable has an DIBasicType, extract it. Basic types cannot have
983 // unique identifiers, so don't bother resolving the type with the
985 const DIBasicType *BT = dyn_cast<DIBasicType>(
986 static_cast<const Metadata *>(IV.first->getType()));
988 // Finalize the entry by lowering it into a DWARF bytestream.
989 for (auto &Entry : Entries)
990 Entry.finalize(*Asm, List, BT);
993 // Collect info for variables that were optimized out.
994 for (const DILocalVariable *DV : SP->getVariables()) {
995 if (Processed.insert(InlinedVariable(DV, nullptr)).second)
996 if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
997 createConcreteVariable(*Scope, InlinedVariable(DV, nullptr));
1001 // Return Label preceding the instruction.
1002 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1003 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1004 assert(Label && "Didn't insert label before instruction");
1008 // Return Label immediately following the instruction.
1009 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1010 return LabelsAfterInsn.lookup(MI);
1013 // Process beginning of an instruction.
1014 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1015 assert(CurMI == nullptr);
1017 // Check if source location changes, but ignore DBG_VALUE locations.
1018 if (!MI->isDebugValue()) {
1019 DebugLoc DL = MI->getDebugLoc();
1020 if (DL != PrevInstLoc) {
1024 if (DL == PrologEndLoc) {
1025 Flags |= DWARF2_FLAG_PROLOGUE_END;
1026 PrologEndLoc = DebugLoc();
1027 Flags |= DWARF2_FLAG_IS_STMT;
1030 Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine())
1031 Flags |= DWARF2_FLAG_IS_STMT;
1033 const MDNode *Scope = DL.getScope();
1034 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1035 } else if (UnknownLocations) {
1037 recordSourceLine(0, 0, nullptr, 0);
1042 // Insert labels where requested.
1043 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1044 LabelsBeforeInsn.find(MI);
1047 if (I == LabelsBeforeInsn.end())
1050 // Label already assigned.
1055 PrevLabel = MMI->getContext().createTempSymbol();
1056 Asm->OutStreamer->EmitLabel(PrevLabel);
1058 I->second = PrevLabel;
1061 // Process end of an instruction.
1062 void DwarfDebug::endInstruction() {
1063 assert(CurMI != nullptr);
1064 // Don't create a new label after DBG_VALUE instructions.
1065 // They don't generate code.
1066 if (!CurMI->isDebugValue())
1067 PrevLabel = nullptr;
1069 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1070 LabelsAfterInsn.find(CurMI);
1074 if (I == LabelsAfterInsn.end())
1077 // Label already assigned.
1081 // We need a label after this instruction.
1083 PrevLabel = MMI->getContext().createTempSymbol();
1084 Asm->OutStreamer->EmitLabel(PrevLabel);
1086 I->second = PrevLabel;
1089 // Each LexicalScope has first instruction and last instruction to mark
1090 // beginning and end of a scope respectively. Create an inverse map that list
1091 // scopes starts (and ends) with an instruction. One instruction may start (or
1092 // end) multiple scopes. Ignore scopes that are not reachable.
1093 void DwarfDebug::identifyScopeMarkers() {
1094 SmallVector<LexicalScope *, 4> WorkList;
1095 WorkList.push_back(LScopes.getCurrentFunctionScope());
1096 while (!WorkList.empty()) {
1097 LexicalScope *S = WorkList.pop_back_val();
1099 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1100 if (!Children.empty())
1101 WorkList.append(Children.begin(), Children.end());
1103 if (S->isAbstractScope())
1106 for (const InsnRange &R : S->getRanges()) {
1107 assert(R.first && "InsnRange does not have first instruction!");
1108 assert(R.second && "InsnRange does not have second instruction!");
1109 requestLabelBeforeInsn(R.first);
1110 requestLabelAfterInsn(R.second);
1115 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1116 // First known non-DBG_VALUE and non-frame setup location marks
1117 // the beginning of the function body.
1118 for (const auto &MBB : *MF)
1119 for (const auto &MI : MBB)
1120 if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1122 return MI.getDebugLoc();
1126 // Gather pre-function debug information. Assumes being called immediately
1127 // after the function entry point has been emitted.
1128 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1131 // If there's no debug info for the function we're not going to do anything.
1132 if (!MMI->hasDebugInfo())
1135 auto DI = MF->getFunction()->getSubprogram();
1139 // Grab the lexical scopes for the function, if we don't have any of those
1140 // then we're not going to be able to do anything.
1141 LScopes.initialize(*MF);
1142 if (LScopes.empty())
1145 assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1147 // Make sure that each lexical scope will have a begin/end label.
1148 identifyScopeMarkers();
1150 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1151 // belongs to so that we add to the correct per-cu line table in the
1153 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1154 // FnScope->getScopeNode() and DI->second should represent the same function,
1155 // though they may not be the same MDNode due to inline functions merged in
1156 // LTO where the debug info metadata still differs (either due to distinct
1157 // written differences - two versions of a linkonce_odr function
1158 // written/copied into two separate files, or some sub-optimal metadata that
1159 // isn't structurally identical (see: file path/name info from clang, which
1160 // includes the directory of the cpp file being built, even when the file name
1161 // is absolute (such as an <> lookup header)))
1162 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1163 assert(TheCU && "Unable to find compile unit!");
1164 if (Asm->OutStreamer->hasRawTextSupport())
1165 // Use a single line table if we are generating assembly.
1166 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1168 Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1170 // Calculate history for local variables.
1171 calculateDbgValueHistory(MF, Asm->MF->getSubtarget().getRegisterInfo(),
1174 // Request labels for the full history.
1175 for (const auto &I : DbgValues) {
1176 const auto &Ranges = I.second;
1180 // The first mention of a function argument gets the CurrentFnBegin
1181 // label, so arguments are visible when breaking at function entry.
1182 const DILocalVariable *DIVar = Ranges.front().first->getDebugVariable();
1183 if (DIVar->isParameter() &&
1184 getDISubprogram(DIVar->getScope())->describes(MF->getFunction())) {
1185 LabelsBeforeInsn[Ranges.front().first] = Asm->getFunctionBegin();
1186 if (Ranges.front().first->getDebugExpression()->isBitPiece()) {
1187 // Mark all non-overlapping initial pieces.
1188 for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1189 const DIExpression *Piece = I->first->getDebugExpression();
1190 if (std::all_of(Ranges.begin(), I,
1191 [&](DbgValueHistoryMap::InstrRange Pred) {
1192 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1194 LabelsBeforeInsn[I->first] = Asm->getFunctionBegin();
1201 for (const auto &Range : Ranges) {
1202 requestLabelBeforeInsn(Range.first);
1204 requestLabelAfterInsn(Range.second);
1208 PrevInstLoc = DebugLoc();
1209 PrevLabel = Asm->getFunctionBegin();
1211 // Record beginning of function.
1212 PrologEndLoc = findPrologueEndLoc(MF);
1213 if (DILocation *L = PrologEndLoc) {
1214 // We'd like to list the prologue as "not statements" but GDB behaves
1215 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1216 auto *SP = L->getInlinedAtScope()->getSubprogram();
1217 recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1221 // Gather and emit post-function debug information.
1222 void DwarfDebug::endFunction(const MachineFunction *MF) {
1223 assert(CurFn == MF &&
1224 "endFunction should be called with the same function as beginFunction");
1226 if (!MMI->hasDebugInfo() || LScopes.empty() ||
1227 !MF->getFunction()->getSubprogram()) {
1228 // If we don't have a lexical scope for this function then there will
1229 // be a hole in the range information. Keep note of this by setting the
1230 // previously used section to nullptr.
1236 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1237 Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1239 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1240 auto *SP = cast<DISubprogram>(FnScope->getScopeNode());
1241 DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1243 DenseSet<InlinedVariable> ProcessedVars;
1244 collectVariableInfo(TheCU, SP, ProcessedVars);
1246 // Add the range of this function to the list of ranges for the CU.
1247 TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1249 // Under -gmlt, skip building the subprogram if there are no inlined
1250 // subroutines inside it.
1251 if (TheCU.getCUNode()->getEmissionKind() == DIBuilder::LineTablesOnly &&
1252 LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1253 assert(InfoHolder.getScopeVariables().empty());
1254 assert(DbgValues.empty());
1255 // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1256 // by a -gmlt CU. Add a test and remove this assertion.
1257 assert(AbstractVariables.empty());
1258 LabelsBeforeInsn.clear();
1259 LabelsAfterInsn.clear();
1260 PrevLabel = nullptr;
1266 size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1268 // Construct abstract scopes.
1269 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1270 auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1271 // Collect info for variables that were optimized out.
1272 for (const DILocalVariable *DV : SP->getVariables()) {
1273 if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1275 ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr),
1277 assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1278 && "ensureAbstractVariableIsCreated inserted abstract scopes");
1280 constructAbstractSubprogramScopeDIE(AScope);
1283 TheCU.constructSubprogramScopeDIE(FnScope);
1284 if (auto *SkelCU = TheCU.getSkeleton())
1285 if (!LScopes.getAbstractScopesList().empty())
1286 SkelCU->constructSubprogramScopeDIE(FnScope);
1289 // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1290 // DbgVariables except those that are also in AbstractVariables (since they
1291 // can be used cross-function)
1292 InfoHolder.getScopeVariables().clear();
1294 LabelsBeforeInsn.clear();
1295 LabelsAfterInsn.clear();
1296 PrevLabel = nullptr;
1300 // Register a source line with debug info. Returns the unique label that was
1301 // emitted and which provides correspondence to the source line list.
1302 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1307 unsigned Discriminator = 0;
1308 if (auto *Scope = cast_or_null<DIScope>(S)) {
1309 Fn = Scope->getFilename();
1310 Dir = Scope->getDirectory();
1311 if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1312 Discriminator = LBF->getDiscriminator();
1314 unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1315 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1316 .getOrCreateSourceID(Fn, Dir);
1318 Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1322 //===----------------------------------------------------------------------===//
1324 //===----------------------------------------------------------------------===//
1326 // Emit the debug info section.
1327 void DwarfDebug::emitDebugInfo() {
1328 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1329 Holder.emitUnits(/* UseOffsets */ false);
1332 // Emit the abbreviation section.
1333 void DwarfDebug::emitAbbreviations() {
1334 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1336 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1339 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
1340 StringRef TableName) {
1341 Accel.FinalizeTable(Asm, TableName);
1342 Asm->OutStreamer->SwitchSection(Section);
1344 // Emit the full data.
1345 Accel.emit(Asm, Section->getBeginSymbol(), this);
1348 // Emit visible names into a hashed accelerator table section.
1349 void DwarfDebug::emitAccelNames() {
1350 emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1354 // Emit objective C classes and categories into a hashed accelerator table
1356 void DwarfDebug::emitAccelObjC() {
1357 emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1361 // Emit namespace dies into a hashed accelerator table.
1362 void DwarfDebug::emitAccelNamespaces() {
1363 emitAccel(AccelNamespace,
1364 Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1368 // Emit type dies into a hashed accelerator table.
1369 void DwarfDebug::emitAccelTypes() {
1370 emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1374 // Public name handling.
1375 // The format for the various pubnames:
1377 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1378 // for the DIE that is named.
1380 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1381 // into the CU and the index value is computed according to the type of value
1382 // for the DIE that is named.
1384 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1385 // it's the offset within the debug_info/debug_types dwo section, however, the
1386 // reference in the pubname header doesn't change.
1388 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1389 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1391 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1393 // We could have a specification DIE that has our most of our knowledge,
1394 // look for that now.
1395 if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1396 DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1397 if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1398 Linkage = dwarf::GIEL_EXTERNAL;
1399 } else if (Die->findAttribute(dwarf::DW_AT_external))
1400 Linkage = dwarf::GIEL_EXTERNAL;
1402 switch (Die->getTag()) {
1403 case dwarf::DW_TAG_class_type:
1404 case dwarf::DW_TAG_structure_type:
1405 case dwarf::DW_TAG_union_type:
1406 case dwarf::DW_TAG_enumeration_type:
1407 return dwarf::PubIndexEntryDescriptor(
1408 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1409 ? dwarf::GIEL_STATIC
1410 : dwarf::GIEL_EXTERNAL);
1411 case dwarf::DW_TAG_typedef:
1412 case dwarf::DW_TAG_base_type:
1413 case dwarf::DW_TAG_subrange_type:
1414 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1415 case dwarf::DW_TAG_namespace:
1416 return dwarf::GIEK_TYPE;
1417 case dwarf::DW_TAG_subprogram:
1418 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1419 case dwarf::DW_TAG_variable:
1420 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1421 case dwarf::DW_TAG_enumerator:
1422 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1423 dwarf::GIEL_STATIC);
1425 return dwarf::GIEK_NONE;
1429 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1431 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1432 MCSection *PSec = GnuStyle
1433 ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1434 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1436 emitDebugPubSection(GnuStyle, PSec, "Names",
1437 &DwarfCompileUnit::getGlobalNames);
1440 void DwarfDebug::emitDebugPubSection(
1441 bool GnuStyle, MCSection *PSec, StringRef Name,
1442 const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1443 for (const auto &NU : CUMap) {
1444 DwarfCompileUnit *TheU = NU.second;
1446 const auto &Globals = (TheU->*Accessor)();
1448 if (Globals.empty())
1451 if (auto *Skeleton = TheU->getSkeleton())
1454 // Start the dwarf pubnames section.
1455 Asm->OutStreamer->SwitchSection(PSec);
1458 Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1459 MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1460 MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1461 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1463 Asm->OutStreamer->EmitLabel(BeginLabel);
1465 Asm->OutStreamer->AddComment("DWARF Version");
1466 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1468 Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1469 Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1471 Asm->OutStreamer->AddComment("Compilation Unit Length");
1472 Asm->EmitInt32(TheU->getLength());
1474 // Emit the pubnames for this compilation unit.
1475 for (const auto &GI : Globals) {
1476 const char *Name = GI.getKeyData();
1477 const DIE *Entity = GI.second;
1479 Asm->OutStreamer->AddComment("DIE offset");
1480 Asm->EmitInt32(Entity->getOffset());
1483 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1484 Asm->OutStreamer->AddComment(
1485 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1486 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1487 Asm->EmitInt8(Desc.toBits());
1490 Asm->OutStreamer->AddComment("External Name");
1491 Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1494 Asm->OutStreamer->AddComment("End Mark");
1496 Asm->OutStreamer->EmitLabel(EndLabel);
1500 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1501 MCSection *PSec = GnuStyle
1502 ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1503 : Asm->getObjFileLowering().getDwarfPubTypesSection();
1505 emitDebugPubSection(GnuStyle, PSec, "Types",
1506 &DwarfCompileUnit::getGlobalTypes);
1509 // Emit visible names into a debug str section.
1510 void DwarfDebug::emitDebugStr() {
1511 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1512 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1515 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1516 const DebugLocStream::Entry &Entry) {
1517 auto &&Comments = DebugLocs.getComments(Entry);
1518 auto Comment = Comments.begin();
1519 auto End = Comments.end();
1520 for (uint8_t Byte : DebugLocs.getBytes(Entry))
1521 Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1524 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1525 ByteStreamer &Streamer,
1526 const DebugLocEntry::Value &Value,
1527 unsigned PieceOffsetInBits) {
1528 DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1529 AP.getDwarfDebug()->getDwarfVersion(),
1532 if (Value.isInt()) {
1533 if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1534 BT->getEncoding() == dwarf::DW_ATE_signed_char))
1535 DwarfExpr.AddSignedConstant(Value.getInt());
1537 DwarfExpr.AddUnsignedConstant(Value.getInt());
1538 } else if (Value.isLocation()) {
1539 MachineLocation Loc = Value.getLoc();
1540 const DIExpression *Expr = Value.getExpression();
1541 if (!Expr || !Expr->getNumElements())
1543 AP.EmitDwarfRegOp(Streamer, Loc);
1545 // Complex address entry.
1546 if (Loc.getOffset()) {
1547 DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1548 DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(),
1551 DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1555 // else ... ignore constant fp. There is not any good way to
1556 // to represent them here in dwarf.
1560 void DebugLocEntry::finalize(const AsmPrinter &AP,
1561 DebugLocStream::ListBuilder &List,
1562 const DIBasicType *BT) {
1563 DebugLocStream::EntryBuilder Entry(List, Begin, End);
1564 BufferByteStreamer Streamer = Entry.getStreamer();
1565 const DebugLocEntry::Value &Value = Values[0];
1566 if (Value.isBitPiece()) {
1567 // Emit all pieces that belong to the same variable and range.
1568 assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1569 return P.isBitPiece();
1570 }) && "all values are expected to be pieces");
1571 assert(std::is_sorted(Values.begin(), Values.end()) &&
1572 "pieces are expected to be sorted");
1574 unsigned Offset = 0;
1575 for (auto Piece : Values) {
1576 const DIExpression *Expr = Piece.getExpression();
1577 unsigned PieceOffset = Expr->getBitPieceOffset();
1578 unsigned PieceSize = Expr->getBitPieceSize();
1579 assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1580 if (Offset < PieceOffset) {
1581 // The DWARF spec seriously mandates pieces with no locations for gaps.
1582 DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1583 AP.getDwarfDebug()->getDwarfVersion(),
1585 Expr.AddOpPiece(PieceOffset-Offset, 0);
1586 Offset += PieceOffset-Offset;
1588 Offset += PieceSize;
1590 emitDebugLocValue(AP, BT, Streamer, Piece, PieceOffset);
1593 assert(Values.size() == 1 && "only pieces may have >1 value");
1594 emitDebugLocValue(AP, BT, Streamer, Value, 0);
1598 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1600 Asm->OutStreamer->AddComment("Loc expr size");
1601 Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1604 APByteStreamer Streamer(*Asm);
1605 emitDebugLocEntry(Streamer, Entry);
1608 // Emit locations into the debug loc section.
1609 void DwarfDebug::emitDebugLoc() {
1610 // Start the dwarf loc section.
1611 Asm->OutStreamer->SwitchSection(
1612 Asm->getObjFileLowering().getDwarfLocSection());
1613 unsigned char Size = Asm->getDataLayout().getPointerSize();
1614 for (const auto &List : DebugLocs.getLists()) {
1615 Asm->OutStreamer->EmitLabel(List.Label);
1616 const DwarfCompileUnit *CU = List.CU;
1617 for (const auto &Entry : DebugLocs.getEntries(List)) {
1618 // Set up the range. This range is relative to the entry point of the
1619 // compile unit. This is a hard coded 0 for low_pc when we're emitting
1620 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1621 if (auto *Base = CU->getBaseAddress()) {
1622 Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1623 Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1625 Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1626 Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1629 emitDebugLocEntryLocation(Entry);
1631 Asm->OutStreamer->EmitIntValue(0, Size);
1632 Asm->OutStreamer->EmitIntValue(0, Size);
1636 void DwarfDebug::emitDebugLocDWO() {
1637 Asm->OutStreamer->SwitchSection(
1638 Asm->getObjFileLowering().getDwarfLocDWOSection());
1639 for (const auto &List : DebugLocs.getLists()) {
1640 Asm->OutStreamer->EmitLabel(List.Label);
1641 for (const auto &Entry : DebugLocs.getEntries(List)) {
1642 // Just always use start_length for now - at least that's one address
1643 // rather than two. We could get fancier and try to, say, reuse an
1644 // address we know we've emitted elsewhere (the start of the function?
1645 // The start of the CU or CU subrange that encloses this range?)
1646 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1647 unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1648 Asm->EmitULEB128(idx);
1649 Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1651 emitDebugLocEntryLocation(Entry);
1653 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1658 const MCSymbol *Start, *End;
1661 // Emit a debug aranges section, containing a CU lookup for any
1662 // address we can tie back to a CU.
1663 void DwarfDebug::emitDebugARanges() {
1664 // Provides a unique id per text section.
1665 MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1667 // Filter labels by section.
1668 for (const SymbolCU &SCU : ArangeLabels) {
1669 if (SCU.Sym->isInSection()) {
1670 // Make a note of this symbol and it's section.
1671 MCSection *Section = &SCU.Sym->getSection();
1672 if (!Section->getKind().isMetadata())
1673 SectionMap[Section].push_back(SCU);
1675 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1676 // appear in the output. This sucks as we rely on sections to build
1677 // arange spans. We can do it without, but it's icky.
1678 SectionMap[nullptr].push_back(SCU);
1682 // Add terminating symbols for each section.
1683 for (const auto &I : SectionMap) {
1684 MCSection *Section = I.first;
1685 MCSymbol *Sym = nullptr;
1688 Sym = Asm->OutStreamer->endSection(Section);
1690 // Insert a final terminator.
1691 SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1694 DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1696 for (auto &I : SectionMap) {
1697 const MCSection *Section = I.first;
1698 SmallVector<SymbolCU, 8> &List = I.second;
1699 if (List.size() < 2)
1702 // If we have no section (e.g. common), just write out
1703 // individual spans for each symbol.
1705 for (const SymbolCU &Cur : List) {
1707 Span.Start = Cur.Sym;
1710 Spans[Cur.CU].push_back(Span);
1715 // Sort the symbols by offset within the section.
1716 std::sort(List.begin(), List.end(),
1717 [&](const SymbolCU &A, const SymbolCU &B) {
1718 unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1719 unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1721 // Symbols with no order assigned should be placed at the end.
1722 // (e.g. section end labels)
1730 // Build spans between each label.
1731 const MCSymbol *StartSym = List[0].Sym;
1732 for (size_t n = 1, e = List.size(); n < e; n++) {
1733 const SymbolCU &Prev = List[n - 1];
1734 const SymbolCU &Cur = List[n];
1736 // Try and build the longest span we can within the same CU.
1737 if (Cur.CU != Prev.CU) {
1739 Span.Start = StartSym;
1741 Spans[Prev.CU].push_back(Span);
1747 // Start the dwarf aranges section.
1748 Asm->OutStreamer->SwitchSection(
1749 Asm->getObjFileLowering().getDwarfARangesSection());
1751 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1753 // Build a list of CUs used.
1754 std::vector<DwarfCompileUnit *> CUs;
1755 for (const auto &it : Spans) {
1756 DwarfCompileUnit *CU = it.first;
1760 // Sort the CU list (again, to ensure consistent output order).
1761 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1762 return A->getUniqueID() < B->getUniqueID();
1765 // Emit an arange table for each CU we used.
1766 for (DwarfCompileUnit *CU : CUs) {
1767 std::vector<ArangeSpan> &List = Spans[CU];
1769 // Describe the skeleton CU's offset and length, not the dwo file's.
1770 if (auto *Skel = CU->getSkeleton())
1773 // Emit size of content not including length itself.
1774 unsigned ContentSize =
1775 sizeof(int16_t) + // DWARF ARange version number
1776 sizeof(int32_t) + // Offset of CU in the .debug_info section
1777 sizeof(int8_t) + // Pointer Size (in bytes)
1778 sizeof(int8_t); // Segment Size (in bytes)
1780 unsigned TupleSize = PtrSize * 2;
1782 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1784 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1786 ContentSize += Padding;
1787 ContentSize += (List.size() + 1) * TupleSize;
1789 // For each compile unit, write the list of spans it covers.
1790 Asm->OutStreamer->AddComment("Length of ARange Set");
1791 Asm->EmitInt32(ContentSize);
1792 Asm->OutStreamer->AddComment("DWARF Arange version number");
1793 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1794 Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1795 Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1796 Asm->OutStreamer->AddComment("Address Size (in bytes)");
1797 Asm->EmitInt8(PtrSize);
1798 Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1801 Asm->OutStreamer->EmitFill(Padding, 0xff);
1803 for (const ArangeSpan &Span : List) {
1804 Asm->EmitLabelReference(Span.Start, PtrSize);
1806 // Calculate the size as being from the span start to it's end.
1808 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1810 // For symbols without an end marker (e.g. common), we
1811 // write a single arange entry containing just that one symbol.
1812 uint64_t Size = SymSize[Span.Start];
1816 Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1820 Asm->OutStreamer->AddComment("ARange terminator");
1821 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1822 Asm->OutStreamer->EmitIntValue(0, PtrSize);
1826 // Emit visible names into a debug ranges section.
1827 void DwarfDebug::emitDebugRanges() {
1828 // Start the dwarf ranges section.
1829 Asm->OutStreamer->SwitchSection(
1830 Asm->getObjFileLowering().getDwarfRangesSection());
1832 // Size for our labels.
1833 unsigned char Size = Asm->getDataLayout().getPointerSize();
1835 // Grab the specific ranges for the compile units in the module.
1836 for (const auto &I : CUMap) {
1837 DwarfCompileUnit *TheCU = I.second;
1839 if (auto *Skel = TheCU->getSkeleton())
1842 // Iterate over the misc ranges for the compile units in the module.
1843 for (const RangeSpanList &List : TheCU->getRangeLists()) {
1844 // Emit our symbol so we can find the beginning of the range.
1845 Asm->OutStreamer->EmitLabel(List.getSym());
1847 for (const RangeSpan &Range : List.getRanges()) {
1848 const MCSymbol *Begin = Range.getStart();
1849 const MCSymbol *End = Range.getEnd();
1850 assert(Begin && "Range without a begin symbol?");
1851 assert(End && "Range without an end symbol?");
1852 if (auto *Base = TheCU->getBaseAddress()) {
1853 Asm->EmitLabelDifference(Begin, Base, Size);
1854 Asm->EmitLabelDifference(End, Base, Size);
1856 Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1857 Asm->OutStreamer->EmitSymbolValue(End, Size);
1861 // And terminate the list with two 0 values.
1862 Asm->OutStreamer->EmitIntValue(0, Size);
1863 Asm->OutStreamer->EmitIntValue(0, Size);
1868 unsigned DwarfDebug::handleMacroNodes(AsmStreamerBase *AS,
1869 DIMacroNodeArray Nodes,
1870 DwarfCompileUnit &U) {
1872 for (auto *MN : Nodes) {
1873 if (auto *M = dyn_cast<DIMacro>(MN))
1874 Size += emitMacro(AS, *M);
1875 else if (auto *F = dyn_cast<DIMacroFile>(MN))
1876 Size += emitMacroFile(AS, *F, U);
1878 llvm_unreachable("Unexpected DI type!");
1883 unsigned DwarfDebug::emitMacro(AsmStreamerBase *AS, DIMacro &M) {
1885 Size += AS->emitULEB128(M.getMacinfoType());
1886 Size += AS->emitULEB128(M.getLine());
1887 StringRef Name = M.getName();
1888 StringRef Value = M.getValue();
1889 Size += AS->emitBytes(Name);
1890 if (!Value.empty()) {
1891 // There should be one space between macro name and macro value.
1892 Size += AS->emitInt8(' ');
1893 Size += AS->emitBytes(Value);
1895 Size += AS->emitInt8('\0');
1899 unsigned DwarfDebug::emitMacroFile(AsmStreamerBase *AS, DIMacroFile &F,
1900 DwarfCompileUnit &U) {
1902 assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
1903 Size += AS->emitULEB128(dwarf::DW_MACINFO_start_file);
1904 Size += AS->emitULEB128(F.getLine());
1905 DIFile *File = F.getFile();
1907 U.getOrCreateSourceID(File->getFilename(), File->getDirectory());
1908 Size += AS->emitULEB128(FID);
1909 Size += handleMacroNodes(AS, F.getElements(), U);
1910 Size += AS->emitULEB128(dwarf::DW_MACINFO_end_file);
1914 // Emit visible names into a debug macinfo section.
1915 void DwarfDebug::emitDebugMacinfo() {
1916 if (MCSection *Macinfo = Asm->getObjFileLowering().getDwarfMacinfoSection()) {
1917 // Start the dwarf macinfo section.
1918 Asm->OutStreamer->SwitchSection(Macinfo);
1920 std::unique_ptr<AsmStreamerBase> AS(new EmittingAsmStreamer(Asm));
1921 for (const auto &P : CUMap) {
1922 auto &TheCU = *P.second;
1923 auto *SkCU = TheCU.getSkeleton();
1924 DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1925 auto *CUNode = cast<DICompileUnit>(P.first);
1926 handleMacroNodes(AS.get(), CUNode->getMacros(), U);
1928 Asm->OutStreamer->AddComment("End Of Macro List Mark");
1932 // DWARF5 Experimental Separate Dwarf emitters.
1934 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1935 std::unique_ptr<DwarfUnit> NewU) {
1936 NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1937 U.getCUNode()->getSplitDebugFilename());
1939 if (!CompilationDir.empty())
1940 NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1942 addGnuPubAttributes(*NewU, Die);
1944 SkeletonHolder.addUnit(std::move(NewU));
1947 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1948 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1949 // DW_AT_addr_base, DW_AT_ranges_base.
1950 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1952 auto OwnedUnit = make_unique<DwarfCompileUnit>(
1953 CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1954 DwarfCompileUnit &NewCU = *OwnedUnit;
1955 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1957 NewCU.initStmtList();
1959 initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1964 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1965 // compile units that would normally be in debug_info.
1966 void DwarfDebug::emitDebugInfoDWO() {
1967 assert(useSplitDwarf() && "No split dwarf debug info?");
1968 // Don't emit relocations into the dwo file.
1969 InfoHolder.emitUnits(/* UseOffsets */ true);
1972 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1973 // abbreviations for the .debug_info.dwo section.
1974 void DwarfDebug::emitDebugAbbrevDWO() {
1975 assert(useSplitDwarf() && "No split dwarf?");
1976 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1979 void DwarfDebug::emitDebugLineDWO() {
1980 assert(useSplitDwarf() && "No split dwarf?");
1981 Asm->OutStreamer->SwitchSection(
1982 Asm->getObjFileLowering().getDwarfLineDWOSection());
1983 SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
1986 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1987 // string section and is identical in format to traditional .debug_str
1989 void DwarfDebug::emitDebugStrDWO() {
1990 assert(useSplitDwarf() && "No split dwarf?");
1991 MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1992 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1996 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1997 if (!useSplitDwarf())
2000 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
2001 return &SplitTypeUnitFileTable;
2004 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2006 Hash.update(Identifier);
2007 // ... take the least significant 8 bytes and return those. Our MD5
2008 // implementation always returns its results in little endian, swap bytes
2010 MD5::MD5Result Result;
2012 return support::endian::read64le(Result + 8);
2015 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2016 StringRef Identifier, DIE &RefDie,
2017 const DICompositeType *CTy) {
2018 // Fast path if we're building some type units and one has already used the
2019 // address pool we know we're going to throw away all this work anyway, so
2020 // don't bother building dependent types.
2021 if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2024 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2026 CU.addDIETypeSignature(RefDie, *TU);
2030 bool TopLevelType = TypeUnitsUnderConstruction.empty();
2031 AddrPool.resetUsedFlag();
2033 auto OwnedUnit = make_unique<DwarfTypeUnit>(
2034 InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2035 this, &InfoHolder, getDwoLineTable(CU));
2036 DwarfTypeUnit &NewTU = *OwnedUnit;
2037 DIE &UnitDie = NewTU.getUnitDie();
2039 TypeUnitsUnderConstruction.push_back(
2040 std::make_pair(std::move(OwnedUnit), CTy));
2042 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2045 uint64_t Signature = makeTypeSignature(Identifier);
2046 NewTU.setTypeSignature(Signature);
2048 if (useSplitDwarf())
2049 NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2051 CU.applyStmtList(UnitDie);
2053 Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2056 NewTU.setType(NewTU.createTypeDIE(CTy));
2059 auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2060 TypeUnitsUnderConstruction.clear();
2062 // Types referencing entries in the address table cannot be placed in type
2064 if (AddrPool.hasBeenUsed()) {
2066 // Remove all the types built while building this type.
2067 // This is pessimistic as some of these types might not be dependent on
2068 // the type that used an address.
2069 for (const auto &TU : TypeUnitsToAdd)
2070 DwarfTypeUnits.erase(TU.second);
2072 // Construct this type in the CU directly.
2073 // This is inefficient because all the dependent types will be rebuilt
2074 // from scratch, including building them in type units, discovering that
2075 // they depend on addresses, throwing them out and rebuilding them.
2076 CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2080 // If the type wasn't dependent on fission addresses, finish adding the type
2081 // and all its dependent types.
2082 for (auto &TU : TypeUnitsToAdd)
2083 InfoHolder.addUnit(std::move(TU.first));
2085 CU.addDIETypeSignature(RefDie, NewTU);
2088 // Accelerator table mutators - add each name along with its companion
2089 // DIE to the proper table while ensuring that the name that we're going
2090 // to reference is in the string table. We do this since the names we
2091 // add may not only be identical to the names in the DIE.
2092 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2093 if (!useDwarfAccelTables())
2095 AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2098 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2099 if (!useDwarfAccelTables())
2101 AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2104 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2105 if (!useDwarfAccelTables())
2107 AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2110 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2111 if (!useDwarfAccelTables())
2113 AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);