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 "DwarfAccelTable.h"
19 #include "DwarfUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DIBuilder.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ValueHandle.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCSection.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Dwarf.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/LEB128.h"
43 #include "llvm/Support/MD5.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Target/TargetFrameLowering.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include "llvm/Target/TargetMachine.h"
49 #include "llvm/Target/TargetOptions.h"
50 #include "llvm/Target/TargetRegisterInfo.h"
53 #define DEBUG_TYPE "dwarfdebug"
56 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
57 cl::desc("Disable debug info printing"));
59 static cl::opt<bool> UnknownLocations(
60 "use-unknown-locations", cl::Hidden,
61 cl::desc("Make an absence of debug location information explicit."),
65 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
66 cl::desc("Generate GNU-style pubnames and pubtypes"),
69 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
71 cl::desc("Generate dwarf aranges"),
75 enum DefaultOnOff { Default, Enable, Disable };
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 SplitDwarf("split-dwarf", cl::Hidden,
88 cl::desc("Output DWARF5 split debug info."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
96 cl::desc("Generate DWARF pubnames and pubtypes sections"),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
102 static cl::opt<unsigned>
103 DwarfVersionNumber("dwarf-version", cl::Hidden,
104 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
106 static const char *const DWARFGroupName = "DWARF Emission";
107 static const char *const DbgTimerName = "DWARF Debug Writer";
109 //===----------------------------------------------------------------------===//
111 /// resolve - Look in the DwarfDebug map for the MDNode that
112 /// corresponds to the reference.
113 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
114 return DD->resolve(Ref);
117 bool DbgVariable::isBlockByrefVariable() const {
118 assert(Var.isVariable() && "Invalid complex DbgVariable!");
119 return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
123 DIType DbgVariable::getType() const {
124 DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
125 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
126 // addresses instead.
127 if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
128 /* Byref variables, in Blocks, are declared by the programmer as
129 "SomeType VarName;", but the compiler creates a
130 __Block_byref_x_VarName struct, and gives the variable VarName
131 either the struct, or a pointer to the struct, as its type. This
132 is necessary for various behind-the-scenes things the compiler
133 needs to do with by-reference variables in blocks.
135 However, as far as the original *programmer* is concerned, the
136 variable should still have type 'SomeType', as originally declared.
138 The following function dives into the __Block_byref_x_VarName
139 struct to find the original type of the variable. This will be
140 passed back to the code generating the type for the Debug
141 Information Entry for the variable 'VarName'. 'VarName' will then
142 have the original type 'SomeType' in its debug information.
144 The original type 'SomeType' will be the type of the field named
145 'VarName' inside the __Block_byref_x_VarName struct.
147 NOTE: In order for this to not completely fail on the debugger
148 side, the Debug Information Entry for the variable VarName needs to
149 have a DW_AT_location that tells the debugger how to unwind through
150 the pointers and __Block_byref_x_VarName struct to find the actual
151 value of the variable. The function addBlockByrefType does this. */
153 uint16_t tag = Ty.getTag();
155 if (tag == dwarf::DW_TAG_pointer_type)
156 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
158 DIArray Elements = DICompositeType(subType).getTypeArray();
159 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
160 DIDerivedType DT(Elements.getElement(i));
161 if (getName() == DT.getName())
162 return (resolve(DT.getTypeDerivedFrom()));
168 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
169 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
170 InfoHolder(A, "info_string", DIEValueAllocator),
171 UsedNonDefaultText(false),
172 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
174 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
175 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
176 DwarfAddrSectionSym = 0;
177 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
178 FunctionBeginSym = FunctionEndSym = 0;
182 // Turn on accelerator tables for Darwin by default, pubnames by
183 // default for non-Darwin, and handle split dwarf.
184 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
186 if (DwarfAccelTables == Default)
187 HasDwarfAccelTables = IsDarwin;
189 HasDwarfAccelTables = DwarfAccelTables == Enable;
191 if (SplitDwarf == Default)
192 HasSplitDwarf = false;
194 HasSplitDwarf = SplitDwarf == Enable;
196 if (DwarfPubSections == Default)
197 HasDwarfPubSections = !IsDarwin;
199 HasDwarfPubSections = DwarfPubSections == Enable;
201 DwarfVersion = DwarfVersionNumber
203 : MMI->getModule()->getDwarfVersion();
206 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
211 // Switch to the specified MCSection and emit an assembler
212 // temporary label to it if SymbolStem is specified.
213 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
214 const char *SymbolStem = 0) {
215 Asm->OutStreamer.SwitchSection(Section);
219 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
220 Asm->OutStreamer.EmitLabel(TmpSym);
224 static bool isObjCClass(StringRef Name) {
225 return Name.startswith("+") || Name.startswith("-");
228 static bool hasObjCCategory(StringRef Name) {
229 if (!isObjCClass(Name))
232 return Name.find(") ") != StringRef::npos;
235 static void getObjCClassCategory(StringRef In, StringRef &Class,
236 StringRef &Category) {
237 if (!hasObjCCategory(In)) {
238 Class = In.slice(In.find('[') + 1, In.find(' '));
243 Class = In.slice(In.find('[') + 1, In.find('('));
244 Category = In.slice(In.find('[') + 1, In.find(' '));
248 static StringRef getObjCMethodName(StringRef In) {
249 return In.slice(In.find(' ') + 1, In.find(']'));
252 // Helper for sorting sections into a stable output order.
253 static bool SectionSort(const MCSection *A, const MCSection *B) {
254 std::string LA = (A ? A->getLabelBeginName() : "");
255 std::string LB = (B ? B->getLabelBeginName() : "");
259 // Add the various names to the Dwarf accelerator table names.
260 // TODO: Determine whether or not we should add names for programs
261 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
262 // is only slightly different than the lookup of non-standard ObjC names.
263 static void addSubprogramNames(DwarfUnit &TheU, DISubprogram SP, DIE *Die) {
264 if (!SP.isDefinition())
266 TheU.addAccelName(SP.getName(), Die);
268 // If the linkage name is different than the name, go ahead and output
269 // that as well into the name table.
270 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
271 TheU.addAccelName(SP.getLinkageName(), Die);
273 // If this is an Objective-C selector name add it to the ObjC accelerator
275 if (isObjCClass(SP.getName())) {
276 StringRef Class, Category;
277 getObjCClassCategory(SP.getName(), Class, Category);
278 TheU.addAccelObjC(Class, Die);
280 TheU.addAccelObjC(Category, Die);
281 // Also add the base method name to the name table.
282 TheU.addAccelName(getObjCMethodName(SP.getName()), Die);
286 /// isSubprogramContext - Return true if Context is either a subprogram
287 /// or another context nested inside a subprogram.
288 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
291 DIDescriptor D(Context);
292 if (D.isSubprogram())
295 return isSubprogramContext(resolve(DIType(Context).getContext()));
299 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
300 // and DW_AT_high_pc attributes. If there are global variables in this
301 // scope then create and insert DIEs for these variables.
302 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit &SPCU,
304 DIE *SPDie = SPCU.getDIE(SP);
306 assert(SPDie && "Unable to find subprogram DIE!");
308 // If we're updating an abstract DIE, then we will be adding the children and
309 // object pointer later on. But what we don't want to do is process the
310 // concrete DIE twice.
311 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
312 // Pick up abstract subprogram DIE.
313 SPDie = SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
314 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
316 DISubprogram SPDecl = SP.getFunctionDeclaration();
317 if (!SPDecl.isSubprogram()) {
318 // There is not any need to generate specification DIE for a function
319 // defined at compile unit level. If a function is defined inside another
320 // function then gdb prefers the definition at top level and but does not
321 // expect specification DIE in parent function. So avoid creating
322 // specification DIE for a function defined inside a function.
323 DIScope SPContext = resolve(SP.getContext());
324 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
325 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
326 SPCU.addFlag(SPDie, dwarf::DW_AT_declaration);
329 DICompositeType SPTy = SP.getType();
330 DIArray Args = SPTy.getTypeArray();
331 uint16_t SPTag = SPTy.getTag();
332 if (SPTag == dwarf::DW_TAG_subroutine_type)
333 SPCU.constructSubprogramArguments(*SPDie, Args);
334 DIE *SPDeclDie = SPDie;
336 SPCU.createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU.getUnitDie());
337 SPCU.addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
342 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
344 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
345 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
346 SPCU.addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
348 // Add name to the name table, we do this here because we're guaranteed
349 // to have concrete versions of our DW_TAG_subprogram nodes.
350 addSubprogramNames(SPCU, SP, SPDie);
355 /// Check whether we should create a DIE for the given Scope, return true
356 /// if we don't create a DIE (the corresponding DIE is null).
357 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
358 if (Scope->isAbstractScope())
361 // We don't create a DIE if there is no Range.
362 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
366 if (Ranges.size() > 1)
369 // We don't create a DIE if we have a single Range and the end label
371 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
372 MCSymbol *End = getLabelAfterInsn(RI->second);
376 static void addSectionLabel(AsmPrinter &Asm, DwarfUnit &U, DIE *D,
377 dwarf::Attribute A, const MCSymbol *L,
378 const MCSymbol *Sec) {
379 if (Asm.MAI->doesDwarfUseRelocationsAcrossSections())
380 U.addSectionLabel(D, A, L);
382 U.addSectionDelta(D, A, L, Sec);
385 void DwarfDebug::addScopeRangeList(DwarfCompileUnit &TheCU, DIE *ScopeDIE,
386 const SmallVectorImpl<InsnRange> &Range) {
387 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
388 // emitting it appropriately.
389 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
391 // Under fission, ranges are specified by constant offsets relative to the
392 // CU's DW_AT_GNU_ranges_base.
394 TheCU.addSectionDelta(ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
395 DwarfDebugRangeSectionSym);
397 addSectionLabel(*Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
398 DwarfDebugRangeSectionSym);
400 RangeSpanList List(RangeSym);
401 for (const InsnRange &R : Range) {
402 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
403 List.addRange(std::move(Span));
406 // Add the range list to the set of ranges to be emitted.
407 TheCU.addRangeList(std::move(List));
410 // Construct new DW_TAG_lexical_block for this scope and attach
411 // DW_AT_low_pc/DW_AT_high_pc labels.
412 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit &TheCU,
413 LexicalScope *Scope) {
414 if (isLexicalScopeDIENull(Scope))
417 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
418 if (Scope->isAbstractScope())
421 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
423 // If we have multiple ranges, emit them into the range section.
424 if (ScopeRanges.size() > 1) {
425 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
429 // Construct the address range for this DIE.
430 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
431 MCSymbol *Start = getLabelBeforeInsn(RI->first);
432 MCSymbol *End = getLabelAfterInsn(RI->second);
433 assert(End && "End label should not be null!");
435 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
436 assert(End->isDefined() && "Invalid end label for an inlined scope!");
438 attachLowHighPC(TheCU, ScopeDIE, Start, End);
443 // This scope represents inlined body of a function. Construct DIE to
444 // represent this concrete inlined copy of the function.
445 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit &TheCU,
446 LexicalScope *Scope) {
447 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
448 assert(!ScopeRanges.empty() &&
449 "LexicalScope does not have instruction markers!");
451 if (!Scope->getScopeNode())
453 DIScope DS(Scope->getScopeNode());
454 DISubprogram InlinedSP = getDISubprogram(DS);
455 DIE *OriginDIE = TheCU.getDIE(InlinedSP);
457 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
461 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
462 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
464 // If we have multiple ranges, emit them into the range section.
465 if (ScopeRanges.size() > 1)
466 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
468 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
469 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
470 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
472 if (StartLabel == 0 || EndLabel == 0)
473 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
475 assert(StartLabel->isDefined() &&
476 "Invalid starting label for an inlined scope!");
477 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
479 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
482 InlinedSubprogramDIEs.insert(OriginDIE);
484 // Add the call site information to the DIE.
485 DILocation DL(Scope->getInlinedAt());
486 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
487 TheCU.getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
488 TheCU.addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
490 // Add name to the name table, we do this here because we're guaranteed
491 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
492 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
497 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit &TheCU,
499 SmallVectorImpl<DIE *> &Children) {
500 DIE *ObjectPointer = NULL;
502 // Collect arguments for current function.
503 if (LScopes.isCurrentFunctionScope(Scope)) {
504 for (DbgVariable *ArgDV : CurrentFnArguments)
507 TheCU.constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
508 Children.push_back(Arg);
509 if (ArgDV->isObjectPointer())
513 // If this is a variadic function, add an unspecified parameter.
514 DISubprogram SP(Scope->getScopeNode());
515 DIArray FnArgs = SP.getType().getTypeArray();
516 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
517 .isUnspecifiedParameter()) {
518 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
519 Children.push_back(Ellipsis);
523 // Collect lexical scope children first.
524 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
526 TheCU.constructVariableDIE(*DV, Scope->isAbstractScope())) {
527 Children.push_back(Variable);
528 if (DV->isObjectPointer())
529 ObjectPointer = Variable;
531 for (LexicalScope *LS : Scope->getChildren())
532 if (DIE *Nested = constructScopeDIE(TheCU, LS))
533 Children.push_back(Nested);
534 return ObjectPointer;
537 // Construct a DIE for this scope.
538 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit &TheCU,
539 LexicalScope *Scope) {
540 if (!Scope || !Scope->getScopeNode())
543 DIScope DS(Scope->getScopeNode());
545 SmallVector<DIE *, 8> Children;
546 DIE *ObjectPointer = NULL;
547 bool ChildrenCreated = false;
549 // We try to create the scope DIE first, then the children DIEs. This will
550 // avoid creating un-used children then removing them later when we find out
551 // the scope DIE is null.
552 DIE *ScopeDIE = NULL;
553 if (Scope->getInlinedAt())
554 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
555 else if (DS.isSubprogram()) {
556 ProcessedSPNodes.insert(DS);
557 if (Scope->isAbstractScope()) {
558 ScopeDIE = TheCU.getDIE(DS);
559 // Note down abstract DIE.
561 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
563 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
565 // Early exit when we know the scope DIE is going to be null.
566 if (isLexicalScopeDIENull(Scope))
569 // We create children here when we know the scope DIE is not going to be
570 // null and the children will be added to the scope DIE.
571 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
572 ChildrenCreated = true;
574 // There is no need to emit empty lexical block DIE.
575 std::pair<ImportedEntityMap::const_iterator,
576 ImportedEntityMap::const_iterator> Range =
578 ScopesWithImportedEntities.begin(),
579 ScopesWithImportedEntities.end(),
580 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
582 if (Children.empty() && Range.first == Range.second)
584 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
585 assert(ScopeDIE && "Scope DIE should not be null.");
586 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
588 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
592 assert(Children.empty() &&
593 "We create children only when the scope DIE is not null.");
596 if (!ChildrenCreated)
597 // We create children when the scope DIE is not null.
598 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
601 for (DIE *I : Children)
602 ScopeDIE->addChild(I);
604 if (DS.isSubprogram() && ObjectPointer != NULL)
605 TheCU.addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
610 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE *D) const {
611 if (!GenerateGnuPubSections)
614 U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
617 // Create new DwarfCompileUnit for the given metadata node with tag
618 // DW_TAG_compile_unit.
619 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
620 StringRef FN = DIUnit.getFilename();
621 CompilationDir = DIUnit.getDirectory();
623 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
624 auto OwnedUnit = make_unique<DwarfCompileUnit>(
625 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
626 DwarfCompileUnit &NewCU = *OwnedUnit;
627 InfoHolder.addUnit(std::move(OwnedUnit));
629 // LTO with assembly output shares a single line table amongst multiple CUs.
630 // To avoid the compilation directory being ambiguous, let the line table
631 // explicitly describe the directory of all files, never relying on the
632 // compilation directory.
633 if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
634 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
635 NewCU.getUniqueID(), CompilationDir);
637 NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
638 NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
639 DIUnit.getLanguage());
640 NewCU.addString(Die, dwarf::DW_AT_name, FN);
642 if (!useSplitDwarf()) {
643 NewCU.initStmtList(DwarfLineSectionSym);
645 // If we're using split dwarf the compilation dir is going to be in the
646 // skeleton CU and so we don't need to duplicate it here.
647 if (!CompilationDir.empty())
648 NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
650 addGnuPubAttributes(NewCU, Die);
653 if (DIUnit.isOptimized())
654 NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
656 StringRef Flags = DIUnit.getFlags();
658 NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
660 if (unsigned RVer = DIUnit.getRunTimeVersion())
661 NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
662 dwarf::DW_FORM_data1, RVer);
667 if (useSplitDwarf()) {
668 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
669 DwarfInfoDWOSectionSym);
670 NewCU.setSkeleton(constructSkeletonCU(NewCU));
672 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
673 DwarfInfoSectionSym);
675 CUMap.insert(std::make_pair(DIUnit, &NewCU));
676 CUDieMap.insert(std::make_pair(Die, &NewCU));
680 // Construct subprogram DIE.
681 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit &TheCU,
683 // FIXME: We should only call this routine once, however, during LTO if a
684 // program is defined in multiple CUs we could end up calling it out of
685 // beginModule as we walk the CUs.
687 DwarfCompileUnit *&CURef = SPMap[N];
693 if (!SP.isDefinition())
694 // This is a method declaration which will be handled while constructing
698 DIE *SubprogramDie = TheCU.getOrCreateSubprogramDIE(SP);
700 // Expose as a global name.
701 TheCU.addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
704 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
706 DIImportedEntity Module(N);
707 assert(Module.Verify());
708 if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
709 constructImportedEntityDIE(TheCU, Module, D);
712 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
713 const MDNode *N, DIE *Context) {
714 DIImportedEntity Module(N);
715 assert(Module.Verify());
716 return constructImportedEntityDIE(TheCU, Module, Context);
719 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit &TheCU,
720 const DIImportedEntity &Module,
722 assert(Module.Verify() &&
723 "Use one of the MDNode * overloads to handle invalid metadata");
724 assert(Context && "Should always have a context for an imported_module");
725 DIE *IMDie = TheCU.createAndAddDIE(Module.getTag(), *Context, Module);
727 DIDescriptor Entity = resolve(Module.getEntity());
728 if (Entity.isNameSpace())
729 EntityDie = TheCU.getOrCreateNameSpace(DINameSpace(Entity));
730 else if (Entity.isSubprogram())
731 EntityDie = TheCU.getOrCreateSubprogramDIE(DISubprogram(Entity));
732 else if (Entity.isType())
733 EntityDie = TheCU.getOrCreateTypeDIE(DIType(Entity));
735 EntityDie = TheCU.getDIE(Entity);
736 TheCU.addSourceLine(IMDie, Module.getLineNumber(),
737 Module.getContext().getFilename(),
738 Module.getContext().getDirectory());
739 TheCU.addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
740 StringRef Name = Module.getName();
742 TheCU.addString(IMDie, dwarf::DW_AT_name, Name);
745 // Emit all Dwarf sections that should come prior to the content. Create
746 // global DIEs and emit initial debug info sections. This is invoked by
747 // the target AsmPrinter.
748 void DwarfDebug::beginModule() {
749 if (DisableDebugInfoPrinting)
752 const Module *M = MMI->getModule();
754 // If module has named metadata anchors then use them, otherwise scan the
755 // module using debug info finder to collect debug info.
756 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
759 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
761 // Emit initial sections so we can reference labels later.
764 SingleCU = CU_Nodes->getNumOperands() == 1;
766 for (MDNode *N : CU_Nodes->operands()) {
767 DICompileUnit CUNode(N);
768 DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
769 DIArray ImportedEntities = CUNode.getImportedEntities();
770 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
771 ScopesWithImportedEntities.push_back(std::make_pair(
772 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
773 ImportedEntities.getElement(i)));
774 std::sort(ScopesWithImportedEntities.begin(),
775 ScopesWithImportedEntities.end(), less_first());
776 DIArray GVs = CUNode.getGlobalVariables();
777 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
778 CU.createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
779 DIArray SPs = CUNode.getSubprograms();
780 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
781 constructSubprogramDIE(CU, SPs.getElement(i));
782 DIArray EnumTypes = CUNode.getEnumTypes();
783 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
784 CU.getOrCreateTypeDIE(EnumTypes.getElement(i));
785 DIArray RetainedTypes = CUNode.getRetainedTypes();
786 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
787 DIType Ty(RetainedTypes.getElement(i));
788 // The retained types array by design contains pointers to
789 // MDNodes rather than DIRefs. Unique them here.
790 DIType UniqueTy(resolve(Ty.getRef()));
791 CU.getOrCreateTypeDIE(UniqueTy);
793 // Emit imported_modules last so that the relevant context is already
795 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
796 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
799 // Tell MMI that we have debug info.
800 MMI->setDebugInfoAvailability(true);
802 // Prime section data.
803 SectionMap[Asm->getObjFileLowering().getTextSection()];
806 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
807 void DwarfDebug::computeInlinedDIEs() {
808 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
809 for (DIE *ISP : InlinedSubprogramDIEs)
810 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
812 for (const auto &AI : AbstractSPDies) {
813 DIE *ISP = AI.second;
814 if (InlinedSubprogramDIEs.count(ISP))
816 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
820 // Collect info for variables that were optimized out.
821 void DwarfDebug::collectDeadVariables() {
822 const Module *M = MMI->getModule();
824 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
825 for (MDNode *N : CU_Nodes->operands()) {
826 DICompileUnit TheCU(N);
827 DIArray Subprograms = TheCU.getSubprograms();
828 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
829 DISubprogram SP(Subprograms.getElement(i));
830 if (ProcessedSPNodes.count(SP) != 0)
832 if (!SP.isSubprogram())
834 if (!SP.isDefinition())
836 DIArray Variables = SP.getVariables();
837 if (Variables.getNumElements() == 0)
840 // Construct subprogram DIE and add variables DIEs.
841 DwarfCompileUnit *SPCU =
842 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
843 assert(SPCU && "Unable to find Compile Unit!");
844 // FIXME: See the comment in constructSubprogramDIE about duplicate
846 constructSubprogramDIE(*SPCU, SP);
847 DIE *SPDIE = SPCU->getDIE(SP);
848 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
849 DIVariable DV(Variables.getElement(vi));
850 if (!DV.isVariable())
852 DbgVariable NewVar(DV, NULL, this);
853 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
854 SPDIE->addChild(VariableDIE);
861 void DwarfDebug::finalizeModuleInfo() {
862 // Collect info for variables that were optimized out.
863 collectDeadVariables();
865 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
866 computeInlinedDIEs();
868 // Handle anything that needs to be done on a per-unit basis after
869 // all other generation.
870 for (const auto &TheU : getUnits()) {
871 // Emit DW_AT_containing_type attribute to connect types with their
872 // vtable holding type.
873 TheU->constructContainingTypeDIEs();
875 // Add CU specific attributes if we need to add any.
876 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
877 // If we're splitting the dwarf out now that we've got the entire
878 // CU then add the dwo id to it.
879 DwarfCompileUnit *SkCU =
880 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
881 if (useSplitDwarf()) {
882 // Emit a unique identifier for this CU.
883 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
884 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
885 dwarf::DW_FORM_data8, ID);
886 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
887 dwarf::DW_FORM_data8, ID);
889 // We don't keep track of which addresses are used in which CU so this
890 // is a bit pessimistic under LTO.
891 if (!InfoHolder.getAddrPool()->empty())
892 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
893 dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
894 DwarfAddrSectionSym);
895 if (!TheU->getRangeLists().empty())
896 addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
897 dwarf::DW_AT_GNU_ranges_base,
898 DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
901 // If we have code split among multiple sections or non-contiguous
902 // ranges of code then emit a DW_AT_ranges attribute on the unit that will
903 // remain in the .o file, otherwise add a DW_AT_low_pc.
904 // FIXME: We should use ranges allow reordering of code ala
905 // .subsections_via_symbols in mach-o. This would mean turning on
906 // ranges for all subprogram DIEs for mach-o.
907 DwarfCompileUnit &U =
908 SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
909 unsigned NumRanges = TheU->getRanges().size();
912 addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
913 Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
914 DwarfDebugRangeSectionSym);
916 // A DW_AT_low_pc attribute may also be specified in combination with
917 // DW_AT_ranges to specify the default base address for use in
918 // location lists (see Section 2.6.2) and range lists (see Section
920 U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
923 RangeSpan &Range = TheU->getRanges().back();
924 U.addLocalLabelAddress(U.getUnitDie(), dwarf::DW_AT_low_pc,
926 U.addLabelDelta(U.getUnitDie(), dwarf::DW_AT_high_pc, Range.getEnd(),
933 // Compute DIE offsets and sizes.
934 InfoHolder.computeSizeAndOffsets();
936 SkeletonHolder.computeSizeAndOffsets();
939 void DwarfDebug::endSections() {
940 // Filter labels by section.
941 for (const SymbolCU &SCU : ArangeLabels) {
942 if (SCU.Sym->isInSection()) {
943 // Make a note of this symbol and it's section.
944 const MCSection *Section = &SCU.Sym->getSection();
945 if (!Section->getKind().isMetadata())
946 SectionMap[Section].push_back(SCU);
948 // Some symbols (e.g. common/bss on mach-o) can have no section but still
949 // appear in the output. This sucks as we rely on sections to build
950 // arange spans. We can do it without, but it's icky.
951 SectionMap[NULL].push_back(SCU);
955 // Build a list of sections used.
956 std::vector<const MCSection *> Sections;
957 for (const auto &it : SectionMap) {
958 const MCSection *Section = it.first;
959 Sections.push_back(Section);
962 // Sort the sections into order.
963 // This is only done to ensure consistent output order across different runs.
964 std::sort(Sections.begin(), Sections.end(), SectionSort);
966 // Add terminating symbols for each section.
967 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
968 const MCSection *Section = Sections[ID];
969 MCSymbol *Sym = NULL;
972 // We can't call MCSection::getLabelEndName, as it's only safe to do so
973 // if we know the section name up-front. For user-created sections, the
974 // resulting label may not be valid to use as a label. (section names can
975 // use a greater set of characters on some systems)
976 Sym = Asm->GetTempSymbol("debug_end", ID);
977 Asm->OutStreamer.SwitchSection(Section);
978 Asm->OutStreamer.EmitLabel(Sym);
981 // Insert a final terminator.
982 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
986 // Emit all Dwarf sections that should come after the content.
987 void DwarfDebug::endModule() {
994 // End any existing sections.
995 // TODO: Does this need to happen?
998 // Finalize the debug info for the module.
999 finalizeModuleInfo();
1003 // Emit all the DIEs into a debug info section.
1006 // Corresponding abbreviations into a abbrev section.
1007 emitAbbreviations();
1009 // Emit info into a debug aranges section.
1010 if (GenerateARangeSection)
1013 // Emit info into a debug ranges section.
1016 if (useSplitDwarf()) {
1019 emitDebugAbbrevDWO();
1021 // Emit DWO addresses.
1022 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1025 // Emit info into a debug loc section.
1028 // Emit info into the dwarf accelerator table sections.
1029 if (useDwarfAccelTables()) {
1032 emitAccelNamespaces();
1036 // Emit the pubnames and pubtypes sections if requested.
1037 if (HasDwarfPubSections) {
1038 emitDebugPubNames(GenerateGnuPubSections);
1039 emitDebugPubTypes(GenerateGnuPubSections);
1045 // Reset these for the next Module if we have one.
1049 // Find abstract variable, if any, associated with Var.
1050 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1051 DebugLoc ScopeLoc) {
1052 LLVMContext &Ctx = DV->getContext();
1053 // More then one inlined variable corresponds to one abstract variable.
1054 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1055 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1057 return AbsDbgVariable;
1059 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1063 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1064 addScopeVariable(Scope, AbsDbgVariable);
1065 AbstractVariables[Var] = AbsDbgVariable;
1066 return AbsDbgVariable;
1069 // If Var is a current function argument then add it to CurrentFnArguments list.
1070 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1071 if (!LScopes.isCurrentFunctionScope(Scope))
1073 DIVariable DV = Var->getVariable();
1074 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1076 unsigned ArgNo = DV.getArgNumber();
1080 size_t Size = CurrentFnArguments.size();
1082 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1083 // llvm::Function argument size is not good indicator of how many
1084 // arguments does the function have at source level.
1086 CurrentFnArguments.resize(ArgNo * 2);
1087 CurrentFnArguments[ArgNo - 1] = Var;
1091 // Collect variable information from side table maintained by MMI.
1092 void DwarfDebug::collectVariableInfoFromMMITable(
1093 SmallPtrSet<const MDNode *, 16> &Processed) {
1094 for (const auto &VI : MMI->getVariableDbgInfo()) {
1097 Processed.insert(VI.Var);
1098 DIVariable DV(VI.Var);
1099 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1101 // If variable scope is not found then skip this variable.
1105 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1106 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1107 RegVar->setFrameIndex(VI.Slot);
1108 if (!addCurrentFnArgument(RegVar, Scope))
1109 addScopeVariable(Scope, RegVar);
1111 AbsDbgVariable->setFrameIndex(VI.Slot);
1115 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1117 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1118 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1119 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1120 MI->getOperand(0).getReg() &&
1121 (MI->getOperand(1).isImm() ||
1122 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1125 // Get .debug_loc entry for the instruction range starting at MI.
1126 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1127 const MCSymbol *FLabel,
1128 const MCSymbol *SLabel,
1129 const MachineInstr *MI,
1130 DwarfCompileUnit *Unit) {
1131 const MDNode *Var = MI->getDebugVariable();
1133 assert(MI->getNumOperands() == 3);
1134 if (MI->getOperand(0).isReg()) {
1135 MachineLocation MLoc;
1136 // If the second operand is an immediate, this is a
1137 // register-indirect address.
1138 if (!MI->getOperand(1).isImm())
1139 MLoc.set(MI->getOperand(0).getReg());
1141 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1142 return DebugLocEntry(FLabel, SLabel, MLoc, Var, Unit);
1144 if (MI->getOperand(0).isImm())
1145 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm(), Var, Unit);
1146 if (MI->getOperand(0).isFPImm())
1147 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm(),
1149 if (MI->getOperand(0).isCImm())
1150 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm(),
1153 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1156 // Find variables for each lexical scope.
1158 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1160 // Grab the variable info that was squirreled away in the MMI side-table.
1161 collectVariableInfoFromMMITable(Processed);
1163 for (const MDNode *Var : UserVariables) {
1164 if (Processed.count(Var))
1167 // History contains relevant DBG_VALUE instructions for Var and instructions
1169 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1170 if (History.empty())
1172 const MachineInstr *MInsn = History.front();
1175 LexicalScope *Scope = NULL;
1176 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1177 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1178 Scope = LScopes.getCurrentFunctionScope();
1179 else if (MDNode *IA = DV.getInlinedAt())
1180 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1182 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1183 // If variable scope is not found then skip this variable.
1187 Processed.insert(DV);
1188 assert(MInsn->isDebugValue() && "History must begin with debug value");
1189 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1190 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1191 if (!addCurrentFnArgument(RegVar, Scope))
1192 addScopeVariable(Scope, RegVar);
1194 AbsVar->setMInsn(MInsn);
1196 // Simplify ranges that are fully coalesced.
1197 if (History.size() <= 1 ||
1198 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1199 RegVar->setMInsn(MInsn);
1203 // Handle multiple DBG_VALUE instructions describing one variable.
1204 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1206 DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1207 DebugLocList &LocList = DotDebugLocEntries.back();
1209 Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1210 SmallVector<DebugLocEntry, 4> &DebugLoc = LocList.List;
1211 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1212 HI = History.begin(),
1215 const MachineInstr *Begin = *HI;
1216 assert(Begin->isDebugValue() && "Invalid History entry");
1218 // Check if DBG_VALUE is truncating a range.
1219 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1220 !Begin->getOperand(0).getReg())
1223 // Compute the range for a register location.
1224 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1225 const MCSymbol *SLabel = 0;
1228 // If Begin is the last instruction in History then its value is valid
1229 // until the end of the function.
1230 SLabel = FunctionEndSym;
1232 const MachineInstr *End = HI[1];
1233 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1234 << "\t" << *Begin << "\t" << *End << "\n");
1235 if (End->isDebugValue())
1236 SLabel = getLabelBeforeInsn(End);
1238 // End is a normal instruction clobbering the range.
1239 SLabel = getLabelAfterInsn(End);
1240 assert(SLabel && "Forgot label after clobber instruction");
1245 // The value is valid until the next DBG_VALUE or clobber.
1246 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1247 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1248 DebugLocEntry Loc = getDebugLocEntry(Asm, FLabel, SLabel, Begin, TheCU);
1249 if (DebugLoc.empty() || !DebugLoc.back().Merge(Loc))
1250 DebugLoc.push_back(std::move(Loc));
1254 // Collect info for variables that were optimized out.
1255 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1256 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1257 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1258 DIVariable DV(Variables.getElement(i));
1259 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1261 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1262 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1266 // Return Label preceding the instruction.
1267 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1268 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1269 assert(Label && "Didn't insert label before instruction");
1273 // Return Label immediately following the instruction.
1274 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1275 return LabelsAfterInsn.lookup(MI);
1278 // Process beginning of an instruction.
1279 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1282 // Check if source location changes, but ignore DBG_VALUE locations.
1283 if (!MI->isDebugValue()) {
1284 DebugLoc DL = MI->getDebugLoc();
1285 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1288 if (DL == PrologEndLoc) {
1289 Flags |= DWARF2_FLAG_PROLOGUE_END;
1290 PrologEndLoc = DebugLoc();
1292 if (PrologEndLoc.isUnknown())
1293 Flags |= DWARF2_FLAG_IS_STMT;
1295 if (!DL.isUnknown()) {
1296 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1297 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1299 recordSourceLine(0, 0, 0, 0);
1303 // Insert labels where requested.
1304 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1305 LabelsBeforeInsn.find(MI);
1308 if (I == LabelsBeforeInsn.end())
1311 // Label already assigned.
1316 PrevLabel = MMI->getContext().CreateTempSymbol();
1317 Asm->OutStreamer.EmitLabel(PrevLabel);
1319 I->second = PrevLabel;
1322 // Process end of an instruction.
1323 void DwarfDebug::endInstruction() {
1325 // Don't create a new label after DBG_VALUE instructions.
1326 // They don't generate code.
1327 if (!CurMI->isDebugValue())
1330 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1331 LabelsAfterInsn.find(CurMI);
1335 if (I == LabelsAfterInsn.end())
1338 // Label already assigned.
1342 // We need a label after this instruction.
1344 PrevLabel = MMI->getContext().CreateTempSymbol();
1345 Asm->OutStreamer.EmitLabel(PrevLabel);
1347 I->second = PrevLabel;
1350 // Each LexicalScope has first instruction and last instruction to mark
1351 // beginning and end of a scope respectively. Create an inverse map that list
1352 // scopes starts (and ends) with an instruction. One instruction may start (or
1353 // end) multiple scopes. Ignore scopes that are not reachable.
1354 void DwarfDebug::identifyScopeMarkers() {
1355 SmallVector<LexicalScope *, 4> WorkList;
1356 WorkList.push_back(LScopes.getCurrentFunctionScope());
1357 while (!WorkList.empty()) {
1358 LexicalScope *S = WorkList.pop_back_val();
1360 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1361 if (!Children.empty())
1362 WorkList.append(Children.begin(), Children.end());
1364 if (S->isAbstractScope())
1367 for (const InsnRange &R : S->getRanges()) {
1368 assert(R.first && "InsnRange does not have first instruction!");
1369 assert(R.second && "InsnRange does not have second instruction!");
1370 requestLabelBeforeInsn(R.first);
1371 requestLabelAfterInsn(R.second);
1376 // Gather pre-function debug information. Assumes being called immediately
1377 // after the function entry point has been emitted.
1378 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1381 // If there's no debug info for the function we're not going to do anything.
1382 if (!MMI->hasDebugInfo())
1385 // Grab the lexical scopes for the function, if we don't have any of those
1386 // then we're not going to be able to do anything.
1387 LScopes.initialize(*MF);
1388 if (LScopes.empty())
1391 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1393 // Make sure that each lexical scope will have a begin/end label.
1394 identifyScopeMarkers();
1396 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1397 // belongs to so that we add to the correct per-cu line table in the
1399 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1400 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1401 assert(TheCU && "Unable to find compile unit!");
1402 if (Asm->OutStreamer.hasRawTextSupport())
1403 // Use a single line table if we are generating assembly.
1404 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1406 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1408 // Emit a label for the function so that we have a beginning address.
1409 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1410 // Assumes in correct section after the entry point.
1411 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1413 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1414 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1415 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1417 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1419 bool AtBlockEntry = true;
1420 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1422 const MachineInstr *MI = II;
1424 if (MI->isDebugValue()) {
1425 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1427 // Keep track of user variables.
1428 const MDNode *Var = MI->getDebugVariable();
1430 // Variable is in a register, we need to check for clobbers.
1431 if (isDbgValueInDefinedReg(MI))
1432 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1434 // Check the history of this variable.
1435 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1436 if (History.empty()) {
1437 UserVariables.push_back(Var);
1438 // The first mention of a function argument gets the FunctionBeginSym
1439 // label, so arguments are visible when breaking at function entry.
1441 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1442 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1443 LabelsBeforeInsn[MI] = FunctionBeginSym;
1445 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1446 const MachineInstr *Prev = History.back();
1447 if (Prev->isDebugValue()) {
1448 // Coalesce identical entries at the end of History.
1449 if (History.size() >= 2 &&
1450 Prev->isIdenticalTo(History[History.size() - 2])) {
1451 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1452 << "\t" << *Prev << "\t"
1453 << *History[History.size() - 2] << "\n");
1457 // Terminate old register assignments that don't reach MI;
1458 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1459 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1460 isDbgValueInDefinedReg(Prev)) {
1461 // Previous register assignment needs to terminate at the end of
1463 MachineBasicBlock::const_iterator LastMI =
1464 PrevMBB->getLastNonDebugInstr();
1465 if (LastMI == PrevMBB->end()) {
1466 // Drop DBG_VALUE for empty range.
1467 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1468 << "\t" << *Prev << "\n");
1470 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1471 // Terminate after LastMI.
1472 History.push_back(LastMI);
1476 History.push_back(MI);
1478 // Not a DBG_VALUE instruction.
1479 if (!MI->isPosition())
1480 AtBlockEntry = false;
1482 // First known non-DBG_VALUE and non-frame setup location marks
1483 // the beginning of the function body.
1484 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1485 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1486 PrologEndLoc = MI->getDebugLoc();
1488 // Check if the instruction clobbers any registers with debug vars.
1489 for (const MachineOperand &MO : MI->operands()) {
1490 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1492 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1495 const MDNode *Var = LiveUserVar[Reg];
1498 // Reg is now clobbered.
1499 LiveUserVar[Reg] = 0;
1501 // Was MD last defined by a DBG_VALUE referring to Reg?
1502 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1503 if (HistI == DbgValues.end())
1505 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1506 if (History.empty())
1508 const MachineInstr *Prev = History.back();
1509 // Sanity-check: Register assignments are terminated at the end of
1511 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1513 // Is the variable still in Reg?
1514 if (!isDbgValueInDefinedReg(Prev) ||
1515 Prev->getOperand(0).getReg() != Reg)
1517 // Var is clobbered. Make sure the next instruction gets a label.
1518 History.push_back(MI);
1525 for (auto &I : DbgValues) {
1526 SmallVectorImpl<const MachineInstr *> &History = I.second;
1527 if (History.empty())
1530 // Make sure the final register assignments are terminated.
1531 const MachineInstr *Prev = History.back();
1532 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1533 const MachineBasicBlock *PrevMBB = Prev->getParent();
1534 MachineBasicBlock::const_iterator LastMI =
1535 PrevMBB->getLastNonDebugInstr();
1536 if (LastMI == PrevMBB->end())
1537 // Drop DBG_VALUE for empty range.
1539 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1540 // Terminate after LastMI.
1541 History.push_back(LastMI);
1544 // Request labels for the full history.
1545 for (const MachineInstr *MI : History) {
1546 if (MI->isDebugValue())
1547 requestLabelBeforeInsn(MI);
1549 requestLabelAfterInsn(MI);
1553 PrevInstLoc = DebugLoc();
1554 PrevLabel = FunctionBeginSym;
1556 // Record beginning of function.
1557 if (!PrologEndLoc.isUnknown()) {
1558 DebugLoc FnStartDL =
1559 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1561 FnStartDL.getLine(), FnStartDL.getCol(),
1562 FnStartDL.getScope(MF->getFunction()->getContext()),
1563 // We'd like to list the prologue as "not statements" but GDB behaves
1564 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1565 DWARF2_FLAG_IS_STMT);
1569 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1570 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1571 DIVariable DV = Var->getVariable();
1572 // Variables with positive arg numbers are parameters.
1573 if (unsigned ArgNum = DV.getArgNumber()) {
1574 // Keep all parameters in order at the start of the variable list to ensure
1575 // function types are correct (no out-of-order parameters)
1577 // This could be improved by only doing it for optimized builds (unoptimized
1578 // builds have the right order to begin with), searching from the back (this
1579 // would catch the unoptimized case quickly), or doing a binary search
1580 // rather than linear search.
1581 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1582 while (I != Vars.end()) {
1583 unsigned CurNum = (*I)->getVariable().getArgNumber();
1584 // A local (non-parameter) variable has been found, insert immediately
1588 // A later indexed parameter has been found, insert immediately before it.
1589 if (CurNum > ArgNum)
1593 Vars.insert(I, Var);
1597 Vars.push_back(Var);
1600 // Gather and emit post-function debug information.
1601 void DwarfDebug::endFunction(const MachineFunction *MF) {
1602 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1603 // though the beginFunction may not be called at all.
1604 // We should handle both cases.
1608 assert(CurFn == MF);
1611 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1612 // If we don't have a lexical scope for this function then there will
1613 // be a hole in the range information. Keep note of this by setting the
1614 // previously used section to nullptr.
1615 PrevSection = nullptr;
1621 // Define end label for subprogram.
1622 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1623 // Assumes in correct section after the entry point.
1624 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1626 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1627 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1629 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1630 collectVariableInfo(ProcessedVars);
1632 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1633 DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1635 // Construct abstract scopes.
1636 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1637 DISubprogram SP(AScope->getScopeNode());
1638 if (SP.isSubprogram()) {
1639 // Collect info for variables that were optimized out.
1640 DIArray Variables = SP.getVariables();
1641 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1642 DIVariable DV(Variables.getElement(i));
1643 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1645 // Check that DbgVariable for DV wasn't created earlier, when
1646 // findAbstractVariable() was called for inlined instance of DV.
1647 LLVMContext &Ctx = DV->getContext();
1648 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1649 if (AbstractVariables.lookup(CleanDV))
1651 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1652 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1655 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1656 constructScopeDIE(TheCU, AScope);
1659 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1660 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1661 TheCU.addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1663 // Add the range of this function to the list of ranges for the CU.
1664 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1665 TheCU.addRange(std::move(Span));
1666 PrevSection = Asm->getCurrentSection();
1670 for (auto &I : ScopeVariables)
1671 DeleteContainerPointers(I.second);
1672 ScopeVariables.clear();
1673 DeleteContainerPointers(CurrentFnArguments);
1674 UserVariables.clear();
1676 AbstractVariables.clear();
1677 LabelsBeforeInsn.clear();
1678 LabelsAfterInsn.clear();
1683 // Register a source line with debug info. Returns the unique label that was
1684 // emitted and which provides correspondence to the source line list.
1685 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1690 unsigned Discriminator = 0;
1692 DIDescriptor Scope(S);
1694 if (Scope.isCompileUnit()) {
1695 DICompileUnit CU(S);
1696 Fn = CU.getFilename();
1697 Dir = CU.getDirectory();
1698 } else if (Scope.isFile()) {
1700 Fn = F.getFilename();
1701 Dir = F.getDirectory();
1702 } else if (Scope.isSubprogram()) {
1704 Fn = SP.getFilename();
1705 Dir = SP.getDirectory();
1706 } else if (Scope.isLexicalBlockFile()) {
1707 DILexicalBlockFile DBF(S);
1708 Fn = DBF.getFilename();
1709 Dir = DBF.getDirectory();
1710 } else if (Scope.isLexicalBlock()) {
1711 DILexicalBlock DB(S);
1712 Fn = DB.getFilename();
1713 Dir = DB.getDirectory();
1714 Discriminator = DB.getDiscriminator();
1716 llvm_unreachable("Unexpected scope info");
1718 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1719 Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1720 .getOrCreateSourceID(Fn, Dir);
1722 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1726 //===----------------------------------------------------------------------===//
1728 //===----------------------------------------------------------------------===//
1730 // Emit initial Dwarf sections with a label at the start of each one.
1731 void DwarfDebug::emitSectionLabels() {
1732 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1734 // Dwarf sections base addresses.
1735 DwarfInfoSectionSym =
1736 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1737 if (useSplitDwarf())
1738 DwarfInfoDWOSectionSym =
1739 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1740 DwarfAbbrevSectionSym =
1741 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1742 if (useSplitDwarf())
1743 DwarfAbbrevDWOSectionSym = emitSectionSym(
1744 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1745 if (GenerateARangeSection)
1746 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1748 DwarfLineSectionSym =
1749 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1750 if (GenerateGnuPubSections) {
1751 DwarfGnuPubNamesSectionSym =
1752 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1753 DwarfGnuPubTypesSectionSym =
1754 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1755 } else if (HasDwarfPubSections) {
1756 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1757 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1760 DwarfStrSectionSym =
1761 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1762 if (useSplitDwarf()) {
1763 DwarfStrDWOSectionSym =
1764 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1765 DwarfAddrSectionSym =
1766 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1767 DwarfDebugLocSectionSym =
1768 emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1770 DwarfDebugLocSectionSym =
1771 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1772 DwarfDebugRangeSectionSym =
1773 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1776 // Recursively emits a debug information entry.
1777 void DwarfDebug::emitDIE(DIE &Die) {
1778 // Get the abbreviation for this DIE.
1779 const DIEAbbrev &Abbrev = Die.getAbbrev();
1781 // Emit the code (index) for the abbreviation.
1782 if (Asm->isVerbose())
1783 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1784 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1785 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1786 dwarf::TagString(Abbrev.getTag()));
1787 Asm->EmitULEB128(Abbrev.getNumber());
1789 const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1790 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1792 // Emit the DIE attribute values.
1793 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1794 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1795 dwarf::Form Form = AbbrevData[i].getForm();
1796 assert(Form && "Too many attributes for DIE (check abbreviation)");
1798 if (Asm->isVerbose()) {
1799 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1800 if (Attr == dwarf::DW_AT_accessibility)
1801 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1802 cast<DIEInteger>(Values[i])->getValue()));
1805 // Emit an attribute using the defined form.
1806 Values[i]->EmitValue(Asm, Form);
1809 // Emit the DIE children if any.
1810 if (Abbrev.hasChildren()) {
1811 for (auto &Child : Die.getChildren())
1814 Asm->OutStreamer.AddComment("End Of Children Mark");
1819 // Emit the debug info section.
1820 void DwarfDebug::emitDebugInfo() {
1821 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1823 Holder.emitUnits(this, DwarfAbbrevSectionSym);
1826 // Emit the abbreviation section.
1827 void DwarfDebug::emitAbbreviations() {
1828 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1830 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1833 // Emit the last address of the section and the end of the line matrix.
1834 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1835 // Define last address of section.
1836 Asm->OutStreamer.AddComment("Extended Op");
1839 Asm->OutStreamer.AddComment("Op size");
1840 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1841 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1842 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1844 Asm->OutStreamer.AddComment("Section end label");
1846 Asm->OutStreamer.EmitSymbolValue(
1847 Asm->GetTempSymbol("section_end", SectionEnd),
1848 Asm->getDataLayout().getPointerSize());
1850 // Mark end of matrix.
1851 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1857 // Emit visible names into a hashed accelerator table section.
1858 void DwarfDebug::emitAccelNames() {
1860 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1861 for (const auto &TheU : getUnits()) {
1862 for (const auto &GI : TheU->getAccelNames()) {
1863 StringRef Name = GI.getKey();
1864 for (const DIE *D : GI.second)
1865 AT.AddName(Name, D);
1869 AT.FinalizeTable(Asm, "Names");
1870 Asm->OutStreamer.SwitchSection(
1871 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1872 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1873 Asm->OutStreamer.EmitLabel(SectionBegin);
1875 // Emit the full data.
1876 AT.Emit(Asm, SectionBegin, &InfoHolder);
1879 // Emit objective C classes and categories into a hashed accelerator table
1881 void DwarfDebug::emitAccelObjC() {
1883 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1884 for (const auto &TheU : getUnits()) {
1885 for (const auto &GI : TheU->getAccelObjC()) {
1886 StringRef Name = GI.getKey();
1887 for (const DIE *D : GI.second)
1888 AT.AddName(Name, D);
1892 AT.FinalizeTable(Asm, "ObjC");
1893 Asm->OutStreamer.SwitchSection(
1894 Asm->getObjFileLowering().getDwarfAccelObjCSection());
1895 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1896 Asm->OutStreamer.EmitLabel(SectionBegin);
1898 // Emit the full data.
1899 AT.Emit(Asm, SectionBegin, &InfoHolder);
1902 // Emit namespace dies into a hashed accelerator table.
1903 void DwarfDebug::emitAccelNamespaces() {
1905 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1906 for (const auto &TheU : getUnits()) {
1907 for (const auto &GI : TheU->getAccelNamespace()) {
1908 StringRef Name = GI.getKey();
1909 for (const DIE *D : GI.second)
1910 AT.AddName(Name, D);
1914 AT.FinalizeTable(Asm, "namespac");
1915 Asm->OutStreamer.SwitchSection(
1916 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
1917 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1918 Asm->OutStreamer.EmitLabel(SectionBegin);
1920 // Emit the full data.
1921 AT.Emit(Asm, SectionBegin, &InfoHolder);
1924 // Emit type dies into a hashed accelerator table.
1925 void DwarfDebug::emitAccelTypes() {
1926 std::vector<DwarfAccelTable::Atom> Atoms;
1928 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
1930 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
1932 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
1933 DwarfAccelTable AT(Atoms);
1934 for (const auto &TheU : getUnits()) {
1935 for (const auto &GI : TheU->getAccelTypes()) {
1936 StringRef Name = GI.getKey();
1937 for (const auto &DI : GI.second)
1938 AT.AddName(Name, DI.first, DI.second);
1942 AT.FinalizeTable(Asm, "types");
1943 Asm->OutStreamer.SwitchSection(
1944 Asm->getObjFileLowering().getDwarfAccelTypesSection());
1945 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1946 Asm->OutStreamer.EmitLabel(SectionBegin);
1948 // Emit the full data.
1949 AT.Emit(Asm, SectionBegin, &InfoHolder);
1952 // Public name handling.
1953 // The format for the various pubnames:
1955 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1956 // for the DIE that is named.
1958 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1959 // into the CU and the index value is computed according to the type of value
1960 // for the DIE that is named.
1962 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1963 // it's the offset within the debug_info/debug_types dwo section, however, the
1964 // reference in the pubname header doesn't change.
1966 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1967 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1969 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1971 // We could have a specification DIE that has our most of our knowledge,
1972 // look for that now.
1973 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1975 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1976 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
1977 Linkage = dwarf::GIEL_EXTERNAL;
1978 } else if (Die->findAttribute(dwarf::DW_AT_external))
1979 Linkage = dwarf::GIEL_EXTERNAL;
1981 switch (Die->getTag()) {
1982 case dwarf::DW_TAG_class_type:
1983 case dwarf::DW_TAG_structure_type:
1984 case dwarf::DW_TAG_union_type:
1985 case dwarf::DW_TAG_enumeration_type:
1986 return dwarf::PubIndexEntryDescriptor(
1987 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1988 ? dwarf::GIEL_STATIC
1989 : dwarf::GIEL_EXTERNAL);
1990 case dwarf::DW_TAG_typedef:
1991 case dwarf::DW_TAG_base_type:
1992 case dwarf::DW_TAG_subrange_type:
1993 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1994 case dwarf::DW_TAG_namespace:
1995 return dwarf::GIEK_TYPE;
1996 case dwarf::DW_TAG_subprogram:
1997 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1998 case dwarf::DW_TAG_constant:
1999 case dwarf::DW_TAG_variable:
2000 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2001 case dwarf::DW_TAG_enumerator:
2002 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2003 dwarf::GIEL_STATIC);
2005 return dwarf::GIEK_NONE;
2009 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2011 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2012 const MCSection *PSec =
2013 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2014 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2016 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2019 void DwarfDebug::emitDebugPubSection(
2020 bool GnuStyle, const MCSection *PSec, StringRef Name,
2021 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2022 for (const auto &NU : CUMap) {
2023 DwarfCompileUnit *TheU = NU.second;
2025 const auto &Globals = (TheU->*Accessor)();
2027 if (Globals.empty())
2030 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2032 unsigned ID = TheU->getUniqueID();
2034 // Start the dwarf pubnames section.
2035 Asm->OutStreamer.SwitchSection(PSec);
2038 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2039 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2040 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2041 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2043 Asm->OutStreamer.EmitLabel(BeginLabel);
2045 Asm->OutStreamer.AddComment("DWARF Version");
2046 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2048 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2049 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2051 Asm->OutStreamer.AddComment("Compilation Unit Length");
2052 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2054 // Emit the pubnames for this compilation unit.
2055 for (const auto &GI : Globals) {
2056 const char *Name = GI.getKeyData();
2057 const DIE *Entity = GI.second;
2059 Asm->OutStreamer.AddComment("DIE offset");
2060 Asm->EmitInt32(Entity->getOffset());
2063 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2064 Asm->OutStreamer.AddComment(
2065 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2066 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2067 Asm->EmitInt8(Desc.toBits());
2070 Asm->OutStreamer.AddComment("External Name");
2071 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2074 Asm->OutStreamer.AddComment("End Mark");
2076 Asm->OutStreamer.EmitLabel(EndLabel);
2080 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2081 const MCSection *PSec =
2082 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2083 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2085 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2088 // Emit visible names into a debug str section.
2089 void DwarfDebug::emitDebugStr() {
2090 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2091 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2094 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2095 const DebugLocEntry &Entry) {
2096 DIVariable DV(Entry.getVariable());
2097 if (Entry.isInt()) {
2098 DIBasicType BTy(resolve(DV.getType()));
2099 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2100 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2101 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2102 Streamer.EmitSLEB128(Entry.getInt());
2104 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2105 Streamer.EmitULEB128(Entry.getInt());
2107 } else if (Entry.isLocation()) {
2108 MachineLocation Loc = Entry.getLoc();
2109 if (!DV.hasComplexAddress())
2111 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2113 // Complex address entry.
2114 unsigned N = DV.getNumAddrElements();
2116 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2117 if (Loc.getOffset()) {
2119 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2120 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2121 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2122 Streamer.EmitSLEB128(DV.getAddrElement(1));
2124 // If first address element is OpPlus then emit
2125 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2126 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2127 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2131 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2134 // Emit remaining complex address elements.
2135 for (; i < N; ++i) {
2136 uint64_t Element = DV.getAddrElement(i);
2137 if (Element == DIBuilder::OpPlus) {
2138 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2139 Streamer.EmitULEB128(DV.getAddrElement(++i));
2140 } else if (Element == DIBuilder::OpDeref) {
2142 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2144 llvm_unreachable("unknown Opcode found in complex address");
2148 // else ... ignore constant fp. There is not any good way to
2149 // to represent them here in dwarf.
2153 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2154 Asm->OutStreamer.AddComment("Loc expr size");
2155 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2156 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2157 Asm->EmitLabelDifference(end, begin, 2);
2158 Asm->OutStreamer.EmitLabel(begin);
2160 APByteStreamer Streamer(*Asm);
2161 emitDebugLocEntry(Streamer, Entry);
2163 Asm->OutStreamer.EmitLabel(end);
2166 // Emit locations into the debug loc section.
2167 void DwarfDebug::emitDebugLoc() {
2168 // Start the dwarf loc section.
2169 Asm->OutStreamer.SwitchSection(
2170 Asm->getObjFileLowering().getDwarfLocSection());
2171 unsigned char Size = Asm->getDataLayout().getPointerSize();
2172 for (const auto &DebugLoc : DotDebugLocEntries) {
2173 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2174 for (const auto &Entry : DebugLoc.List) {
2175 // Set up the range. This range is relative to the entry point of the
2176 // compile unit. This is a hard coded 0 for low_pc when we're emitting
2177 // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2178 const DwarfCompileUnit *CU = Entry.getCU();
2179 if (CU->getRanges().size() == 1) {
2180 // Grab the begin symbol from the first range as our base.
2181 const MCSymbol *Base = CU->getRanges()[0].getStart();
2182 Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2183 Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2185 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2186 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2189 emitDebugLocEntryLocation(Entry);
2191 Asm->OutStreamer.EmitIntValue(0, Size);
2192 Asm->OutStreamer.EmitIntValue(0, Size);
2196 void DwarfDebug::emitDebugLocDWO() {
2197 Asm->OutStreamer.SwitchSection(
2198 Asm->getObjFileLowering().getDwarfLocDWOSection());
2199 for (const auto &DebugLoc : DotDebugLocEntries) {
2200 Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2201 for (const auto &Entry : DebugLoc.List) {
2202 // Just always use start_length for now - at least that's one address
2203 // rather than two. We could get fancier and try to, say, reuse an
2204 // address we know we've emitted elsewhere (the start of the function?
2205 // The start of the CU or CU subrange that encloses this range?)
2206 Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2207 unsigned idx = InfoHolder.getAddrPoolIndex(Entry.getBeginSym());
2208 Asm->EmitULEB128(idx);
2209 Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2211 emitDebugLocEntryLocation(Entry);
2213 Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2218 const MCSymbol *Start, *End;
2221 // Emit a debug aranges section, containing a CU lookup for any
2222 // address we can tie back to a CU.
2223 void DwarfDebug::emitDebugARanges() {
2224 // Start the dwarf aranges section.
2225 Asm->OutStreamer.SwitchSection(
2226 Asm->getObjFileLowering().getDwarfARangesSection());
2228 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2232 // Build a list of sections used.
2233 std::vector<const MCSection *> Sections;
2234 for (const auto &it : SectionMap) {
2235 const MCSection *Section = it.first;
2236 Sections.push_back(Section);
2239 // Sort the sections into order.
2240 // This is only done to ensure consistent output order across different runs.
2241 std::sort(Sections.begin(), Sections.end(), SectionSort);
2243 // Build a set of address spans, sorted by CU.
2244 for (const MCSection *Section : Sections) {
2245 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2246 if (List.size() < 2)
2249 // Sort the symbols by offset within the section.
2250 std::sort(List.begin(), List.end(),
2251 [&](const SymbolCU &A, const SymbolCU &B) {
2252 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2253 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2255 // Symbols with no order assigned should be placed at the end.
2256 // (e.g. section end labels)
2264 // If we have no section (e.g. common), just write out
2265 // individual spans for each symbol.
2266 if (Section == NULL) {
2267 for (const SymbolCU &Cur : List) {
2269 Span.Start = Cur.Sym;
2272 Spans[Cur.CU].push_back(Span);
2275 // Build spans between each label.
2276 const MCSymbol *StartSym = List[0].Sym;
2277 for (size_t n = 1, e = List.size(); n < e; n++) {
2278 const SymbolCU &Prev = List[n - 1];
2279 const SymbolCU &Cur = List[n];
2281 // Try and build the longest span we can within the same CU.
2282 if (Cur.CU != Prev.CU) {
2284 Span.Start = StartSym;
2286 Spans[Prev.CU].push_back(Span);
2293 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2295 // Build a list of CUs used.
2296 std::vector<DwarfCompileUnit *> CUs;
2297 for (const auto &it : Spans) {
2298 DwarfCompileUnit *CU = it.first;
2302 // Sort the CU list (again, to ensure consistent output order).
2303 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2304 return A->getUniqueID() < B->getUniqueID();
2307 // Emit an arange table for each CU we used.
2308 for (DwarfCompileUnit *CU : CUs) {
2309 std::vector<ArangeSpan> &List = Spans[CU];
2311 // Emit size of content not including length itself.
2312 unsigned ContentSize =
2313 sizeof(int16_t) + // DWARF ARange version number
2314 sizeof(int32_t) + // Offset of CU in the .debug_info section
2315 sizeof(int8_t) + // Pointer Size (in bytes)
2316 sizeof(int8_t); // Segment Size (in bytes)
2318 unsigned TupleSize = PtrSize * 2;
2320 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2322 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2324 ContentSize += Padding;
2325 ContentSize += (List.size() + 1) * TupleSize;
2327 // For each compile unit, write the list of spans it covers.
2328 Asm->OutStreamer.AddComment("Length of ARange Set");
2329 Asm->EmitInt32(ContentSize);
2330 Asm->OutStreamer.AddComment("DWARF Arange version number");
2331 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2332 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2333 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2334 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2335 Asm->EmitInt8(PtrSize);
2336 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2339 Asm->OutStreamer.EmitFill(Padding, 0xff);
2341 for (const ArangeSpan &Span : List) {
2342 Asm->EmitLabelReference(Span.Start, PtrSize);
2344 // Calculate the size as being from the span start to it's end.
2346 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2348 // For symbols without an end marker (e.g. common), we
2349 // write a single arange entry containing just that one symbol.
2350 uint64_t Size = SymSize[Span.Start];
2354 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2358 Asm->OutStreamer.AddComment("ARange terminator");
2359 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2360 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2364 // Emit visible names into a debug ranges section.
2365 void DwarfDebug::emitDebugRanges() {
2366 // Start the dwarf ranges section.
2367 Asm->OutStreamer.SwitchSection(
2368 Asm->getObjFileLowering().getDwarfRangesSection());
2370 // Size for our labels.
2371 unsigned char Size = Asm->getDataLayout().getPointerSize();
2373 // Grab the specific ranges for the compile units in the module.
2374 for (const auto &I : CUMap) {
2375 DwarfCompileUnit *TheCU = I.second;
2377 // Emit a symbol so we can find the beginning of our ranges.
2378 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2380 // Iterate over the misc ranges for the compile units in the module.
2381 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2382 // Emit our symbol so we can find the beginning of the range.
2383 Asm->OutStreamer.EmitLabel(List.getSym());
2385 for (const RangeSpan &Range : List.getRanges()) {
2386 const MCSymbol *Begin = Range.getStart();
2387 const MCSymbol *End = Range.getEnd();
2388 assert(Begin && "Range without a begin symbol?");
2389 assert(End && "Range without an end symbol?");
2390 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2391 Asm->OutStreamer.EmitSymbolValue(End, Size);
2394 // And terminate the list with two 0 values.
2395 Asm->OutStreamer.EmitIntValue(0, Size);
2396 Asm->OutStreamer.EmitIntValue(0, Size);
2399 // Now emit a range for the CU itself.
2400 if (TheCU->getRanges().size() > 1) {
2401 Asm->OutStreamer.EmitLabel(
2402 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2403 for (const RangeSpan &Range : TheCU->getRanges()) {
2404 const MCSymbol *Begin = Range.getStart();
2405 const MCSymbol *End = Range.getEnd();
2406 assert(Begin && "Range without a begin symbol?");
2407 assert(End && "Range without an end symbol?");
2408 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2409 Asm->OutStreamer.EmitSymbolValue(End, Size);
2411 // And terminate the list with two 0 values.
2412 Asm->OutStreamer.EmitIntValue(0, Size);
2413 Asm->OutStreamer.EmitIntValue(0, Size);
2418 // DWARF5 Experimental Separate Dwarf emitters.
2420 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE *Die,
2421 std::unique_ptr<DwarfUnit> NewU) {
2422 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2423 U.getCUNode().getSplitDebugFilename());
2425 if (!CompilationDir.empty())
2426 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2428 addGnuPubAttributes(*NewU, Die);
2430 SkeletonHolder.addUnit(std::move(NewU));
2433 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2434 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2435 // DW_AT_addr_base, DW_AT_ranges_base.
2436 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2438 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2439 auto OwnedUnit = make_unique<DwarfCompileUnit>(
2440 CU.getUniqueID(), Die, CU.getCUNode(), Asm, this, &SkeletonHolder);
2441 DwarfCompileUnit &NewCU = *OwnedUnit;
2442 NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2443 DwarfInfoSectionSym);
2445 NewCU.initStmtList(DwarfLineSectionSym);
2447 initSkeletonUnit(CU, Die, std::move(OwnedUnit));
2452 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2454 DwarfTypeUnit &DwarfDebug::constructSkeletonTU(DwarfTypeUnit &TU) {
2455 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2456 *SkeletonHolder.getUnits()[TU.getCU().getUniqueID()]);
2458 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2459 auto OwnedUnit = make_unique<DwarfTypeUnit>(TU.getUniqueID(), Die, CU, Asm,
2460 this, &SkeletonHolder);
2461 DwarfTypeUnit &NewTU = *OwnedUnit;
2462 NewTU.setTypeSignature(TU.getTypeSignature());
2463 NewTU.setType(NULL);
2465 Asm->getObjFileLowering().getDwarfTypesSection(TU.getTypeSignature()));
2467 initSkeletonUnit(TU, Die, std::move(OwnedUnit));
2471 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2472 // compile units that would normally be in debug_info.
2473 void DwarfDebug::emitDebugInfoDWO() {
2474 assert(useSplitDwarf() && "No split dwarf debug info?");
2475 // Don't pass an abbrev symbol, using a constant zero instead so as not to
2476 // emit relocations into the dwo file.
2477 InfoHolder.emitUnits(this, /* AbbrevSymbol */nullptr);
2480 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2481 // abbreviations for the .debug_info.dwo section.
2482 void DwarfDebug::emitDebugAbbrevDWO() {
2483 assert(useSplitDwarf() && "No split dwarf?");
2484 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2487 void DwarfDebug::emitDebugLineDWO() {
2488 assert(useSplitDwarf() && "No split dwarf?");
2489 Asm->OutStreamer.SwitchSection(
2490 Asm->getObjFileLowering().getDwarfLineDWOSection());
2491 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2494 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2495 // string section and is identical in format to traditional .debug_str
2497 void DwarfDebug::emitDebugStrDWO() {
2498 assert(useSplitDwarf() && "No split dwarf?");
2499 const MCSection *OffSec =
2500 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2501 const MCSymbol *StrSym = DwarfStrSectionSym;
2502 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2506 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2507 if (!useSplitDwarf())
2510 SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2511 return &SplitTypeUnitFileTable;
2514 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2515 StringRef Identifier, DIE *RefDie,
2516 DICompositeType CTy) {
2517 // Flag the type unit reference as a declaration so that if it contains
2518 // members (implicit special members, static data member definitions, member
2519 // declarations for definitions in this CU, etc) consumers don't get confused
2520 // and think this is a full definition.
2521 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2523 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2525 CU.addDIETypeSignature(RefDie, *TU);
2529 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2531 make_unique<DwarfTypeUnit>(InfoHolder.getUnits().size(), UnitDie, CU, Asm,
2532 this, &InfoHolder, getDwoLineTable(CU));
2533 DwarfTypeUnit &NewTU = *OwnedUnit;
2535 InfoHolder.addUnit(std::move(OwnedUnit));
2537 NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2541 Hash.update(Identifier);
2542 // ... take the least significant 8 bytes and return those. Our MD5
2543 // implementation always returns its results in little endian, swap bytes
2545 MD5::MD5Result Result;
2547 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2548 NewTU.setTypeSignature(Signature);
2549 if (useSplitDwarf())
2550 NewTU.setSkeleton(constructSkeletonTU(NewTU));
2552 CU.applyStmtList(*UnitDie);
2554 NewTU.setType(NewTU.createTypeDIE(CTy));
2558 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2559 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2561 CU.addDIETypeSignature(RefDie, NewTU);
2564 void DwarfDebug::attachLowHighPC(DwarfCompileUnit &Unit, DIE *D,
2565 MCSymbol *Begin, MCSymbol *End) {
2566 Unit.addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2567 if (DwarfVersion < 4)
2568 Unit.addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2570 Unit.addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);