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 "ByteStreamer.h"
15 #include "DwarfDebug.h"
18 #include "DwarfUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DIBuilder.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/ValueHandle.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MD5.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Timer.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
52 #define DEBUG_TYPE "dwarfdebug"
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
70 cl::desc("Generate dwarf aranges"),
74 enum DefaultOnOff { Default, Enable, Disable };
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
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());
122 DIType DbgVariable::getType() const {
123 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
124 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
125 // addresses instead.
126 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
127 /* Byref variables, in Blocks, are declared by the programmer as
128 "SomeType VarName;", but the compiler creates a
129 __Block_byref_x_VarName struct, and gives the variable VarName
130 either the struct, or a pointer to the struct, as its type. This
131 is necessary for various behind-the-scenes things the compiler
132 needs to do with by-reference variables in blocks.
134 However, as far as the original *programmer* is concerned, the
135 variable should still have type 'SomeType', as originally declared.
137 The following function dives into the __Block_byref_x_VarName
138 struct to find the original type of the variable. This will be
139 passed back to the code generating the type for the Debug
140 Information Entry for the variable 'VarName'. 'VarName' will then
141 have the original type 'SomeType' in its debug information.
143 The original type 'SomeType' will be the type of the field named
144 'VarName' inside the __Block_byref_x_VarName struct.
146 NOTE: In order for this to not completely fail on the debugger
147 side, the Debug Information Entry for the variable VarName needs to
148 have a DW_AT_location that tells the debugger how to unwind through
149 the pointers and __Block_byref_x_VarName struct to find the actual
150 value of the variable. The function addBlockByrefType does this. */
152 uint16_t tag = Ty.getTag();
154 if (tag == dwarf::DW_TAG_pointer_type)
155 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
157 DIArray Elements = DICompositeType(subType).getTypeArray();
158 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
159 DIDerivedType DT(Elements.getElement(i));
160 if (getName() == DT.getName())
161 return (resolve(DT.getTypeDerivedFrom()));
167 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
168 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
169 InfoHolder(A, "info_string", DIEValueAllocator),
170 UsedNonDefaultText(false),
171 SkeletonHolder(A, "skel_string", DIEValueAllocator),
172 AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
173 dwarf::DW_FORM_data4)),
174 AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
175 dwarf::DW_FORM_data4)),
176 AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
177 dwarf::DW_FORM_data4)) {
179 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
180 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
181 DwarfAddrSectionSym = 0;
182 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
183 FunctionBeginSym = FunctionEndSym = 0;
187 // Turn on accelerator tables for Darwin by default, pubnames by
188 // default for non-Darwin, and handle split dwarf.
189 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
191 if (DwarfAccelTables == Default)
192 HasDwarfAccelTables = IsDarwin;
194 HasDwarfAccelTables = DwarfAccelTables == Enable;
196 if (SplitDwarf == Default)
197 HasSplitDwarf = false;
199 HasSplitDwarf = SplitDwarf == Enable;
201 if (DwarfPubSections == Default)
202 HasDwarfPubSections = !IsDarwin;
204 HasDwarfPubSections = DwarfPubSections == Enable;
206 DwarfVersion = DwarfVersionNumber
208 : MMI->getModule()->getDwarfVersion();
211 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
216 // Switch to the specified MCSection and emit an assembler
217 // temporary label to it if SymbolStem is specified.
218 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
219 const char *SymbolStem = 0) {
220 Asm->OutStreamer.SwitchSection(Section);
224 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
225 Asm->OutStreamer.EmitLabel(TmpSym);
229 static bool isObjCClass(StringRef Name) {
230 return Name.startswith("+") || Name.startswith("-");
233 static bool hasObjCCategory(StringRef Name) {
234 if (!isObjCClass(Name))
237 return Name.find(") ") != StringRef::npos;
240 static void getObjCClassCategory(StringRef In, StringRef &Class,
241 StringRef &Category) {
242 if (!hasObjCCategory(In)) {
243 Class = In.slice(In.find('[') + 1, In.find(' '));
248 Class = In.slice(In.find('[') + 1, In.find('('));
249 Category = In.slice(In.find('[') + 1, In.find(' '));
253 static StringRef getObjCMethodName(StringRef In) {
254 return In.slice(In.find(' ') + 1, In.find(']'));
257 // Helper for sorting sections into a stable output order.
258 static bool SectionSort(const MCSection *A, const MCSection *B) {
259 std::string LA = (A ? A->getLabelBeginName() : "");
260 std::string LB = (B ? B->getLabelBeginName() : "");
264 // Add the various names to the Dwarf accelerator table names.
265 // TODO: Determine whether or not we should add names for programs
266 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
267 // is only slightly different than the lookup of non-standard ObjC names.
268 void DwarfDebug::addSubprogramNames(DwarfUnit &TheU, DISubprogram SP,
270 if (!SP.isDefinition())
272 addAccelName(SP.getName(), Die);
274 // If the linkage name is different than the name, go ahead and output
275 // that as well into the name table.
276 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
277 addAccelName(SP.getLinkageName(), Die);
279 // If this is an Objective-C selector name add it to the ObjC accelerator
281 if (isObjCClass(SP.getName())) {
282 StringRef Class, Category;
283 getObjCClassCategory(SP.getName(), Class, Category);
284 addAccelObjC(Class, Die);
286 addAccelObjC(Category, Die);
287 // Also add the base method name to the name table.
288 addAccelName(getObjCMethodName(SP.getName()), Die);
292 /// isSubprogramContext - Return true if Context is either a subprogram
293 /// or another context nested inside a subprogram.
294 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
297 DIDescriptor D(Context);
298 if (D.isSubprogram())
301 return isSubprogramContext(resolve(DIType(Context).getContext()));
305 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
306 // and DW_AT_high_pc attributes. If there are global variables in this
307 // scope then create and insert DIEs for these variables.
308 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
310 DIE *SPDie = SPCU.getDIE(SP);
312 assert(SPDie && "Unable to find subprogram DIE!");
314 // If we're updating an abstract DIE, then we will be adding the children and
315 // object pointer later on. But what we don't want to do is process the
316 // concrete DIE twice.
317 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
318 // Pick up abstract subprogram DIE.
319 SPDie = SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
320 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
322 DISubprogram SPDecl = SP.getFunctionDeclaration();
323 if (!SPDecl.isSubprogram()) {
324 // There is not any need to generate specification DIE for a function
325 // defined at compile unit level. If a function is defined inside another
326 // function then gdb prefers the definition at top level and but does not
327 // expect specification DIE in parent function. So avoid creating
328 // specification DIE for a function defined inside a function.
329 DIScope SPContext = resolve(SP.getContext());
330 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
331 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
332 SPCU.addFlag(SPDie, dwarf::DW_AT_declaration);
335 DICompositeType SPTy = SP.getType();
336 DIArray Args = SPTy.getTypeArray();
337 uint16_t SPTag = SPTy.getTag();
338 if (SPTag == dwarf::DW_TAG_subroutine_type)
339 SPCU.constructSubprogramArguments(*SPDie, Args);
340 DIE *SPDeclDie = SPDie;
342 SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
343 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
348 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
350 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
351 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
352 SPCU.addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
354 // Add name to the name table, we do this here because we're guaranteed
355 // to have concrete versions of our DW_TAG_subprogram nodes.
356 addSubprogramNames(SPCU, SP, SPDie);
361 /// Check whether we should create a DIE for the given Scope, return true
362 /// if we don't create a DIE (the corresponding DIE is null).
363 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
364 if (Scope->isAbstractScope())
367 // We don't create a DIE if there is no Range.
368 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
372 if (Ranges.size() > 1)
375 // We don't create a DIE if we have a single Range and the end label
377 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
378 MCSymbol *End = getLabelAfterInsn(RI->second);
382 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE *D,
383 dwarf::Attribute A, const MCSymbol *L,
384 const MCSymbol *Sec) {
385 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
386 U.addSectionLabel(D, A, L);
388 U.addSectionDelta(D, A, L, Sec);
391 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE *ScopeDIE,
392 const SmallVectorImpl<InsnRange> &Range) {
393 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
394 // emitting it appropriately.
395 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
397 // Under fission, ranges are specified by constant offsets relative to the
398 // CU's DW_AT_GNU_ranges_base.
400 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
401 DwarfDebugRangeSectionSym);
403 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
404 DwarfDebugRangeSectionSym);
406 RangeSpanList List(RangeSym);
407 for (const InsnRange &R : Range) {
408 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
409 List.addRange(std::move(Span));
412 // Add the range list to the set of ranges to be emitted.
413 TheCU.addRangeList(std::move(List));
416 // Construct new DW_TAG_lexical_block for this scope and attach
417 // DW_AT_low_pc/DW_AT_high_pc labels.
418 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
419 LexicalScope *Scope) {
420 if (isLexicalScopeDIENull(Scope))
423 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
424 if (Scope->isAbstractScope())
427 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
429 // If we have multiple ranges, emit them into the range section.
430 if (ScopeRanges.size() > 1) {
431 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
435 // Construct the address range for this DIE.
436 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
437 MCSymbol *Start = getLabelBeforeInsn(RI->first);
438 MCSymbol *End = getLabelAfterInsn(RI->second);
439 assert(End && "End label should not be null!");
441 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
442 assert(End->isDefined() && "Invalid end label for an inlined scope!");
444 attachLowHighPC(TheCU, ScopeDIE, Start, End);
449 // This scope represents inlined body of a function. Construct DIE to
450 // represent this concrete inlined copy of the function.
451 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
452 LexicalScope *Scope) {
453 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
454 assert(!ScopeRanges.empty() &&
455 "LexicalScope does not have instruction markers!");
457 if (!Scope->getScopeNode())
459 DIScope DS(Scope->getScopeNode());
460 DISubprogram InlinedSP = getDISubprogram(DS);
461 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
463 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
467 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
468 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
470 // If we have multiple ranges, emit them into the range section.
471 if (ScopeRanges.size() > 1)
472 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
474 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
475 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
476 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
478 if (StartLabel == 0 || EndLabel == 0)
479 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
481 assert(StartLabel->isDefined() &&
482 "Invalid starting label for an inlined scope!");
483 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
485 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
488 InlinedSubprogramDIEs.insert(OriginDIE);
490 // Add the call site information to the DIE.
491 DILocation DL(Scope->getInlinedAt());
492 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
493 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
494 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
496 // Add name to the name table, we do this here because we're guaranteed
497 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
498 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
503 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit &TheCU,
505 SmallVectorImpl<DIE *> &Children) {
506 DIE *ObjectPointer = NULL;
508 // Collect arguments for current function.
509 if (LScopes.isCurrentFunctionScope(Scope)) {
510 for (DbgVariable *ArgDV : CurrentFnArguments)
513 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
514 Children.push_back(Arg);
515 if (ArgDV->isObjectPointer())
519 // If this is a variadic function, add an unspecified parameter.
520 DISubprogram SP(Scope->getScopeNode());
521 DIArray FnArgs = SP.getType().getTypeArray();
522 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
523 .isUnspecifiedParameter()) {
524 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
525 Children.push_back(Ellipsis);
529 // Collect lexical scope children first.
530 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
532 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope())) {
533 Children.push_back(Variable);
534 if (DV->isObjectPointer())
535 ObjectPointer = Variable;
537 for (LexicalScope *LS : Scope->getChildren())
538 if (DIE *Nested = constructScopeDIE(TheCU, LS))
539 Children.push_back(Nested);
540 return ObjectPointer;
543 // Construct a DIE for this scope.
544 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
545 LexicalScope *Scope) {
546 if (!Scope || !Scope->getScopeNode())
549 DIScope DS(Scope->getScopeNode());
551 SmallVector<DIE *, 8> Children;
552 DIE *ObjectPointer = NULL;
553 bool ChildrenCreated = false;
555 // We try to create the scope DIE first, then the children DIEs. This will
556 // avoid creating un-used children then removing them later when we find out
557 // the scope DIE is null.
558 DIE *ScopeDIE = NULL;
559 if (Scope->getInlinedAt())
560 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
561 else if (DS.isSubprogram()) {
562 ProcessedSPNodes.insert(DS);
563 if (Scope->isAbstractScope()) {
564 ScopeDIE = TheCU.getDIE(DS);
565 // Note down abstract DIE.
567 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
569 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
571 // Early exit when we know the scope DIE is going to be null.
572 if (isLexicalScopeDIENull(Scope))
575 // We create children here when we know the scope DIE is not going to be
576 // null and the children will be added to the scope DIE.
577 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
578 ChildrenCreated = true;
580 // There is no need to emit empty lexical block DIE.
581 std::pair<ImportedEntityMap::const_iterator,
582 ImportedEntityMap::const_iterator> Range =
584 ScopesWithImportedEntities.begin(),
585 ScopesWithImportedEntities.end(),
586 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
588 if (Children.empty() && Range.first == Range.second)
590 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
591 assert(ScopeDIE && "Scope DIE should not be null.");
592 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
594 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
598 assert(Children.empty() &&
599 "We create children only when the scope DIE is not null.");
602 if (!ChildrenCreated)
603 // We create children when the scope DIE is not null.
604 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
607 for (DIE *I : Children)
608 ScopeDIE->addChild(I);
610 if (DS.isSubprogram() && ObjectPointer != NULL)
611 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
616 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE *D) const {
617 if (!GenerateGnuPubSections)
620 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
623 // Create new DwarfCompileUnit for the given metadata node with tag
624 // DW_TAG_compile_unit.
625 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
626 StringRef FN = DIUnit.getFilename();
627 CompilationDir = DIUnit.getDirectory();
629 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
630 auto OwnedUnit = make_unique<DwarfCompileUnit>(
631 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
632 DwarfCompileUnit &NewCU = *OwnedUnit;
633 InfoHolder.addUnit(std::move(OwnedUnit));
635 // LTO with assembly output shares a single line table amongst multiple CUs.
636 // To avoid the compilation directory being ambiguous, let the line table
637 // explicitly describe the directory of all files, never relying on the
638 // compilation directory.
639 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
640 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
641 NewCU.getUniqueID(), CompilationDir);
643 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
644 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
645 DIUnit.getLanguage());
646 NewCU.addString(Die, dwarf::DW_AT_name, FN);
648 if (!useSplitDwarf()) {
649 NewCU.initStmtList(DwarfLineSectionSym);
651 // If we're using split dwarf the compilation dir is going to be in the
652 // skeleton CU and so we don't need to duplicate it here.
653 if (!CompilationDir.empty())
654 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
656 addGnuPubAttributes(NewCU, Die);
659 if (DIUnit.isOptimized())
660 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
662 StringRef Flags = DIUnit.getFlags();
664 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
666 if (unsigned RVer = DIUnit.getRunTimeVersion())
667 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
668 dwarf::DW_FORM_data1, RVer);
673 if (useSplitDwarf()) {
674 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
675 DwarfInfoDWOSectionSym);
676 NewCU.setSkeleton(constructSkeletonCU(NewCU));
678 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
679 DwarfInfoSectionSym);
681 CUMap.insert(std::make_pair(DIUnit, &NewCU));
682 CUDieMap.insert(std::make_pair(Die, &NewCU));
686 // Construct subprogram DIE.
687 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
689 // FIXME: We should only call this routine once, however, during LTO if a
690 // program is defined in multiple CUs we could end up calling it out of
691 // beginModule as we walk the CUs.
693 DwarfCompileUnit *&CURef = SPMap[N];
699 if (!SP.isDefinition())
700 // This is a method declaration which will be handled while constructing
704 DIE *SubprogramDie = TheCU.getOrCreateSubprogramDIE(SP);
706 // Expose as a global name.
707 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
710 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
712 DIImportedEntity Module(N);
713 assert(Module.Verify());
714 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
715 constructImportedEntityDIE(TheCU, Module, D);
718 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
719 const MDNode *N, DIE *Context) {
720 DIImportedEntity Module(N);
721 assert(Module.Verify());
722 return constructImportedEntityDIE(TheCU, Module, Context);
725 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
726 const DIImportedEntity &Module,
728 assert(Module.Verify() &&
729 "Use one of the MDNode * overloads to handle invalid metadata");
730 assert(Context && "Should always have a context for an imported_module");
731 DIE *IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
733 DIDescriptor Entity = resolve(Module.getEntity());
734 if (Entity.isNameSpace())
735 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
736 else if (Entity.isSubprogram())
737 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
738 else if (Entity.isType())
739 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
741 EntityDie = TheCU.getDIE(Entity);
742 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
743 Module.getContext().getFilename(),
744 Module.getContext().getDirectory());
745 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
746 StringRef Name = Module.getName();
748 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
751 // Emit all Dwarf sections that should come prior to the content. Create
752 // global DIEs and emit initial debug info sections. This is invoked by
753 // the target AsmPrinter.
754 void DwarfDebug::beginModule() {
755 if (DisableDebugInfoPrinting)
758 const Module *M = MMI->getModule();
760 // If module has named metadata anchors then use them, otherwise scan the
761 // module using debug info finder to collect debug info.
762 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
765 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
767 // Emit initial sections so we can reference labels later.
770 SingleCU = CU_Nodes->getNumOperands() == 1;
772 for (MDNode *N : CU_Nodes->operands()) {
773 DICompileUnit CUNode(N);
774 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
775 DIArray ImportedEntities = CUNode.getImportedEntities();
776 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
777 ScopesWithImportedEntities.push_back(std::make_pair(
778 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
779 ImportedEntities.getElement(i)));
780 std::sort(ScopesWithImportedEntities.begin(),
781 ScopesWithImportedEntities.end(), less_first());
782 DIArray GVs = CUNode.getGlobalVariables();
783 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
784 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
785 DIArray SPs = CUNode.getSubprograms();
786 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
787 constructSubprogramDIE(CU, SPs.getElement(i));
788 DIArray EnumTypes = CUNode.getEnumTypes();
789 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
790 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
791 DIArray RetainedTypes = CUNode.getRetainedTypes();
792 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
793 DIType Ty(RetainedTypes.getElement(i));
794 // The retained types array by design contains pointers to
795 // MDNodes rather than DIRefs. Unique them here.
796 DIType UniqueTy(resolve(Ty.getRef()));
797 CU.getOrCreateTypeDIE(UniqueTy);
799 // Emit imported_modules last so that the relevant context is already
801 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
802 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
805 // Tell MMI that we have debug info.
806 MMI->setDebugInfoAvailability(true);
808 // Prime section data.
809 SectionMap[Asm->getObjFileLowering().getTextSection()];
812 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
813 void DwarfDebug::computeInlinedDIEs() {
814 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
815 for (DIE *ISP : InlinedSubprogramDIEs)
816 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
818 for (const auto &AI : AbstractSPDies) {
819 DIE *ISP = AI.second;
820 if (InlinedSubprogramDIEs.count(ISP))
822 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
826 // Collect info for variables that were optimized out.
827 void DwarfDebug::collectDeadVariables() {
828 const Module *M = MMI->getModule();
830 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
831 for (MDNode *N : CU_Nodes->operands()) {
832 DICompileUnit TheCU(N);
833 DIArray Subprograms = TheCU.getSubprograms();
834 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
835 DISubprogram SP(Subprograms.getElement(i));
836 if (ProcessedSPNodes.count(SP) != 0)
838 if (!SP.isSubprogram())
840 if (!SP.isDefinition())
842 DIArray Variables = SP.getVariables();
843 if (Variables.getNumElements() == 0)
846 // Construct subprogram DIE and add variables DIEs.
847 DwarfCompileUnit *SPCU =
848 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
849 assert(SPCU && "Unable to find Compile Unit!");
850 // FIXME: See the comment in constructSubprogramDIE about duplicate
852 constructSubprogramDIE(*SPCU, SP);
853 DIE *SPDIE = SPCU->getDIE(SP);
854 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
855 DIVariable DV(Variables.getElement(vi));
856 if (!DV.isVariable())
858 DbgVariable NewVar(DV, NULL, this);
859 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
860 SPDIE->addChild(VariableDIE);
867 void DwarfDebug::finalizeModuleInfo() {
868 // Collect info for variables that were optimized out.
869 collectDeadVariables();
871 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
872 computeInlinedDIEs();
874 // Handle anything that needs to be done on a per-unit basis after
875 // all other generation.
876 for (const auto &TheU : getUnits()) {
877 // Emit DW_AT_containing_type attribute to connect types with their
878 // vtable holding type.
879 TheU->constructContainingTypeDIEs();
881 // Add CU specific attributes if we need to add any.
882 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
883 // If we're splitting the dwarf out now that we've got the entire
884 // CU then add the dwo id to it.
885 DwarfCompileUnit *SkCU =
886 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
887 if (useSplitDwarf()) {
888 // Emit a unique identifier for this CU.
889 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
890 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
891 dwarf::DW_FORM_data8, ID);
892 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
893 dwarf::DW_FORM_data8, ID);
895 // We don't keep track of which addresses are used in which CU so this
896 // is a bit pessimistic under LTO.
897 if (!AddrPool.isEmpty())
898 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
899 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
900 DwarfAddrSectionSym);
901 if (!TheU->getRangeLists().empty())
902 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
903 dwarf::DW_AT_GNU_ranges_base,
904 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
907 // If we have code split among multiple sections or non-contiguous
908 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
909 // remain in the .o file, otherwise add a DW_AT_low_pc.
910 // FIXME: We should use ranges allow reordering of code ala
911 // .subsections_via_symbols in mach-o. This would mean turning on
912 // ranges for all subprogram DIEs for mach-o.
913 DwarfCompileUnit &U =
914 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
915 unsigned NumRanges = TheU->getRanges().size();
918 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
919 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
920 DwarfDebugRangeSectionSym);
922 // A DW_AT_low_pc attribute may also be specified in combination with
923 // DW_AT_ranges to specify the default base address for use in
924 // location lists (see Section 2.6.2) and range lists (see Section
926 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
929 RangeSpan &Range = TheU->getRanges().back();
930 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
932 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
939 // Compute DIE offsets and sizes.
940 InfoHolder.computeSizeAndOffsets();
942 SkeletonHolder.computeSizeAndOffsets();
945 void DwarfDebug::endSections() {
946 // Filter labels by section.
947 for (const SymbolCU &SCU : ArangeLabels) {
948 if (SCU.Sym->isInSection()) {
949 // Make a note of this symbol and it's section.
950 const MCSection *Section = &SCU.Sym->getSection();
951 if (!Section->getKind().isMetadata())
952 SectionMap[Section].push_back(SCU);
954 // Some symbols (e.g. common/bss on mach-o) can have no section but still
955 // appear in the output. This sucks as we rely on sections to build
956 // arange spans. We can do it without, but it's icky.
957 SectionMap[NULL].push_back(SCU);
961 // Build a list of sections used.
962 std::vector<const MCSection *> Sections;
963 for (const auto &it : SectionMap) {
964 const MCSection *Section = it.first;
965 Sections.push_back(Section);
968 // Sort the sections into order.
969 // This is only done to ensure consistent output order across different runs.
970 std::sort(Sections.begin(), Sections.end(), SectionSort);
972 // Add terminating symbols for each section.
973 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
974 const MCSection *Section = Sections[ID];
975 MCSymbol *Sym = NULL;
978 // We can't call MCSection::getLabelEndName, as it's only safe to do so
979 // if we know the section name up-front. For user-created sections, the
980 // resulting label may not be valid to use as a label. (section names can
981 // use a greater set of characters on some systems)
982 Sym = Asm->GetTempSymbol("debug_end", ID);
983 Asm->OutStreamer.SwitchSection(Section);
984 Asm->OutStreamer.EmitLabel(Sym);
987 // Insert a final terminator.
988 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
992 // Emit all Dwarf sections that should come after the content.
993 void DwarfDebug::endModule() {
1000 // End any existing sections.
1001 // TODO: Does this need to happen?
1004 // Finalize the debug info for the module.
1005 finalizeModuleInfo();
1009 // Emit all the DIEs into a debug info section.
1012 // Corresponding abbreviations into a abbrev section.
1013 emitAbbreviations();
1015 // Emit info into a debug aranges section.
1016 if (GenerateARangeSection)
1019 // Emit info into a debug ranges section.
1022 if (useSplitDwarf()) {
1025 emitDebugAbbrevDWO();
1027 // Emit DWO addresses.
1028 AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1031 // Emit info into a debug loc section.
1034 // Emit info into the dwarf accelerator table sections.
1035 if (useDwarfAccelTables()) {
1038 emitAccelNamespaces();
1042 // Emit the pubnames and pubtypes sections if requested.
1043 if (HasDwarfPubSections) {
1044 emitDebugPubNames(GenerateGnuPubSections);
1045 emitDebugPubTypes(GenerateGnuPubSections);
1051 // Reset these for the next Module if we have one.
1055 // Find abstract variable, if any, associated with Var.
1056 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1057 DebugLoc ScopeLoc) {
1058 LLVMContext &Ctx = DV->getContext();
1059 // More then one inlined variable corresponds to one abstract variable.
1060 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1061 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1063 return AbsDbgVariable;
1065 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1069 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1070 addScopeVariable(Scope, AbsDbgVariable);
1071 AbstractVariables[Var] = AbsDbgVariable;
1072 return AbsDbgVariable;
1075 // If Var is a current function argument then add it to CurrentFnArguments list.
1076 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1077 if (!LScopes.isCurrentFunctionScope(Scope))
1079 DIVariable DV = Var->getVariable();
1080 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1082 unsigned ArgNo = DV.getArgNumber();
1086 size_t Size = CurrentFnArguments.size();
1088 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1089 // llvm::Function argument size is not good indicator of how many
1090 // arguments does the function have at source level.
1092 CurrentFnArguments.resize(ArgNo * 2);
1093 CurrentFnArguments[ArgNo - 1] = Var;
1097 // Collect variable information from side table maintained by MMI.
1098 void DwarfDebug::collectVariableInfoFromMMITable(
1099 SmallPtrSet<const MDNode *, 16> &Processed) {
1100 for (const auto &VI : MMI->getVariableDbgInfo()) {
1103 Processed.insert(VI.Var);
1104 DIVariable DV(VI.Var);
1105 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1107 // If variable scope is not found then skip this variable.
1111 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1112 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1113 RegVar->setFrameIndex(VI.Slot);
1114 if (!addCurrentFnArgument(RegVar, Scope))
1115 addScopeVariable(Scope, RegVar);
1117 AbsDbgVariable->setFrameIndex(VI.Slot);
1121 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1123 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1124 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1125 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1126 MI->getOperand(0).getReg() &&
1127 (MI->getOperand(1).isImm() ||
1128 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1131 // Get .debug_loc entry for the instruction range starting at MI.
1132 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1133 const MCSymbol *FLabel,
1134 const MCSymbol *SLabel,
1135 const MachineInstr *MI,
1136 DwarfCompileUnit *Unit) {
1137 const MDNode *Var = MI->getDebugVariable();
1139 assert(MI->getNumOperands() == 3);
1140 if (MI->getOperand(0).isReg()) {
1141 MachineLocation MLoc;
1142 // If the second operand is an immediate, this is a
1143 // register-indirect address.
1144 if (!MI->getOperand(1).isImm())
1145 MLoc.set(MI->getOperand(0).getReg());
1147 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1148 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1150 if (MI->getOperand(0).isImm())
1151 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1152 if (MI->getOperand(0).isFPImm())
1153 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1155 if (MI->getOperand(0).isCImm())
1156 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1159 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1162 // Find variables for each lexical scope.
1164 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1166 // Grab the variable info that was squirreled away in the MMI side-table.
1167 collectVariableInfoFromMMITable(Processed);
1169 for (const MDNode *Var : UserVariables) {
1170 if (Processed.count(Var))
1173 // History contains relevant DBG_VALUE instructions for Var and instructions
1175 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1176 if (History.empty())
1178 const MachineInstr *MInsn = History.front();
1181 LexicalScope *Scope = NULL;
1182 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1183 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1184 Scope = LScopes.getCurrentFunctionScope();
1185 else if (MDNode *IA = DV.getInlinedAt())
1186 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1188 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1189 // If variable scope is not found then skip this variable.
1193 Processed.insert(DV);
1194 assert(MInsn->isDebugValue() && "History must begin with debug value");
1195 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1196 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1197 if (!addCurrentFnArgument(RegVar, Scope))
1198 addScopeVariable(Scope, RegVar);
1200 AbsVar->setMInsn(MInsn);
1202 // Simplify ranges that are fully coalesced.
1203 if (History.size() <= 1 ||
1204 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1205 RegVar->setMInsn(MInsn);
1209 // Handle multiple DBG_VALUE instructions describing one variable.
1210 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1212 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1213 DebugLocList &LocList = DotDebugLocEntries.back();
1215 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1216 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1217 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1218 HI = History.begin(),
1221 const MachineInstr *Begin = *HI;
1222 assert(Begin->isDebugValue() && "Invalid History entry");
1224 // Check if DBG_VALUE is truncating a range.
1225 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1226 !Begin->getOperand(0).getReg())
1229 // Compute the range for a register location.
1230 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1231 const MCSymbol *SLabel = 0;
1234 // If Begin is the last instruction in History then its value is valid
1235 // until the end of the function.
1236 SLabel = FunctionEndSym;
1238 const MachineInstr *End = HI[1];
1239 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1240 << "\t" << *Begin << "\t" << *End << "\n");
1241 if (End->isDebugValue())
1242 SLabel = getLabelBeforeInsn(End);
1244 // End is a normal instruction clobbering the range.
1245 SLabel = getLabelAfterInsn(End);
1246 assert(SLabel && "Forgot label after clobber instruction");
1251 // The value is valid until the next DBG_VALUE or clobber.
1252 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1253 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1254 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1255 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1256 DebugLoc.push_back(std::move(Loc));
1260 // Collect info for variables that were optimized out.
1261 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1262 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1263 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1264 DIVariable DV(Variables.getElement(i));
1265 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1267 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1268 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1272 // Return Label preceding the instruction.
1273 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1274 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1275 assert(Label && "Didn't insert label before instruction");
1279 // Return Label immediately following the instruction.
1280 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1281 return LabelsAfterInsn.lookup(MI);
1284 // Process beginning of an instruction.
1285 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1288 // Check if source location changes, but ignore DBG_VALUE locations.
1289 if (!MI->isDebugValue()) {
1290 DebugLoc DL = MI->getDebugLoc();
1291 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1294 if (DL == PrologEndLoc) {
1295 Flags |= DWARF2_FLAG_PROLOGUE_END;
1296 PrologEndLoc = DebugLoc();
1298 if (PrologEndLoc.isUnknown())
1299 Flags |= DWARF2_FLAG_IS_STMT;
1301 if (!DL.isUnknown()) {
1302 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1303 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1305 recordSourceLine(0, 0, 0, 0);
1309 // Insert labels where requested.
1310 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1311 LabelsBeforeInsn.find(MI);
1314 if (I == LabelsBeforeInsn.end())
1317 // Label already assigned.
1322 PrevLabel = MMI->getContext().CreateTempSymbol();
1323 Asm->OutStreamer.EmitLabel(PrevLabel);
1325 I->second = PrevLabel;
1328 // Process end of an instruction.
1329 void DwarfDebug::endInstruction() {
1331 // Don't create a new label after DBG_VALUE instructions.
1332 // They don't generate code.
1333 if (!CurMI->isDebugValue())
1336 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1337 LabelsAfterInsn.find(CurMI);
1341 if (I == LabelsAfterInsn.end())
1344 // Label already assigned.
1348 // We need a label after this instruction.
1350 PrevLabel = MMI->getContext().CreateTempSymbol();
1351 Asm->OutStreamer.EmitLabel(PrevLabel);
1353 I->second = PrevLabel;
1356 // Each LexicalScope has first instruction and last instruction to mark
1357 // beginning and end of a scope respectively. Create an inverse map that list
1358 // scopes starts (and ends) with an instruction. One instruction may start (or
1359 // end) multiple scopes. Ignore scopes that are not reachable.
1360 void DwarfDebug::identifyScopeMarkers() {
1361 SmallVector<LexicalScope *, 4> WorkList;
1362 WorkList.push_back(LScopes.getCurrentFunctionScope());
1363 while (!WorkList.empty()) {
1364 LexicalScope *S = WorkList.pop_back_val();
1366 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1367 if (!Children.empty())
1368 WorkList.append(Children.begin(), Children.end());
1370 if (S->isAbstractScope())
1373 for (const InsnRange &R : S->getRanges()) {
1374 assert(R.first && "InsnRange does not have first instruction!");
1375 assert(R.second && "InsnRange does not have second instruction!");
1376 requestLabelBeforeInsn(R.first);
1377 requestLabelAfterInsn(R.second);
1382 // Gather pre-function debug information. Assumes being called immediately
1383 // after the function entry point has been emitted.
1384 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1387 // If there's no debug info for the function we're not going to do anything.
1388 if (!MMI->hasDebugInfo())
1391 // Grab the lexical scopes for the function, if we don't have any of those
1392 // then we're not going to be able to do anything.
1393 LScopes.initialize(*MF);
1394 if (LScopes.empty())
1397 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1399 // Make sure that each lexical scope will have a begin/end label.
1400 identifyScopeMarkers();
1402 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1403 // belongs to so that we add to the correct per-cu line table in the
1405 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1406 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1407 assert(TheCU && "Unable to find compile unit!");
1408 if (Asm->OutStreamer.hasRawTextSupport())
1409 // Use a single line table if we are generating assembly.
1410 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1412 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1414 // Emit a label for the function so that we have a beginning address.
1415 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1416 // Assumes in correct section after the entry point.
1417 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1419 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1420 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1421 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1423 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1425 bool AtBlockEntry = true;
1426 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1428 const MachineInstr *MI = II;
1430 if (MI->isDebugValue()) {
1431 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1433 // Keep track of user variables.
1434 const MDNode *Var = MI->getDebugVariable();
1436 // Variable is in a register, we need to check for clobbers.
1437 if (isDbgValueInDefinedReg(MI))
1438 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1440 // Check the history of this variable.
1441 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1442 if (History.empty()) {
1443 UserVariables.push_back(Var);
1444 // The first mention of a function argument gets the FunctionBeginSym
1445 // label, so arguments are visible when breaking at function entry.
1447 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1448 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1449 LabelsBeforeInsn[MI] = FunctionBeginSym;
1451 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1452 const MachineInstr *Prev = History.back();
1453 if (Prev->isDebugValue()) {
1454 // Coalesce identical entries at the end of History.
1455 if (History.size() >= 2 &&
1456 Prev->isIdenticalTo(History[History.size() - 2])) {
1457 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1458 << "\t" << *Prev << "\t"
1459 << *History[History.size() - 2] << "\n");
1463 // Terminate old register assignments that don't reach MI;
1464 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1465 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1466 isDbgValueInDefinedReg(Prev)) {
1467 // Previous register assignment needs to terminate at the end of
1469 MachineBasicBlock::const_iterator LastMI =
1470 PrevMBB->getLastNonDebugInstr();
1471 if (LastMI == PrevMBB->end()) {
1472 // Drop DBG_VALUE for empty range.
1473 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1474 << "\t" << *Prev << "\n");
1476 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1477 // Terminate after LastMI.
1478 History.push_back(LastMI);
1482 History.push_back(MI);
1484 // Not a DBG_VALUE instruction.
1485 if (!MI->isPosition())
1486 AtBlockEntry = false;
1488 // First known non-DBG_VALUE and non-frame setup location marks
1489 // the beginning of the function body.
1490 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1491 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1492 PrologEndLoc = MI->getDebugLoc();
1494 // Check if the instruction clobbers any registers with debug vars.
1495 for (const MachineOperand &MO : MI->operands()) {
1496 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1498 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1501 const MDNode *Var = LiveUserVar[Reg];
1504 // Reg is now clobbered.
1505 LiveUserVar[Reg] = 0;
1507 // Was MD last defined by a DBG_VALUE referring to Reg?
1508 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1509 if (HistI == DbgValues.end())
1511 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1512 if (History.empty())
1514 const MachineInstr *Prev = History.back();
1515 // Sanity-check: Register assignments are terminated at the end of
1517 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1519 // Is the variable still in Reg?
1520 if (!isDbgValueInDefinedReg(Prev) ||
1521 Prev->getOperand(0).getReg() != Reg)
1523 // Var is clobbered. Make sure the next instruction gets a label.
1524 History.push_back(MI);
1531 for (auto &I : DbgValues) {
1532 SmallVectorImpl<const MachineInstr *> &History = I.second;
1533 if (History.empty())
1536 // Make sure the final register assignments are terminated.
1537 const MachineInstr *Prev = History.back();
1538 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1539 const MachineBasicBlock *PrevMBB = Prev->getParent();
1540 MachineBasicBlock::const_iterator LastMI =
1541 PrevMBB->getLastNonDebugInstr();
1542 if (LastMI == PrevMBB->end())
1543 // Drop DBG_VALUE for empty range.
1545 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1546 // Terminate after LastMI.
1547 History.push_back(LastMI);
1550 // Request labels for the full history.
1551 for (const MachineInstr *MI : History) {
1552 if (MI->isDebugValue())
1553 requestLabelBeforeInsn(MI);
1555 requestLabelAfterInsn(MI);
1559 PrevInstLoc = DebugLoc();
1560 PrevLabel = FunctionBeginSym;
1562 // Record beginning of function.
1563 if (!PrologEndLoc.isUnknown()) {
1564 DebugLoc FnStartDL =
1565 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1567 FnStartDL.getLine(), FnStartDL.getCol(),
1568 FnStartDL.getScope(MF->getFunction()->getContext()),
1569 // We'd like to list the prologue as "not statements" but GDB behaves
1570 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1571 DWARF2_FLAG_IS_STMT);
1575 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1576 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1577 DIVariable DV = Var->getVariable();
1578 // Variables with positive arg numbers are parameters.
1579 if (unsigned ArgNum = DV.getArgNumber()) {
1580 // Keep all parameters in order at the start of the variable list to ensure
1581 // function types are correct (no out-of-order parameters)
1583 // This could be improved by only doing it for optimized builds (unoptimized
1584 // builds have the right order to begin with), searching from the back (this
1585 // would catch the unoptimized case quickly), or doing a binary search
1586 // rather than linear search.
1587 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1588 while (I != Vars.end()) {
1589 unsigned CurNum = (*I)->getVariable().getArgNumber();
1590 // A local (non-parameter) variable has been found, insert immediately
1594 // A later indexed parameter has been found, insert immediately before it.
1595 if (CurNum > ArgNum)
1599 Vars.insert(I, Var);
1603 Vars.push_back(Var);
1606 // Gather and emit post-function debug information.
1607 void DwarfDebug::endFunction(const MachineFunction *MF) {
1608 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1609 // though the beginFunction may not be called at all.
1610 // We should handle both cases.
1614 assert(CurFn == MF);
1617 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1618 // If we don't have a lexical scope for this function then there will
1619 // be a hole in the range information. Keep note of this by setting the
1620 // previously used section to nullptr.
1621 PrevSection = nullptr;
1627 // Define end label for subprogram.
1628 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1629 // Assumes in correct section after the entry point.
1630 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1632 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1633 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1635 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1636 collectVariableInfo(ProcessedVars);
1638 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1639 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1641 // Construct abstract scopes.
1642 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1643 DISubprogram SP(AScope->getScopeNode());
1644 if (SP.isSubprogram()) {
1645 // Collect info for variables that were optimized out.
1646 DIArray Variables = SP.getVariables();
1647 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1648 DIVariable DV(Variables.getElement(i));
1649 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1651 // Check that DbgVariable for DV wasn't created earlier, when
1652 // findAbstractVariable() was called for inlined instance of DV.
1653 LLVMContext &Ctx = DV->getContext();
1654 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1655 if (AbstractVariables.lookup(CleanDV))
1657 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1658 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1661 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1662 constructScopeDIE(TheCU, AScope);
1665 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1666 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1667 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1669 // Add the range of this function to the list of ranges for the CU.
1670 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1671 TheCU.addRange(std::move(Span));
1672 PrevSection = Asm->getCurrentSection();
1676 for (auto &I : ScopeVariables)
1677 DeleteContainerPointers(I.second);
1678 ScopeVariables.clear();
1679 DeleteContainerPointers(CurrentFnArguments);
1680 UserVariables.clear();
1682 AbstractVariables.clear();
1683 LabelsBeforeInsn.clear();
1684 LabelsAfterInsn.clear();
1689 // Register a source line with debug info. Returns the unique label that was
1690 // emitted and which provides correspondence to the source line list.
1691 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1696 unsigned Discriminator = 0;
1698 DIDescriptor Scope(S);
1700 if (Scope.isCompileUnit()) {
1701 DICompileUnit CU(S);
1702 Fn = CU.getFilename();
1703 Dir = CU.getDirectory();
1704 } else if (Scope.isFile()) {
1706 Fn = F.getFilename();
1707 Dir = F.getDirectory();
1708 } else if (Scope.isSubprogram()) {
1710 Fn = SP.getFilename();
1711 Dir = SP.getDirectory();
1712 } else if (Scope.isLexicalBlockFile()) {
1713 DILexicalBlockFile DBF(S);
1714 Fn = DBF.getFilename();
1715 Dir = DBF.getDirectory();
1716 } else if (Scope.isLexicalBlock()) {
1717 DILexicalBlock DB(S);
1718 Fn = DB.getFilename();
1719 Dir = DB.getDirectory();
1720 Discriminator = DB.getDiscriminator();
1722 llvm_unreachable("Unexpected scope info");
1724 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1725 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1726 .getOrCreateSourceID(Fn, Dir);
1728 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1732 //===----------------------------------------------------------------------===//
1734 //===----------------------------------------------------------------------===//
1736 // Emit initial Dwarf sections with a label at the start of each one.
1737 void DwarfDebug::emitSectionLabels() {
1738 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1740 // Dwarf sections base addresses.
1741 DwarfInfoSectionSym =
1742 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1743 if (useSplitDwarf())
1744 DwarfInfoDWOSectionSym =
1745 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1746 DwarfAbbrevSectionSym =
1747 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1748 if (useSplitDwarf())
1749 DwarfAbbrevDWOSectionSym = emitSectionSym(
1750 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1751 if (GenerateARangeSection)
1752 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1754 DwarfLineSectionSym =
1755 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1756 if (GenerateGnuPubSections) {
1757 DwarfGnuPubNamesSectionSym =
1758 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1759 DwarfGnuPubTypesSectionSym =
1760 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1761 } else if (HasDwarfPubSections) {
1762 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1763 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1766 DwarfStrSectionSym =
1767 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1768 if (useSplitDwarf()) {
1769 DwarfStrDWOSectionSym =
1770 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1771 DwarfAddrSectionSym =
1772 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1773 DwarfDebugLocSectionSym =
1774 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1776 DwarfDebugLocSectionSym =
1777 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1778 DwarfDebugRangeSectionSym =
1779 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1782 // Recursively emits a debug information entry.
1783 void DwarfDebug::emitDIE(DIE &Die) {
1784 // Get the abbreviation for this DIE.
1785 const DIEAbbrev &Abbrev = Die.getAbbrev();
1787 // Emit the code (index) for the abbreviation.
1788 if (Asm->isVerbose())
1789 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1790 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1791 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1792 dwarf::TagString(Abbrev.getTag()));
1793 Asm->EmitULEB128(Abbrev.getNumber());
1795 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1796 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1798 // Emit the DIE attribute values.
1799 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1800 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1801 dwarf::Form Form = AbbrevData[i].getForm();
1802 assert(Form && "Too many attributes for DIE (check abbreviation)");
1804 if (Asm->isVerbose()) {
1805 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1806 if (Attr == dwarf::DW_AT_accessibility)
1807 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1808 cast<DIEInteger>(Values[i])->getValue()));
1811 // Emit an attribute using the defined form.
1812 Values[i]->EmitValue(Asm, Form);
1815 // Emit the DIE children if any.
1816 if (Abbrev.hasChildren()) {
1817 for (auto &Child : Die.getChildren())
1820 Asm->OutStreamer.AddComment("End Of Children Mark");
1825 // Emit the debug info section.
1826 void DwarfDebug::emitDebugInfo() {
1827 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1829 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1832 // Emit the abbreviation section.
1833 void DwarfDebug::emitAbbreviations() {
1834 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1836 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1839 // Emit the last address of the section and the end of the line matrix.
1840 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1841 // Define last address of section.
1842 Asm->OutStreamer.AddComment("Extended Op");
1845 Asm->OutStreamer.AddComment("Op size");
1846 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1847 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1848 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1850 Asm->OutStreamer.AddComment("Section end label");
1852 Asm->OutStreamer.EmitSymbolValue(
1853 Asm->GetTempSymbol("section_end", SectionEnd),
1854 Asm->getDataLayout().getPointerSize());
1856 // Mark end of matrix.
1857 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1863 // Emit visible names into a hashed accelerator table section.
1864 void DwarfDebug::emitAccelNames() {
1865 AccelNames.FinalizeTable(Asm, "Names");
1866 Asm->OutStreamer.SwitchSection(
1867 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1868 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1869 Asm->OutStreamer.EmitLabel(SectionBegin);
1871 // Emit the full data.
1872 AccelNames.Emit(Asm, SectionBegin, &InfoHolder);
1875 // Emit objective C classes and categories into a hashed accelerator table
1877 void DwarfDebug::emitAccelObjC() {
1878 AccelObjC.FinalizeTable(Asm, "ObjC");
1879 Asm->OutStreamer.SwitchSection(
1880 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1881 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1882 Asm->OutStreamer.EmitLabel(SectionBegin);
1884 // Emit the full data.
1885 AccelObjC.Emit(Asm, SectionBegin, &InfoHolder);
1888 // Emit namespace dies into a hashed accelerator table.
1889 void DwarfDebug::emitAccelNamespaces() {
1890 AccelNamespace.FinalizeTable(Asm, "namespac");
1891 Asm->OutStreamer.SwitchSection(
1892 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1893 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1894 Asm->OutStreamer.EmitLabel(SectionBegin);
1896 // Emit the full data.
1897 AccelNamespace.Emit(Asm, SectionBegin, &InfoHolder);
1900 // Emit type dies into a hashed accelerator table.
1901 void DwarfDebug::emitAccelTypes() {
1902 DwarfAccelTable::Atom Atoms[] = {
1903 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
1904 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
1905 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
1906 DwarfAccelTable AT(Atoms);
1907 for (const auto &TheU : getUnits()) {
1908 for (const auto &GI : TheU->getAccelTypes()) {
1909 StringRef Name = GI.getKey();
1910 for (const auto &DI : GI.second)
1911 AT.AddName(Name, DI.first, DI.second);
1915 AT.FinalizeTable(Asm, "types");
1916 Asm->OutStreamer.SwitchSection(
1917 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1918 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1919 Asm->OutStreamer.EmitLabel(SectionBegin);
1921 // Emit the full data.
1922 AT.Emit(Asm, SectionBegin, &InfoHolder);
1925 // Public name handling.
1926 // The format for the various pubnames:
1928 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1929 // for the DIE that is named.
1931 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1932 // into the CU and the index value is computed according to the type of value
1933 // for the DIE that is named.
1935 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1936 // it's the offset within the debug_info/debug_types dwo section, however, the
1937 // reference in the pubname header doesn't change.
1939 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1940 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1942 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1944 // We could have a specification DIE that has our most of our knowledge,
1945 // look for that now.
1946 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1948 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1949 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
1950 Linkage = dwarf::GIEL_EXTERNAL;
1951 } else if (Die->findAttribute(dwarf::DW_AT_external))
1952 Linkage = dwarf::GIEL_EXTERNAL;
1954 switch (Die->getTag()) {
1955 case dwarf::DW_TAG_class_type:
1956 case dwarf::DW_TAG_structure_type:
1957 case dwarf::DW_TAG_union_type:
1958 case dwarf::DW_TAG_enumeration_type:
1959 return dwarf::PubIndexEntryDescriptor(
1960 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1961 ? dwarf::GIEL_STATIC
1962 : dwarf::GIEL_EXTERNAL);
1963 case dwarf::DW_TAG_typedef:
1964 case dwarf::DW_TAG_base_type:
1965 case dwarf::DW_TAG_subrange_type:
1966 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1967 case dwarf::DW_TAG_namespace:
1968 return dwarf::GIEK_TYPE;
1969 case dwarf::DW_TAG_subprogram:
1970 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1971 case dwarf::DW_TAG_constant:
1972 case dwarf::DW_TAG_variable:
1973 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1974 case dwarf::DW_TAG_enumerator:
1975 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1976 dwarf::GIEL_STATIC);
1978 return dwarf::GIEK_NONE;
1982 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1984 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1985 const MCSection *PSec =
1986 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1987 : Asm->getObjFileLowering().getDwarfPubNamesSection();
1989 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1992 void DwarfDebug::emitDebugPubSection(
1993 bool GnuStyle, const MCSection *PSec, StringRef Name,
1994 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1995 for (const auto &NU : CUMap) {
1996 DwarfCompileUnit *TheU = NU.second;
1998 const auto &Globals = (TheU->*Accessor)();
2000 if (Globals.empty())
2003 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2005 unsigned ID = TheU->getUniqueID();
2007 // Start the dwarf pubnames section.
2008 Asm->OutStreamer.SwitchSection(PSec);
2011 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2012 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2013 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2014 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2016 Asm->OutStreamer.EmitLabel(BeginLabel);
2018 Asm->OutStreamer.AddComment("DWARF Version");
2019 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2021 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2022 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2024 Asm->OutStreamer.AddComment("Compilation Unit Length");
2025 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2027 // Emit the pubnames for this compilation unit.
2028 for (const auto &GI : Globals) {
2029 const char *Name = GI.getKeyData();
2030 const DIE *Entity = GI.second;
2032 Asm->OutStreamer.AddComment("DIE offset");
2033 Asm->EmitInt32(Entity->getOffset());
2036 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2037 Asm->OutStreamer.AddComment(
2038 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2039 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2040 Asm->EmitInt8(Desc.toBits());
2043 Asm->OutStreamer.AddComment("External Name");
2044 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2047 Asm->OutStreamer.AddComment("End Mark");
2049 Asm->OutStreamer.EmitLabel(EndLabel);
2053 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2054 const MCSection *PSec =
2055 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2056 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2058 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2061 // Emit visible names into a debug str section.
2062 void DwarfDebug::emitDebugStr() {
2063 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2064 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2067 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2068 const DebugLocEntry &Entry) {
2069 DIVariable DV(Entry.getVariable());
2070 if (Entry.isInt()) {
2071 DIBasicType BTy(resolve(DV.getType()));
2072 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2073 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2074 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2075 Streamer.EmitSLEB128(Entry.getInt());
2077 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2078 Streamer.EmitULEB128(Entry.getInt());
2080 } else if (Entry.isLocation()) {
2081 MachineLocation Loc = Entry.getLoc();
2082 if (!DV.hasComplexAddress())
2084 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2086 // Complex address entry.
2087 unsigned N = DV.getNumAddrElements();
2089 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2090 if (Loc.getOffset()) {
2092 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2093 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2094 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2095 Streamer.EmitSLEB128(DV.getAddrElement(1));
2097 // If first address element is OpPlus then emit
2098 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2099 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2100 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2104 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2107 // Emit remaining complex address elements.
2108 for (; i < N; ++i) {
2109 uint64_t Element = DV.getAddrElement(i);
2110 if (Element == DIBuilder::OpPlus) {
2111 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2112 Streamer.EmitULEB128(DV.getAddrElement(++i));
2113 } else if (Element == DIBuilder::OpDeref) {
2115 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2117 llvm_unreachable("unknown Opcode found in complex address");
2121 // else ... ignore constant fp. There is not any good way to
2122 // to represent them here in dwarf.
2126 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2127 Asm->OutStreamer.AddComment("Loc expr size");
2128 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2129 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2130 Asm->EmitLabelDifference(end, begin, 2);
2131 Asm->OutStreamer.EmitLabel(begin);
2133 APByteStreamer Streamer(*Asm);
2134 emitDebugLocEntry(Streamer, Entry);
2136 Asm->OutStreamer.EmitLabel(end);
2139 // Emit locations into the debug loc section.
2140 void DwarfDebug::emitDebugLoc() {
2141 // Start the dwarf loc section.
2142 Asm->OutStreamer.SwitchSection(
2143 Asm->getObjFileLowering().getDwarfLocSection());
2144 unsigned char Size = Asm->getDataLayout().getPointerSize();
2145 for (const auto &DebugLoc : DotDebugLocEntries) {
2146 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2147 for (const auto &Entry : DebugLoc.List) {
2148 // Set up the range. This range is relative to the entry point of the
2149 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2150 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2151 const DwarfCompileUnit *CU = Entry.getCU();
2152 if (CU->getRanges().size() == 1) {
2153 // Grab the begin symbol from the first range as our base.
2154 const MCSymbol *Base = CU->getRanges()[0].getStart();
2155 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2156 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2158 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2159 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2162 emitDebugLocEntryLocation(Entry);
2164 Asm->OutStreamer.EmitIntValue(0, Size);
2165 Asm->OutStreamer.EmitIntValue(0, Size);
2169 void DwarfDebug::emitDebugLocDWO() {
2170 Asm->OutStreamer.SwitchSection(
2171 Asm->getObjFileLowering().getDwarfLocDWOSection());
2172 for (const auto &DebugLoc : DotDebugLocEntries) {
2173 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2174 for (const auto &Entry : DebugLoc.List) {
2175 // Just always use start_length for now - at least that's one address
2176 // rather than two. We could get fancier and try to, say, reuse an
2177 // address we know we've emitted elsewhere (the start of the function?
2178 // The start of the CU or CU subrange that encloses this range?)
2179 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2180 unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2181 Asm->EmitULEB128(idx);
2182 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2184 emitDebugLocEntryLocation(Entry);
2186 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2191 const MCSymbol *Start, *End;
2194 // Emit a debug aranges section, containing a CU lookup for any
2195 // address we can tie back to a CU.
2196 void DwarfDebug::emitDebugARanges() {
2197 // Start the dwarf aranges section.
2198 Asm->OutStreamer.SwitchSection(
2199 Asm->getObjFileLowering().getDwarfARangesSection());
2201 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2205 // Build a list of sections used.
2206 std::vector<const MCSection *> Sections;
2207 for (const auto &it : SectionMap) {
2208 const MCSection *Section = it.first;
2209 Sections.push_back(Section);
2212 // Sort the sections into order.
2213 // This is only done to ensure consistent output order across different runs.
2214 std::sort(Sections.begin(), Sections.end(), SectionSort);
2216 // Build a set of address spans, sorted by CU.
2217 for (const MCSection *Section : Sections) {
2218 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2219 if (List.size() < 2)
2222 // Sort the symbols by offset within the section.
2223 std::sort(List.begin(), List.end(),
2224 [&](const SymbolCU &A, const SymbolCU &B) {
2225 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2226 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2228 // Symbols with no order assigned should be placed at the end.
2229 // (e.g. section end labels)
2237 // If we have no section (e.g. common), just write out
2238 // individual spans for each symbol.
2239 if (Section == NULL) {
2240 for (const SymbolCU &Cur : List) {
2242 Span.Start = Cur.Sym;
2245 Spans[Cur.CU].push_back(Span);
2248 // Build spans between each label.
2249 const MCSymbol *StartSym = List[0].Sym;
2250 for (size_t n = 1, e = List.size(); n < e; n++) {
2251 const SymbolCU &Prev = List[n - 1];
2252 const SymbolCU &Cur = List[n];
2254 // Try and build the longest span we can within the same CU.
2255 if (Cur.CU != Prev.CU) {
2257 Span.Start = StartSym;
2259 Spans[Prev.CU].push_back(Span);
2266 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2268 // Build a list of CUs used.
2269 std::vector<DwarfCompileUnit *> CUs;
2270 for (const auto &it : Spans) {
2271 DwarfCompileUnit *CU = it.first;
2275 // Sort the CU list (again, to ensure consistent output order).
2276 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2277 return A->getUniqueID() < B->getUniqueID();
2280 // Emit an arange table for each CU we used.
2281 for (DwarfCompileUnit *CU : CUs) {
2282 std::vector<ArangeSpan> &List = Spans[CU];
2284 // Emit size of content not including length itself.
2285 unsigned ContentSize =
2286 sizeof(int16_t) + // DWARF ARange version number
2287 sizeof(int32_t) + // Offset of CU in the .debug_info section
2288 sizeof(int8_t) + // Pointer Size (in bytes)
2289 sizeof(int8_t); // Segment Size (in bytes)
2291 unsigned TupleSize = PtrSize * 2;
2293 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2295 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2297 ContentSize += Padding;
2298 ContentSize += (List.size() + 1) * TupleSize;
2300 // For each compile unit, write the list of spans it covers.
2301 Asm->OutStreamer.AddComment("Length of ARange Set");
2302 Asm->EmitInt32(ContentSize);
2303 Asm->OutStreamer.AddComment("DWARF Arange version number");
2304 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2305 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2306 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2307 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2308 Asm->EmitInt8(PtrSize);
2309 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2312 Asm->OutStreamer.EmitFill(Padding, 0xff);
2314 for (const ArangeSpan &Span : List) {
2315 Asm->EmitLabelReference(Span.Start, PtrSize);
2317 // Calculate the size as being from the span start to it's end.
2319 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2321 // For symbols without an end marker (e.g. common), we
2322 // write a single arange entry containing just that one symbol.
2323 uint64_t Size = SymSize[Span.Start];
2327 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2331 Asm->OutStreamer.AddComment("ARange terminator");
2332 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2333 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2337 // Emit visible names into a debug ranges section.
2338 void DwarfDebug::emitDebugRanges() {
2339 // Start the dwarf ranges section.
2340 Asm->OutStreamer.SwitchSection(
2341 Asm->getObjFileLowering().getDwarfRangesSection());
2343 // Size for our labels.
2344 unsigned char Size = Asm->getDataLayout().getPointerSize();
2346 // Grab the specific ranges for the compile units in the module.
2347 for (const auto &I : CUMap) {
2348 DwarfCompileUnit *TheCU = I.second;
2350 // Emit a symbol so we can find the beginning of our ranges.
2351 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2353 // Iterate over the misc ranges for the compile units in the module.
2354 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2355 // Emit our symbol so we can find the beginning of the range.
2356 Asm->OutStreamer.EmitLabel(List.getSym());
2358 for (const RangeSpan &Range : List.getRanges()) {
2359 const MCSymbol *Begin = Range.getStart();
2360 const MCSymbol *End = Range.getEnd();
2361 assert(Begin && "Range without a begin symbol?");
2362 assert(End && "Range without an end symbol?");
2363 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2364 Asm->OutStreamer.EmitSymbolValue(End, Size);
2367 // And terminate the list with two 0 values.
2368 Asm->OutStreamer.EmitIntValue(0, Size);
2369 Asm->OutStreamer.EmitIntValue(0, Size);
2372 // Now emit a range for the CU itself.
2373 if (TheCU->getRanges().size() > 1) {
2374 Asm->OutStreamer.EmitLabel(
2375 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2376 for (const RangeSpan &Range : TheCU->getRanges()) {
2377 const MCSymbol *Begin = Range.getStart();
2378 const MCSymbol *End = Range.getEnd();
2379 assert(Begin && "Range without a begin symbol?");
2380 assert(End && "Range without an end symbol?");
2381 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2382 Asm->OutStreamer.EmitSymbolValue(End, Size);
2384 // And terminate the list with two 0 values.
2385 Asm->OutStreamer.EmitIntValue(0, Size);
2386 Asm->OutStreamer.EmitIntValue(0, Size);
2391 // DWARF5 Experimental Separate Dwarf emitters.
2393 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE *Die,
2394 std::unique_ptr<DwarfUnit> NewU) {
2395 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2396 U.getCUNode().getSplitDebugFilename());
2398 if (!CompilationDir.empty())
2399 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2401 addGnuPubAttributes(*NewU, Die);
2403 SkeletonHolder.addUnit(std::move(NewU));
2406 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2407 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2408 // DW_AT_addr_base, DW_AT_ranges_base.
2409 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2411 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2412 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2413 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2414 DwarfCompileUnit &NewCU = *OwnedUnit;
2415 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2416 DwarfInfoSectionSym);
2418 NewCU.initStmtList(DwarfLineSectionSym);
2420 initSkeletonUnit(CU, Die, std::move(OwnedUnit));
2425 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2427 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2428 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2429 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2431 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2432 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2433 this, &SkeletonHolder);
2434 DwarfTypeUnit &NewTU = *OwnedUnit;
2435 NewTU.setTypeSignature(TU.getTypeSignature());
2436 NewTU.setType(NULL);
2438 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2440 initSkeletonUnit(TU, Die, std::move(OwnedUnit));
2444 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2445 // compile units that would normally be in debug_info.
2446 void DwarfDebug::emitDebugInfoDWO() {
2447 assert(useSplitDwarf() && "No split dwarf debug info?");
2448 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2449 // emit relocations into the dwo file.
2450 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2453 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2454 // abbreviations for the .debug_info.dwo section.
2455 void DwarfDebug::emitDebugAbbrevDWO() {
2456 assert(useSplitDwarf() && "No split dwarf?");
2457 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2460 void DwarfDebug::emitDebugLineDWO() {
2461 assert(useSplitDwarf() && "No split dwarf?");
2462 Asm->OutStreamer.SwitchSection(
2463 Asm->getObjFileLowering().getDwarfLineDWOSection());
2464 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2467 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2468 // string section and is identical in format to traditional .debug_str
2470 void DwarfDebug::emitDebugStrDWO() {
2471 assert(useSplitDwarf() && "No split dwarf?");
2472 const MCSection *OffSec =
2473 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2474 const MCSymbol *StrSym = DwarfStrSectionSym;
2475 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2479 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2480 if (!useSplitDwarf())
2483 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2484 return &SplitTypeUnitFileTable;
2487 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2488 StringRef Identifier, DIE *RefDie,
2489 DICompositeType CTy) {
2490 // Flag the type unit reference as a declaration so that if it contains
2491 // members (implicit special members, static data member definitions, member
2492 // declarations for definitions in this CU, etc) consumers don't get confused
2493 // and think this is a full definition.
2494 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2496 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2498 CU.addDIETypeSignature(RefDie, *TU);
2502 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2504 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2505 this, &InfoHolder, getDwoLineTable(CU));
2506 DwarfTypeUnit &NewTU = *OwnedUnit;
2508 InfoHolder.addUnit(std::move(OwnedUnit));
2510 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2514 Hash.update(Identifier);
2515 // ... take the least significant 8 bytes and return those. Our MD5
2516 // implementation always returns its results in little endian, swap bytes
2518 MD5::MD5Result Result;
2520 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2521 NewTU.setTypeSignature(Signature);
2522 if (useSplitDwarf())
2523 NewTU.setSkeleton(constructSkeletonTU(NewTU));
2525 CU.applyStmtList(*UnitDie);
2527 NewTU.setType(NewTU.createTypeDIE(CTy));
2531 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2532 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2534 CU.addDIETypeSignature(RefDie, NewTU);
2537 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE *D,
2538 MCSymbol *Begin, MCSymbol *End) {
2539 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2540 if (DwarfVersion < 4)
2541 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2543 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2546 // Accelerator table mutators - add each name along with its companion
2547 // DIE to the proper table while ensuring that the name that we're going
2548 // to reference is in the string table. We do this since the names we
2549 // add may not only be identical to the names in the DIE.
2550 void DwarfDebug::addAccelName(StringRef Name, const DIE *Die) {
2551 if (!useDwarfAccelTables())
2553 InfoHolder.getStringPoolEntry(Name);
2554 AccelNames.AddName(Name, Die);
2557 void DwarfDebug::addAccelObjC(StringRef Name, const DIE *Die) {
2558 if (!useDwarfAccelTables())
2560 InfoHolder.getStringPoolEntry(Name);
2561 AccelObjC.AddName(Name, Die);
2564 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE *Die) {
2565 if (!useDwarfAccelTables())
2567 InfoHolder.getStringPoolEntry(Name);
2568 AccelNamespace.AddName(Name, Die);