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 #define DEBUG_TYPE "dwarfdebug"
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/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.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/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.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"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
66 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
67 cl::desc("Add the CU hash as the dwo_id."),
71 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
72 cl::desc("Generate GNU-style pubnames and pubtypes"),
83 static cl::opt<DefaultOnOff>
84 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
85 cl::desc("Output prototype dwarf accelerator tables."),
86 cl::values(clEnumVal(Default, "Default for platform"),
87 clEnumVal(Enable, "Enabled"),
88 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 static cl::opt<DefaultOnOff>
92 SplitDwarf("split-dwarf", cl::Hidden,
93 cl::desc("Output prototype dwarf split debug info."),
94 cl::values(clEnumVal(Default, "Default for platform"),
95 clEnumVal(Enable, "Enabled"),
96 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 static cl::opt<DefaultOnOff>
100 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
101 cl::desc("Generate DWARF pubnames and pubtypes sections"),
102 cl::values(clEnumVal(Default, "Default for platform"),
103 clEnumVal(Enable, "Enabled"),
104 clEnumVal(Disable, "Disabled"), clEnumValEnd),
107 static cl::opt<unsigned>
108 DwarfVersionNumber("dwarf-version", cl::Hidden,
109 cl::desc("Generate DWARF for dwarf version."),
112 static const char *const DWARFGroupName = "DWARF Emission";
113 static const char *const DbgTimerName = "DWARF Debug Writer";
115 //===----------------------------------------------------------------------===//
117 // Configuration values for initial hash set sizes (log2).
119 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
123 /// resolve - Look in the DwarfDebug map for the MDNode that
124 /// corresponds to the reference.
125 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
126 return DD->resolve(Ref);
129 DIType DbgVariable::getType() const {
130 DIType Ty = Var.getType();
131 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
132 // addresses instead.
133 if (Var.isBlockByrefVariable()) {
134 /* Byref variables, in Blocks, are declared by the programmer as
135 "SomeType VarName;", but the compiler creates a
136 __Block_byref_x_VarName struct, and gives the variable VarName
137 either the struct, or a pointer to the struct, as its type. This
138 is necessary for various behind-the-scenes things the compiler
139 needs to do with by-reference variables in blocks.
141 However, as far as the original *programmer* is concerned, the
142 variable should still have type 'SomeType', as originally declared.
144 The following function dives into the __Block_byref_x_VarName
145 struct to find the original type of the variable. This will be
146 passed back to the code generating the type for the Debug
147 Information Entry for the variable 'VarName'. 'VarName' will then
148 have the original type 'SomeType' in its debug information.
150 The original type 'SomeType' will be the type of the field named
151 'VarName' inside the __Block_byref_x_VarName struct.
153 NOTE: In order for this to not completely fail on the debugger
154 side, the Debug Information Entry for the variable VarName needs to
155 have a DW_AT_location that tells the debugger how to unwind through
156 the pointers and __Block_byref_x_VarName struct to find the actual
157 value of the variable. The function addBlockByrefType does this. */
159 uint16_t tag = Ty.getTag();
161 if (tag == dwarf::DW_TAG_pointer_type)
162 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
164 DIArray Elements = DICompositeType(subType).getTypeArray();
165 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
166 DIDerivedType DT(Elements.getElement(i));
167 if (getName() == DT.getName())
168 return (resolve(DT.getTypeDerivedFrom()));
174 } // end llvm namespace
176 /// Return Dwarf Version by checking module flags.
177 static unsigned getDwarfVersionFromModule(const Module *M) {
178 Value *Val = M->getModuleFlag("Dwarf Version");
180 return dwarf::DWARF_VERSION;
181 return cast<ConstantInt>(Val)->getZExtValue();
184 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
185 : Asm(A), MMI(Asm->MMI), FirstCU(0),
186 AbbreviationsSet(InitAbbreviationsSetSize),
187 SourceIdMap(DIEValueAllocator), PrevLabel(NULL), GlobalCUIndexCount(0),
188 InfoHolder(A, &AbbreviationsSet, Abbreviations, "info_string",
190 SkeletonAbbrevSet(InitAbbreviationsSetSize),
191 SkeletonHolder(A, &SkeletonAbbrevSet, SkeletonAbbrevs, "skel_string",
194 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
195 DwarfStrSectionSym = TextSectionSym = 0;
196 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
197 DwarfAddrSectionSym = 0;
198 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
199 FunctionBeginSym = FunctionEndSym = 0;
201 // Turn on accelerator tables for Darwin by default, pubnames by
202 // default for non-Darwin, and handle split dwarf.
203 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
205 if (DwarfAccelTables == Default)
206 HasDwarfAccelTables = IsDarwin;
208 HasDwarfAccelTables = DwarfAccelTables == Enable;
210 if (SplitDwarf == Default)
211 HasSplitDwarf = false;
213 HasSplitDwarf = SplitDwarf == Enable;
215 if (DwarfPubSections == Default)
216 HasDwarfPubSections = !IsDarwin;
218 HasDwarfPubSections = DwarfPubSections == Enable;
220 DwarfVersion = DwarfVersionNumber
222 : getDwarfVersionFromModule(MMI->getModule());
225 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
230 // Switch to the specified MCSection and emit an assembler
231 // temporary label to it if SymbolStem is specified.
232 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
233 const char *SymbolStem = 0) {
234 Asm->OutStreamer.SwitchSection(Section);
238 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
239 Asm->OutStreamer.EmitLabel(TmpSym);
243 DwarfUnits::~DwarfUnits() {
244 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
249 MCSymbol *DwarfUnits::getStringPoolSym() {
250 return Asm->GetTempSymbol(StringPref);
253 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
254 std::pair<MCSymbol *, unsigned> &Entry =
255 StringPool.GetOrCreateValue(Str).getValue();
259 Entry.second = NextStringPoolNumber++;
260 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
263 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
264 std::pair<MCSymbol *, unsigned> &Entry =
265 StringPool.GetOrCreateValue(Str).getValue();
269 Entry.second = NextStringPoolNumber++;
270 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
274 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
275 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
278 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
279 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
280 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
282 ++NextAddrPoolNumber;
283 return P.first->second;
286 // Define a unique number for the abbreviation.
288 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
289 // Check the set for priors.
290 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
292 // If it's newly added.
293 if (InSet == &Abbrev) {
294 // Add to abbreviation list.
295 Abbreviations.push_back(&Abbrev);
297 // Assign the vector position + 1 as its number.
298 Abbrev.setNumber(Abbreviations.size());
300 // Assign existing abbreviation number.
301 Abbrev.setNumber(InSet->getNumber());
305 static bool isObjCClass(StringRef Name) {
306 return Name.startswith("+") || Name.startswith("-");
309 static bool hasObjCCategory(StringRef Name) {
310 if (!isObjCClass(Name))
313 return Name.find(") ") != StringRef::npos;
316 static void getObjCClassCategory(StringRef In, StringRef &Class,
317 StringRef &Category) {
318 if (!hasObjCCategory(In)) {
319 Class = In.slice(In.find('[') + 1, In.find(' '));
324 Class = In.slice(In.find('[') + 1, In.find('('));
325 Category = In.slice(In.find('[') + 1, In.find(' '));
329 static StringRef getObjCMethodName(StringRef In) {
330 return In.slice(In.find(' ') + 1, In.find(']'));
333 // Helper for sorting sections into a stable output order.
334 static bool SectionSort(const MCSection *A, const MCSection *B) {
335 std::string LA = (A ? A->getLabelBeginName() : "");
336 std::string LB = (B ? B->getLabelBeginName() : "");
340 // Add the various names to the Dwarf accelerator table names.
341 // TODO: Determine whether or not we should add names for programs
342 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
343 // is only slightly different than the lookup of non-standard ObjC names.
344 static void addSubprogramNames(Unit *TheU, DISubprogram SP, DIE *Die) {
345 if (!SP.isDefinition())
347 TheU->addAccelName(SP.getName(), Die);
349 // If the linkage name is different than the name, go ahead and output
350 // that as well into the name table.
351 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
352 TheU->addAccelName(SP.getLinkageName(), Die);
354 // If this is an Objective-C selector name add it to the ObjC accelerator
356 if (isObjCClass(SP.getName())) {
357 StringRef Class, Category;
358 getObjCClassCategory(SP.getName(), Class, Category);
359 TheU->addAccelObjC(Class, Die);
361 TheU->addAccelObjC(Category, Die);
362 // Also add the base method name to the name table.
363 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
367 /// isSubprogramContext - Return true if Context is either a subprogram
368 /// or another context nested inside a subprogram.
369 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
372 DIDescriptor D(Context);
373 if (D.isSubprogram())
376 return isSubprogramContext(resolve(DIType(Context).getContext()));
380 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
381 // and DW_AT_high_pc attributes. If there are global variables in this
382 // scope then create and insert DIEs for these variables.
383 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, DISubprogram SP) {
384 DIE *SPDie = SPCU->getDIE(SP);
386 assert(SPDie && "Unable to find subprogram DIE!");
388 // If we're updating an abstract DIE, then we will be adding the children and
389 // object pointer later on. But what we don't want to do is process the
390 // concrete DIE twice.
391 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
392 // Pick up abstract subprogram DIE.
394 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
395 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
397 DISubprogram SPDecl = SP.getFunctionDeclaration();
398 if (!SPDecl.isSubprogram()) {
399 // There is not any need to generate specification DIE for a function
400 // defined at compile unit level. If a function is defined inside another
401 // function then gdb prefers the definition at top level and but does not
402 // expect specification DIE in parent function. So avoid creating
403 // specification DIE for a function defined inside a function.
404 DIScope SPContext = resolve(SP.getContext());
405 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
406 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
407 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
410 DICompositeType SPTy = SP.getType();
411 DIArray Args = SPTy.getTypeArray();
412 uint16_t SPTag = SPTy.getTag();
413 if (SPTag == dwarf::DW_TAG_subroutine_type)
414 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
416 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
417 DIType ATy(Args.getElement(i));
418 SPCU->addType(Arg, ATy);
419 if (ATy.isArtificial())
420 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
421 if (ATy.isObjectPointer())
422 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
424 DIE *SPDeclDie = SPDie;
425 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
426 *SPCU->getUnitDie());
427 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
432 SPCU->addLabelAddress(
433 SPDie, dwarf::DW_AT_low_pc,
434 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
435 SPCU->addLabelAddress(
436 SPDie, dwarf::DW_AT_high_pc,
437 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
438 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
439 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
440 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
442 // Add name to the name table, we do this here because we're guaranteed
443 // to have concrete versions of our DW_TAG_subprogram nodes.
444 addSubprogramNames(SPCU, SP, SPDie);
449 /// Check whether we should create a DIE for the given Scope, return true
450 /// if we don't create a DIE (the corresponding DIE is null).
451 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
452 if (Scope->isAbstractScope())
455 // We don't create a DIE if there is no Range.
456 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
460 if (Ranges.size() > 1)
463 // We don't create a DIE if we have a single Range and the end label
465 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
466 MCSymbol *End = getLabelAfterInsn(RI->second);
470 // Construct new DW_TAG_lexical_block for this scope and attach
471 // DW_AT_low_pc/DW_AT_high_pc labels.
472 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
473 LexicalScope *Scope) {
474 if (isLexicalScopeDIENull(Scope))
477 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
478 if (Scope->isAbstractScope())
481 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
482 // If we have multiple ranges, emit them into the range section.
483 if (Ranges.size() > 1) {
484 // .debug_range section has not been laid out yet. Emit offset in
485 // .debug_range as a relocatable label. emitDIE will handle
486 // emitting it appropriately.
487 unsigned Offset = DebugRangeSymbols.size();
488 TheCU->addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges,
489 Asm->GetTempSymbol("debug_ranges", Offset));
490 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
493 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
494 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
497 // Terminate the range list.
498 DebugRangeSymbols.push_back(NULL);
499 DebugRangeSymbols.push_back(NULL);
503 // Construct the address range for this DIE.
504 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
505 MCSymbol *Start = getLabelBeforeInsn(RI->first);
506 MCSymbol *End = getLabelAfterInsn(RI->second);
507 assert(End && "End label should not be null!");
509 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
510 assert(End->isDefined() && "Invalid end label for an inlined scope!");
512 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
513 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
518 // This scope represents inlined body of a function. Construct DIE to
519 // represent this concrete inlined copy of the function.
520 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
521 LexicalScope *Scope) {
522 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
523 assert(Ranges.empty() == false &&
524 "LexicalScope does not have instruction markers!");
526 if (!Scope->getScopeNode())
528 DIScope DS(Scope->getScopeNode());
529 DISubprogram InlinedSP = getDISubprogram(DS);
530 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
532 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
536 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
537 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
539 if (Ranges.size() > 1) {
540 // .debug_range section has not been laid out yet. Emit offset in
541 // .debug_range as a relocatable label. emitDIE will handle
542 // emitting it appropriately.
543 unsigned Offset = DebugRangeSymbols.size();
544 TheCU->addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges,
545 Asm->GetTempSymbol("debug_ranges", Offset));
546 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
549 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
550 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
552 DebugRangeSymbols.push_back(NULL);
553 DebugRangeSymbols.push_back(NULL);
555 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
556 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
557 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
559 if (StartLabel == 0 || EndLabel == 0)
560 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
562 assert(StartLabel->isDefined() &&
563 "Invalid starting label for an inlined scope!");
564 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
566 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
567 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
570 InlinedSubprogramDIEs.insert(OriginDIE);
572 // Add the call site information to the DIE.
573 DILocation DL(Scope->getInlinedAt());
574 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
575 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
576 TheCU->getUniqueID()));
577 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
579 // Add name to the name table, we do this here because we're guaranteed
580 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
581 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
586 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
587 SmallVectorImpl<DIE *> &Children) {
588 DIE *ObjectPointer = NULL;
590 // Collect arguments for current function.
591 if (LScopes.isCurrentFunctionScope(Scope))
592 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
593 if (DbgVariable *ArgDV = CurrentFnArguments[i])
595 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
596 Children.push_back(Arg);
597 if (ArgDV->isObjectPointer())
601 // Collect lexical scope children first.
602 const SmallVectorImpl<DbgVariable *> &Variables =
603 ScopeVariables.lookup(Scope);
604 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
605 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
606 Scope->isAbstractScope())) {
607 Children.push_back(Variable);
608 if (Variables[i]->isObjectPointer())
609 ObjectPointer = Variable;
611 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
612 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
613 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
614 Children.push_back(Nested);
615 return ObjectPointer;
618 // Construct a DIE for this scope.
619 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
620 if (!Scope || !Scope->getScopeNode())
623 DIScope DS(Scope->getScopeNode());
625 SmallVector<DIE *, 8> Children;
626 DIE *ObjectPointer = NULL;
627 bool ChildrenCreated = false;
629 // We try to create the scope DIE first, then the children DIEs. This will
630 // avoid creating un-used children then removing them later when we find out
631 // the scope DIE is null.
632 DIE *ScopeDIE = NULL;
633 if (Scope->getInlinedAt())
634 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
635 else if (DS.isSubprogram()) {
636 ProcessedSPNodes.insert(DS);
637 if (Scope->isAbstractScope()) {
638 ScopeDIE = TheCU->getDIE(DS);
639 // Note down abstract DIE.
641 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
643 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
645 // Early exit when we know the scope DIE is going to be null.
646 if (isLexicalScopeDIENull(Scope))
649 // We create children here when we know the scope DIE is not going to be
650 // null and the children will be added to the scope DIE.
651 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
652 ChildrenCreated = true;
654 // There is no need to emit empty lexical block DIE.
655 std::pair<ImportedEntityMap::const_iterator,
656 ImportedEntityMap::const_iterator> Range =
658 ScopesWithImportedEntities.begin(),
659 ScopesWithImportedEntities.end(),
660 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
662 if (Children.empty() && Range.first == Range.second)
664 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
665 assert(ScopeDIE && "Scope DIE should not be null.");
666 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
668 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
672 assert(Children.empty() &&
673 "We create children only when the scope DIE is not null.");
676 if (!ChildrenCreated)
677 // We create children when the scope DIE is not null.
678 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
681 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
684 ScopeDIE->addChild(*I);
686 if (DS.isSubprogram() && ObjectPointer != NULL)
687 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
692 // Look up the source id with the given directory and source file names.
693 // If none currently exists, create a new id and insert it in the
694 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
696 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
698 // If we use .loc in assembly, we can't separate .file entries according to
699 // compile units. Thus all files will belong to the default compile unit.
701 // FIXME: add a better feature test than hasRawTextSupport. Even better,
702 // extend .file to support this.
703 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
706 // If FE did not provide a file name, then assume stdin.
707 if (FileName.empty())
708 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
710 // TODO: this might not belong here. See if we can factor this better.
711 if (DirName == CompilationDir)
714 // FileIDCUMap stores the current ID for the given compile unit.
715 unsigned SrcId = FileIDCUMap[CUID] + 1;
717 // We look up the CUID/file/dir by concatenating them with a zero byte.
718 SmallString<128> NamePair;
719 NamePair += utostr(CUID);
722 NamePair += '\0'; // Zero bytes are not allowed in paths.
723 NamePair += FileName;
725 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
726 if (Ent.getValue() != SrcId)
727 return Ent.getValue();
729 FileIDCUMap[CUID] = SrcId;
730 // Print out a .file directive to specify files for .loc directives.
731 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
736 // Create new CompileUnit for the given metadata node with tag
737 // DW_TAG_compile_unit.
738 CompileUnit *DwarfDebug::constructCompileUnit(DICompileUnit DIUnit) {
739 StringRef FN = DIUnit.getFilename();
740 CompilationDir = DIUnit.getDirectory();
742 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
743 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++, Die, DIUnit, Asm,
746 FileIDCUMap[NewCU->getUniqueID()] = 0;
747 // Call this to emit a .file directive if it wasn't emitted for the source
748 // file this CU comes from yet.
749 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
751 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
752 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
753 DIUnit.getLanguage());
754 NewCU->addString(Die, dwarf::DW_AT_name, FN);
756 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
757 // into an entity. We're using 0 (or a NULL label) for this. For
758 // split dwarf it's in the skeleton CU so omit it here.
759 if (!useSplitDwarf())
760 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
762 // Define start line table label for each Compile Unit.
763 MCSymbol *LineTableStartSym =
764 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
765 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
766 NewCU->getUniqueID());
768 // Use a single line table if we are using .loc and generating assembly.
770 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
771 (NewCU->getUniqueID() == 0);
773 if (!useSplitDwarf()) {
774 // DW_AT_stmt_list is a offset of line number information for this
775 // compile unit in debug_line section. For split dwarf this is
776 // left in the skeleton CU and so not included.
777 // The line table entries are not always emitted in assembly, so it
778 // is not okay to use line_table_start here.
779 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
780 NewCU->addSectionLabel(
781 Die, dwarf::DW_AT_stmt_list,
782 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
783 : LineTableStartSym);
784 else if (UseTheFirstCU)
785 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
787 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list,
788 LineTableStartSym, DwarfLineSectionSym);
790 // If we're using split dwarf the compilation dir is going to be in the
791 // skeleton CU and so we don't need to duplicate it here.
792 if (!CompilationDir.empty())
793 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
795 // Flags to let the linker know we have emitted new style pubnames. Only
796 // emit it here if we don't have a skeleton CU for split dwarf.
797 if (GenerateGnuPubSections) {
798 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
799 NewCU->addSectionLabel(
800 Die, dwarf::DW_AT_GNU_pubnames,
801 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
803 NewCU->addSectionDelta(
804 Die, dwarf::DW_AT_GNU_pubnames,
805 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
806 DwarfGnuPubNamesSectionSym);
808 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
809 NewCU->addSectionLabel(
810 Die, dwarf::DW_AT_GNU_pubtypes,
811 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
813 NewCU->addSectionDelta(
814 Die, dwarf::DW_AT_GNU_pubtypes,
815 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
816 DwarfGnuPubTypesSectionSym);
820 if (DIUnit.isOptimized())
821 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
823 StringRef Flags = DIUnit.getFlags();
825 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
827 if (unsigned RVer = DIUnit.getRunTimeVersion())
828 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
829 dwarf::DW_FORM_data1, RVer);
834 InfoHolder.addUnit(NewCU);
836 CUMap.insert(std::make_pair(DIUnit, NewCU));
837 CUDieMap.insert(std::make_pair(Die, NewCU));
841 // Construct subprogram DIE.
842 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
843 // FIXME: We should only call this routine once, however, during LTO if a
844 // program is defined in multiple CUs we could end up calling it out of
845 // beginModule as we walk the CUs.
847 CompileUnit *&CURef = SPMap[N];
853 if (!SP.isDefinition())
854 // This is a method declaration which will be handled while constructing
858 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
860 // Expose as a global name.
861 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
864 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
866 DIImportedEntity Module(N);
867 if (!Module.Verify())
869 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
870 constructImportedEntityDIE(TheCU, Module, D);
873 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
875 DIImportedEntity Module(N);
876 if (!Module.Verify())
878 return constructImportedEntityDIE(TheCU, Module, Context);
881 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
882 const DIImportedEntity &Module,
884 assert(Module.Verify() &&
885 "Use one of the MDNode * overloads to handle invalid metadata");
886 assert(Context && "Should always have a context for an imported_module");
887 DIE *IMDie = new DIE(Module.getTag());
888 TheCU->insertDIE(Module, IMDie);
890 DIDescriptor Entity = Module.getEntity();
891 if (Entity.isNameSpace())
892 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
893 else if (Entity.isSubprogram())
894 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
895 else if (Entity.isType())
896 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
898 EntityDie = TheCU->getDIE(Entity);
899 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
900 Module.getContext().getDirectory(),
901 TheCU->getUniqueID());
902 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
903 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
904 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
905 StringRef Name = Module.getName();
907 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
908 Context->addChild(IMDie);
911 // Emit all Dwarf sections that should come prior to the content. Create
912 // global DIEs and emit initial debug info sections. This is invoked by
913 // the target AsmPrinter.
914 void DwarfDebug::beginModule() {
915 if (DisableDebugInfoPrinting)
918 const Module *M = MMI->getModule();
920 // If module has named metadata anchors then use them, otherwise scan the
921 // module using debug info finder to collect debug info.
922 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
925 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
927 // Emit initial sections so we can reference labels later.
930 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
931 DICompileUnit CUNode(CU_Nodes->getOperand(i));
932 CompileUnit *CU = constructCompileUnit(CUNode);
933 DIArray ImportedEntities = CUNode.getImportedEntities();
934 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
935 ScopesWithImportedEntities.push_back(std::make_pair(
936 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
937 ImportedEntities.getElement(i)));
938 std::sort(ScopesWithImportedEntities.begin(),
939 ScopesWithImportedEntities.end(), less_first());
940 DIArray GVs = CUNode.getGlobalVariables();
941 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
942 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
943 DIArray SPs = CUNode.getSubprograms();
944 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
945 constructSubprogramDIE(CU, SPs.getElement(i));
946 DIArray EnumTypes = CUNode.getEnumTypes();
947 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
948 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
949 DIArray RetainedTypes = CUNode.getRetainedTypes();
950 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
951 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
952 // Emit imported_modules last so that the relevant context is already
954 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
955 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
958 // Tell MMI that we have debug info.
959 MMI->setDebugInfoAvailability(true);
961 // Prime section data.
962 SectionMap[Asm->getObjFileLowering().getTextSection()];
965 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
966 void DwarfDebug::computeInlinedDIEs() {
967 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
968 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
969 AE = InlinedSubprogramDIEs.end();
972 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
974 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
975 AE = AbstractSPDies.end();
977 DIE *ISP = AI->second;
978 if (InlinedSubprogramDIEs.count(ISP))
980 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
984 // Collect info for variables that were optimized out.
985 void DwarfDebug::collectDeadVariables() {
986 const Module *M = MMI->getModule();
988 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
989 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
990 DICompileUnit TheCU(CU_Nodes->getOperand(i));
991 DIArray Subprograms = TheCU.getSubprograms();
992 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
993 DISubprogram SP(Subprograms.getElement(i));
994 if (ProcessedSPNodes.count(SP) != 0)
996 if (!SP.isSubprogram())
998 if (!SP.isDefinition())
1000 DIArray Variables = SP.getVariables();
1001 if (Variables.getNumElements() == 0)
1004 // Construct subprogram DIE and add variables DIEs.
1005 CompileUnit *SPCU = static_cast<CompileUnit *>(CUMap.lookup(TheCU));
1006 assert(SPCU && "Unable to find Compile Unit!");
1007 // FIXME: See the comment in constructSubprogramDIE about duplicate
1009 constructSubprogramDIE(SPCU, SP);
1010 DIE *SPDIE = SPCU->getDIE(SP);
1011 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1012 DIVariable DV(Variables.getElement(vi));
1013 if (!DV.isVariable())
1015 DbgVariable NewVar(DV, NULL, this);
1016 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1017 SPDIE->addChild(VariableDIE);
1024 // Type Signature [7.27] and ODR Hash code.
1026 /// \brief Grabs the string in whichever attribute is passed in and returns
1027 /// a reference to it. Returns "" if the attribute doesn't exist.
1028 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1029 DIEValue *V = Die->findAttribute(Attr);
1031 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1032 return S->getString();
1034 return StringRef("");
1037 /// Return true if the current DIE is contained within an anonymous namespace.
1038 static bool isContainedInAnonNamespace(DIE *Die) {
1039 DIE *Parent = Die->getParent();
1042 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1043 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1045 Parent = Parent->getParent();
1051 /// Test if the current CU language is C++ and that we have
1052 /// a named type that is not contained in an anonymous namespace.
1053 static bool shouldAddODRHash(TypeUnit *CU, DIE *Die) {
1054 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1055 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1056 !isContainedInAnonNamespace(Die);
1059 void DwarfDebug::finalizeModuleInfo() {
1060 // Collect info for variables that were optimized out.
1061 collectDeadVariables();
1063 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1064 computeInlinedDIEs();
1066 // Handle anything that needs to be done on a per-cu basis.
1067 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
1068 E = getUnits().end();
1071 // Emit DW_AT_containing_type attribute to connect types with their
1072 // vtable holding type.
1073 TheU->constructContainingTypeDIEs();
1075 // If we're splitting the dwarf out now that we've got the entire
1076 // CU then construct a skeleton CU based upon it.
1077 if (useSplitDwarf() &&
1078 TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1080 if (GenerateCUHash) {
1082 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1084 // This should be a unique identifier when we want to build .dwp files.
1085 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1086 dwarf::DW_FORM_data8, ID);
1087 // Now construct the skeleton CU associated.
1088 CompileUnit *SkCU = constructSkeletonCU(static_cast<CompileUnit *>(TheU));
1089 // This should be a unique identifier when we want to build .dwp files.
1090 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1091 dwarf::DW_FORM_data8, ID);
1095 // Compute DIE offsets and sizes.
1096 InfoHolder.computeSizeAndOffsets();
1097 if (useSplitDwarf())
1098 SkeletonHolder.computeSizeAndOffsets();
1101 void DwarfDebug::endSections() {
1102 // Filter labels by section.
1103 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1104 const SymbolCU &SCU = ArangeLabels[n];
1105 if (SCU.Sym->isInSection()) {
1106 // Make a note of this symbol and it's section.
1107 const MCSection *Section = &SCU.Sym->getSection();
1108 if (!Section->getKind().isMetadata())
1109 SectionMap[Section].push_back(SCU);
1111 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1112 // appear in the output. This sucks as we rely on sections to build
1113 // arange spans. We can do it without, but it's icky.
1114 SectionMap[NULL].push_back(SCU);
1118 // Build a list of sections used.
1119 std::vector<const MCSection *> Sections;
1120 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1122 const MCSection *Section = it->first;
1123 Sections.push_back(Section);
1126 // Sort the sections into order.
1127 // This is only done to ensure consistent output order across different runs.
1128 std::sort(Sections.begin(), Sections.end(), SectionSort);
1130 // Add terminating symbols for each section.
1131 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1132 const MCSection *Section = Sections[ID];
1133 MCSymbol *Sym = NULL;
1136 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1137 // if we know the section name up-front. For user-created sections, the
1139 // label may not be valid to use as a label. (section names can use a
1141 // set of characters on some systems)
1142 Sym = Asm->GetTempSymbol("debug_end", ID);
1143 Asm->OutStreamer.SwitchSection(Section);
1144 Asm->OutStreamer.EmitLabel(Sym);
1147 // Insert a final terminator.
1148 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1152 // Emit all Dwarf sections that should come after the content.
1153 void DwarfDebug::endModule() {
1158 // End any existing sections.
1159 // TODO: Does this need to happen?
1162 // Finalize the debug info for the module.
1163 finalizeModuleInfo();
1167 // Emit all the DIEs into a debug info section.
1170 // Corresponding abbreviations into a abbrev section.
1171 emitAbbreviations();
1173 // Emit info into a debug loc section.
1176 // Emit info into a debug aranges section.
1179 // Emit info into a debug ranges section.
1182 // Emit info into a debug macinfo section.
1185 if (useSplitDwarf()) {
1188 emitDebugAbbrevDWO();
1189 // Emit DWO addresses.
1190 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1193 // Emit info into the dwarf accelerator table sections.
1194 if (useDwarfAccelTables()) {
1197 emitAccelNamespaces();
1201 // Emit the pubnames and pubtypes sections if requested.
1202 if (HasDwarfPubSections) {
1203 emitDebugPubNames(GenerateGnuPubSections);
1204 emitDebugPubTypes(GenerateGnuPubSections);
1210 // Reset these for the next Module if we have one.
1214 // Find abstract variable, if any, associated with Var.
1215 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1216 DebugLoc ScopeLoc) {
1217 LLVMContext &Ctx = DV->getContext();
1218 // More then one inlined variable corresponds to one abstract variable.
1219 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1220 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1222 return AbsDbgVariable;
1224 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1228 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1229 addScopeVariable(Scope, AbsDbgVariable);
1230 AbstractVariables[Var] = AbsDbgVariable;
1231 return AbsDbgVariable;
1234 // If Var is a current function argument then add it to CurrentFnArguments list.
1235 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1236 DbgVariable *Var, LexicalScope *Scope) {
1237 if (!LScopes.isCurrentFunctionScope(Scope))
1239 DIVariable DV = Var->getVariable();
1240 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1242 unsigned ArgNo = DV.getArgNumber();
1246 size_t Size = CurrentFnArguments.size();
1248 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1249 // llvm::Function argument size is not good indicator of how many
1250 // arguments does the function have at source level.
1252 CurrentFnArguments.resize(ArgNo * 2);
1253 CurrentFnArguments[ArgNo - 1] = Var;
1257 // Collect variable information from side table maintained by MMI.
1258 void DwarfDebug::collectVariableInfoFromMMITable(
1259 const MachineFunction *MF, SmallPtrSet<const MDNode *, 16> &Processed) {
1260 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1261 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1264 const MDNode *Var = VI->first;
1267 Processed.insert(Var);
1269 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1271 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1273 // If variable scope is not found then skip this variable.
1277 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1278 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1279 RegVar->setFrameIndex(VP.first);
1280 if (!addCurrentFnArgument(MF, RegVar, Scope))
1281 addScopeVariable(Scope, RegVar);
1283 AbsDbgVariable->setFrameIndex(VP.first);
1287 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1289 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1290 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1291 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1292 MI->getOperand(0).getReg() &&
1293 (MI->getOperand(1).isImm() ||
1294 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1297 // Get .debug_loc entry for the instruction range starting at MI.
1298 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1299 const MCSymbol *FLabel,
1300 const MCSymbol *SLabel,
1301 const MachineInstr *MI) {
1302 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1304 assert(MI->getNumOperands() == 3);
1305 if (MI->getOperand(0).isReg()) {
1306 MachineLocation MLoc;
1307 // If the second operand is an immediate, this is a
1308 // register-indirect address.
1309 if (!MI->getOperand(1).isImm())
1310 MLoc.set(MI->getOperand(0).getReg());
1312 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1313 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1315 if (MI->getOperand(0).isImm())
1316 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1317 if (MI->getOperand(0).isFPImm())
1318 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1319 if (MI->getOperand(0).isCImm())
1320 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1322 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1325 // Find variables for each lexical scope.
1327 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1328 SmallPtrSet<const MDNode *, 16> &Processed) {
1330 // Grab the variable info that was squirreled away in the MMI side-table.
1331 collectVariableInfoFromMMITable(MF, Processed);
1333 for (SmallVectorImpl<const MDNode *>::const_iterator
1334 UVI = UserVariables.begin(),
1335 UVE = UserVariables.end();
1336 UVI != UVE; ++UVI) {
1337 const MDNode *Var = *UVI;
1338 if (Processed.count(Var))
1341 // History contains relevant DBG_VALUE instructions for Var and instructions
1343 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1344 if (History.empty())
1346 const MachineInstr *MInsn = History.front();
1349 LexicalScope *Scope = NULL;
1350 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1351 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1352 Scope = LScopes.getCurrentFunctionScope();
1353 else if (MDNode *IA = DV.getInlinedAt())
1354 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1356 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1357 // If variable scope is not found then skip this variable.
1361 Processed.insert(DV);
1362 assert(MInsn->isDebugValue() && "History must begin with debug value");
1363 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1364 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1365 if (!addCurrentFnArgument(MF, RegVar, Scope))
1366 addScopeVariable(Scope, RegVar);
1368 AbsVar->setMInsn(MInsn);
1370 // Simplify ranges that are fully coalesced.
1371 if (History.size() <= 1 ||
1372 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1373 RegVar->setMInsn(MInsn);
1377 // Handle multiple DBG_VALUE instructions describing one variable.
1378 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1380 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1381 HI = History.begin(),
1384 const MachineInstr *Begin = *HI;
1385 assert(Begin->isDebugValue() && "Invalid History entry");
1387 // Check if DBG_VALUE is truncating a range.
1388 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1389 !Begin->getOperand(0).getReg())
1392 // Compute the range for a register location.
1393 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1394 const MCSymbol *SLabel = 0;
1397 // If Begin is the last instruction in History then its value is valid
1398 // until the end of the function.
1399 SLabel = FunctionEndSym;
1401 const MachineInstr *End = HI[1];
1402 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1403 << "\t" << *Begin << "\t" << *End << "\n");
1404 if (End->isDebugValue())
1405 SLabel = getLabelBeforeInsn(End);
1407 // End is a normal instruction clobbering the range.
1408 SLabel = getLabelAfterInsn(End);
1409 assert(SLabel && "Forgot label after clobber instruction");
1414 // The value is valid until the next DBG_VALUE or clobber.
1415 DotDebugLocEntries.push_back(
1416 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1418 DotDebugLocEntries.push_back(DotDebugLocEntry());
1421 // Collect info for variables that were optimized out.
1422 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1423 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1424 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1425 DIVariable DV(Variables.getElement(i));
1426 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1428 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1429 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1433 // Return Label preceding the instruction.
1434 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1435 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1436 assert(Label && "Didn't insert label before instruction");
1440 // Return Label immediately following the instruction.
1441 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1442 return LabelsAfterInsn.lookup(MI);
1445 // Process beginning of an instruction.
1446 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1447 // Check if source location changes, but ignore DBG_VALUE locations.
1448 if (!MI->isDebugValue()) {
1449 DebugLoc DL = MI->getDebugLoc();
1450 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1453 if (DL == PrologEndLoc) {
1454 Flags |= DWARF2_FLAG_PROLOGUE_END;
1455 PrologEndLoc = DebugLoc();
1457 if (PrologEndLoc.isUnknown())
1458 Flags |= DWARF2_FLAG_IS_STMT;
1460 if (!DL.isUnknown()) {
1461 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1462 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1464 recordSourceLine(0, 0, 0, 0);
1468 // Insert labels where requested.
1469 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1470 LabelsBeforeInsn.find(MI);
1473 if (I == LabelsBeforeInsn.end())
1476 // Label already assigned.
1481 PrevLabel = MMI->getContext().CreateTempSymbol();
1482 Asm->OutStreamer.EmitLabel(PrevLabel);
1484 I->second = PrevLabel;
1487 // Process end of an instruction.
1488 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1489 // Don't create a new label after DBG_VALUE instructions.
1490 // They don't generate code.
1491 if (!MI->isDebugValue())
1494 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1495 LabelsAfterInsn.find(MI);
1498 if (I == LabelsAfterInsn.end())
1501 // Label already assigned.
1505 // We need a label after this instruction.
1507 PrevLabel = MMI->getContext().CreateTempSymbol();
1508 Asm->OutStreamer.EmitLabel(PrevLabel);
1510 I->second = PrevLabel;
1513 // Each LexicalScope has first instruction and last instruction to mark
1514 // beginning and end of a scope respectively. Create an inverse map that list
1515 // scopes starts (and ends) with an instruction. One instruction may start (or
1516 // end) multiple scopes. Ignore scopes that are not reachable.
1517 void DwarfDebug::identifyScopeMarkers() {
1518 SmallVector<LexicalScope *, 4> WorkList;
1519 WorkList.push_back(LScopes.getCurrentFunctionScope());
1520 while (!WorkList.empty()) {
1521 LexicalScope *S = WorkList.pop_back_val();
1523 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1524 if (!Children.empty())
1525 for (SmallVectorImpl<LexicalScope *>::const_iterator
1526 SI = Children.begin(),
1527 SE = Children.end();
1529 WorkList.push_back(*SI);
1531 if (S->isAbstractScope())
1534 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1537 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1540 assert(RI->first && "InsnRange does not have first instruction!");
1541 assert(RI->second && "InsnRange does not have second instruction!");
1542 requestLabelBeforeInsn(RI->first);
1543 requestLabelAfterInsn(RI->second);
1548 // Get MDNode for DebugLoc's scope.
1549 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1550 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1551 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1552 return DL.getScope(Ctx);
1555 // Walk up the scope chain of given debug loc and find line number info
1556 // for the function.
1557 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1558 const MDNode *Scope = getScopeNode(DL, Ctx);
1559 DISubprogram SP = getDISubprogram(Scope);
1560 if (SP.isSubprogram()) {
1561 // Check for number of operands since the compatibility is
1563 if (SP->getNumOperands() > 19)
1564 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1566 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1572 // Gather pre-function debug information. Assumes being called immediately
1573 // after the function entry point has been emitted.
1574 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1576 // If there's no debug info for the function we're not going to do anything.
1577 if (!MMI->hasDebugInfo())
1580 // Grab the lexical scopes for the function, if we don't have any of those
1581 // then we're not going to be able to do anything.
1582 LScopes.initialize(*MF);
1583 if (LScopes.empty())
1586 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1588 // Make sure that each lexical scope will have a begin/end label.
1589 identifyScopeMarkers();
1591 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1592 // belongs to so that we add to the correct per-cu line table in the
1594 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1595 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1596 assert(TheCU && "Unable to find compile unit!");
1597 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1598 // Use a single line table if we are using .loc and generating assembly.
1599 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1601 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1603 // Emit a label for the function so that we have a beginning address.
1604 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1605 // Assumes in correct section after the entry point.
1606 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1608 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1609 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1610 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1612 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1614 bool AtBlockEntry = true;
1615 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1617 const MachineInstr *MI = II;
1619 if (MI->isDebugValue()) {
1620 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1622 // Keep track of user variables.
1624 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1626 // Variable is in a register, we need to check for clobbers.
1627 if (isDbgValueInDefinedReg(MI))
1628 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1630 // Check the history of this variable.
1631 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1632 if (History.empty()) {
1633 UserVariables.push_back(Var);
1634 // The first mention of a function argument gets the FunctionBeginSym
1635 // label, so arguments are visible when breaking at function entry.
1637 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1638 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1639 LabelsBeforeInsn[MI] = FunctionBeginSym;
1641 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1642 const MachineInstr *Prev = History.back();
1643 if (Prev->isDebugValue()) {
1644 // Coalesce identical entries at the end of History.
1645 if (History.size() >= 2 &&
1646 Prev->isIdenticalTo(History[History.size() - 2])) {
1647 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1648 << "\t" << *Prev << "\t"
1649 << *History[History.size() - 2] << "\n");
1653 // Terminate old register assignments that don't reach MI;
1654 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1655 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1656 isDbgValueInDefinedReg(Prev)) {
1657 // Previous register assignment needs to terminate at the end of
1659 MachineBasicBlock::const_iterator LastMI =
1660 PrevMBB->getLastNonDebugInstr();
1661 if (LastMI == PrevMBB->end()) {
1662 // Drop DBG_VALUE for empty range.
1663 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1664 << "\t" << *Prev << "\n");
1666 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1667 // Terminate after LastMI.
1668 History.push_back(LastMI);
1672 History.push_back(MI);
1674 // Not a DBG_VALUE instruction.
1676 AtBlockEntry = false;
1678 // First known non-DBG_VALUE and non-frame setup location marks
1679 // the beginning of the function body.
1680 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1681 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1682 PrologEndLoc = MI->getDebugLoc();
1684 // Check if the instruction clobbers any registers with debug vars.
1685 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1686 MOE = MI->operands_end();
1687 MOI != MOE; ++MOI) {
1688 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1690 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1693 const MDNode *Var = LiveUserVar[Reg];
1696 // Reg is now clobbered.
1697 LiveUserVar[Reg] = 0;
1699 // Was MD last defined by a DBG_VALUE referring to Reg?
1700 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1701 if (HistI == DbgValues.end())
1703 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1704 if (History.empty())
1706 const MachineInstr *Prev = History.back();
1707 // Sanity-check: Register assignments are terminated at the end of
1709 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1711 // Is the variable still in Reg?
1712 if (!isDbgValueInDefinedReg(Prev) ||
1713 Prev->getOperand(0).getReg() != Reg)
1715 // Var is clobbered. Make sure the next instruction gets a label.
1716 History.push_back(MI);
1723 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1725 SmallVectorImpl<const MachineInstr *> &History = I->second;
1726 if (History.empty())
1729 // Make sure the final register assignments are terminated.
1730 const MachineInstr *Prev = History.back();
1731 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1732 const MachineBasicBlock *PrevMBB = Prev->getParent();
1733 MachineBasicBlock::const_iterator LastMI =
1734 PrevMBB->getLastNonDebugInstr();
1735 if (LastMI == PrevMBB->end())
1736 // Drop DBG_VALUE for empty range.
1738 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1739 // Terminate after LastMI.
1740 History.push_back(LastMI);
1743 // Request labels for the full history.
1744 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1745 const MachineInstr *MI = History[i];
1746 if (MI->isDebugValue())
1747 requestLabelBeforeInsn(MI);
1749 requestLabelAfterInsn(MI);
1753 PrevInstLoc = DebugLoc();
1754 PrevLabel = FunctionBeginSym;
1756 // Record beginning of function.
1757 if (!PrologEndLoc.isUnknown()) {
1758 DebugLoc FnStartDL =
1759 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1761 FnStartDL.getLine(), FnStartDL.getCol(),
1762 FnStartDL.getScope(MF->getFunction()->getContext()),
1763 // We'd like to list the prologue as "not statements" but GDB behaves
1764 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1765 DWARF2_FLAG_IS_STMT);
1769 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1770 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1771 DIVariable DV = Var->getVariable();
1772 // Variables with positive arg numbers are parameters.
1773 if (unsigned ArgNum = DV.getArgNumber()) {
1774 // Keep all parameters in order at the start of the variable list to ensure
1775 // function types are correct (no out-of-order parameters)
1777 // This could be improved by only doing it for optimized builds (unoptimized
1778 // builds have the right order to begin with), searching from the back (this
1779 // would catch the unoptimized case quickly), or doing a binary search
1780 // rather than linear search.
1781 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1782 while (I != Vars.end()) {
1783 unsigned CurNum = (*I)->getVariable().getArgNumber();
1784 // A local (non-parameter) variable has been found, insert immediately
1788 // A later indexed parameter has been found, insert immediately before it.
1789 if (CurNum > ArgNum)
1793 Vars.insert(I, Var);
1797 Vars.push_back(Var);
1800 // Gather and emit post-function debug information.
1801 void DwarfDebug::endFunction(const MachineFunction *MF) {
1802 if (!MMI->hasDebugInfo() || LScopes.empty())
1805 // Define end label for subprogram.
1806 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1807 // Assumes in correct section after the entry point.
1808 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1809 // Set DwarfCompileUnitID in MCContext to default value.
1810 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1812 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1813 collectVariableInfo(MF, ProcessedVars);
1815 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1816 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1817 assert(TheCU && "Unable to find compile unit!");
1819 // Construct abstract scopes.
1820 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1821 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1822 LexicalScope *AScope = AList[i];
1823 DISubprogram SP(AScope->getScopeNode());
1824 if (SP.isSubprogram()) {
1825 // Collect info for variables that were optimized out.
1826 DIArray Variables = SP.getVariables();
1827 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1828 DIVariable DV(Variables.getElement(i));
1829 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1831 // Check that DbgVariable for DV wasn't created earlier, when
1832 // findAbstractVariable() was called for inlined instance of DV.
1833 LLVMContext &Ctx = DV->getContext();
1834 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1835 if (AbstractVariables.lookup(CleanDV))
1837 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1838 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1841 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1842 constructScopeDIE(TheCU, AScope);
1845 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1847 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1848 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1851 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1852 E = ScopeVariables.end();
1854 DeleteContainerPointers(I->second);
1855 ScopeVariables.clear();
1856 DeleteContainerPointers(CurrentFnArguments);
1857 UserVariables.clear();
1859 AbstractVariables.clear();
1860 LabelsBeforeInsn.clear();
1861 LabelsAfterInsn.clear();
1865 // Register a source line with debug info. Returns the unique label that was
1866 // emitted and which provides correspondence to the source line list.
1867 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1873 DIDescriptor Scope(S);
1875 if (Scope.isCompileUnit()) {
1876 DICompileUnit CU(S);
1877 Fn = CU.getFilename();
1878 Dir = CU.getDirectory();
1879 } else if (Scope.isFile()) {
1881 Fn = F.getFilename();
1882 Dir = F.getDirectory();
1883 } else if (Scope.isSubprogram()) {
1885 Fn = SP.getFilename();
1886 Dir = SP.getDirectory();
1887 } else if (Scope.isLexicalBlockFile()) {
1888 DILexicalBlockFile DBF(S);
1889 Fn = DBF.getFilename();
1890 Dir = DBF.getDirectory();
1891 } else if (Scope.isLexicalBlock()) {
1892 DILexicalBlock DB(S);
1893 Fn = DB.getFilename();
1894 Dir = DB.getDirectory();
1896 llvm_unreachable("Unexpected scope info");
1898 Src = getOrCreateSourceID(
1899 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1901 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1904 //===----------------------------------------------------------------------===//
1906 //===----------------------------------------------------------------------===//
1908 // Compute the size and offset of a DIE. The offset is relative to start of the
1909 // CU. It returns the offset after laying out the DIE.
1910 unsigned DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1911 // Get the children.
1912 const std::vector<DIE *> &Children = Die->getChildren();
1914 // Record the abbreviation.
1915 assignAbbrevNumber(Die->getAbbrev());
1917 // Get the abbreviation for this DIE.
1918 unsigned AbbrevNumber = Die->getAbbrevNumber();
1919 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1922 Die->setOffset(Offset);
1924 // Start the size with the size of abbreviation code.
1925 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1927 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1928 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1930 // Size the DIE attribute values.
1931 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1932 // Size attribute value.
1933 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1935 // Size the DIE children if any.
1936 if (!Children.empty()) {
1937 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1938 "Children flag not set");
1940 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1941 Offset = computeSizeAndOffset(Children[j], Offset);
1943 // End of children marker.
1944 Offset += sizeof(int8_t);
1947 Die->setSize(Offset - Die->getOffset());
1951 // Compute the size and offset for each DIE.
1952 void DwarfUnits::computeSizeAndOffsets() {
1953 // Offset from the first CU in the debug info section is 0 initially.
1954 unsigned SecOffset = 0;
1956 // Iterate over each compile unit and set the size and offsets for each
1957 // DIE within each compile unit. All offsets are CU relative.
1958 for (SmallVectorImpl<Unit *>::const_iterator I = CUs.begin(), E = CUs.end();
1960 (*I)->setDebugInfoOffset(SecOffset);
1962 // CU-relative offset is reset to 0 here.
1963 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1964 (*I)->getHeaderSize(); // Unit-specific headers
1966 // EndOffset here is CU-relative, after laying out
1967 // all of the CU DIE.
1968 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1969 SecOffset += EndOffset;
1973 // Emit initial Dwarf sections with a label at the start of each one.
1974 void DwarfDebug::emitSectionLabels() {
1975 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1977 // Dwarf sections base addresses.
1978 DwarfInfoSectionSym =
1979 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1980 DwarfAbbrevSectionSym =
1981 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1982 if (useSplitDwarf())
1983 DwarfAbbrevDWOSectionSym = emitSectionSym(
1984 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1985 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1987 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1988 emitSectionSym(Asm, MacroInfo);
1990 DwarfLineSectionSym =
1991 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1992 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1993 if (GenerateGnuPubSections) {
1994 DwarfGnuPubNamesSectionSym =
1995 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1996 DwarfGnuPubTypesSectionSym =
1997 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1998 } else if (HasDwarfPubSections) {
1999 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2000 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2003 DwarfStrSectionSym =
2004 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2005 if (useSplitDwarf()) {
2006 DwarfStrDWOSectionSym =
2007 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2008 DwarfAddrSectionSym =
2009 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2011 DwarfDebugRangeSectionSym =
2012 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2014 DwarfDebugLocSectionSym =
2015 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2017 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2018 emitSectionSym(Asm, TLOF.getDataSection());
2021 // Recursively emits a debug information entry.
2022 void DwarfDebug::emitDIE(DIE *Die, ArrayRef<DIEAbbrev *> Abbrevs) {
2023 // Get the abbreviation for this DIE.
2024 unsigned AbbrevNumber = Die->getAbbrevNumber();
2025 const DIEAbbrev *Abbrev = Abbrevs[AbbrevNumber - 1];
2027 // Emit the code (index) for the abbreviation.
2028 if (Asm->isVerbose())
2029 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2030 Twine::utohexstr(Die->getOffset()) + ":0x" +
2031 Twine::utohexstr(Die->getSize()) + " " +
2032 dwarf::TagString(Abbrev->getTag()));
2033 Asm->EmitULEB128(AbbrevNumber);
2035 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2036 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2038 // Emit the DIE attribute values.
2039 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2040 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2041 dwarf::Form Form = AbbrevData[i].getForm();
2042 assert(Form && "Too many attributes for DIE (check abbreviation)");
2044 if (Asm->isVerbose())
2045 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2048 case dwarf::DW_AT_abstract_origin:
2049 case dwarf::DW_AT_type:
2050 case dwarf::DW_AT_friend:
2051 case dwarf::DW_AT_specification:
2052 case dwarf::DW_AT_import:
2053 case dwarf::DW_AT_containing_type: {
2054 DIEEntry *E = cast<DIEEntry>(Values[i]);
2055 DIE *Origin = E->getEntry();
2056 unsigned Addr = Origin->getOffset();
2057 if (Form == dwarf::DW_FORM_ref_addr) {
2058 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2059 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2060 // section. Origin->getOffset() returns the offset from start of the
2062 CompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2063 assert(CU && "CUDie should belong to a CU.");
2064 Addr += CU->getDebugInfoOffset();
2065 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2066 Asm->EmitLabelPlusOffset(DwarfInfoSectionSym, Addr,
2067 DIEEntry::getRefAddrSize(Asm));
2069 Asm->EmitLabelOffsetDifference(DwarfInfoSectionSym, Addr,
2070 DwarfInfoSectionSym,
2071 DIEEntry::getRefAddrSize(Asm));
2073 // Make sure Origin belong to the same CU.
2074 assert(Die->getUnit() == Origin->getUnit() &&
2075 "The referenced DIE should belong to the same CU in ref4");
2076 Asm->EmitInt32(Addr);
2080 case dwarf::DW_AT_ranges: {
2081 // DW_AT_range Value encodes offset in debug_range section.
2082 DIELabel *V = cast<DIELabel>(Values[i]);
2084 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2085 Asm->EmitSectionOffset(V->getValue(), DwarfDebugRangeSectionSym);
2087 Asm->EmitLabelDifference(V->getValue(), DwarfDebugRangeSectionSym, 4);
2090 case dwarf::DW_AT_location: {
2091 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2092 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2093 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2095 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2097 Values[i]->EmitValue(Asm, Form);
2101 case dwarf::DW_AT_accessibility: {
2102 if (Asm->isVerbose()) {
2103 DIEInteger *V = cast<DIEInteger>(Values[i]);
2104 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2106 Values[i]->EmitValue(Asm, Form);
2110 // Emit an attribute using the defined form.
2111 Values[i]->EmitValue(Asm, Form);
2116 // Emit the DIE children if any.
2117 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2118 const std::vector<DIE *> &Children = Die->getChildren();
2120 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2121 emitDIE(Children[j], Abbrevs);
2123 if (Asm->isVerbose())
2124 Asm->OutStreamer.AddComment("End Of Children Mark");
2129 // Emit the various dwarf units to the unit section USection with
2130 // the abbreviations going into ASection.
2131 void DwarfUnits::emitUnits(DwarfDebug *DD, const MCSection *USection,
2132 const MCSection *ASection,
2133 const MCSymbol *ASectionSym) {
2134 Asm->OutStreamer.SwitchSection(USection);
2135 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
2138 DIE *Die = TheU->getUnitDie();
2140 // Emit the compile units header.
2141 Asm->OutStreamer.EmitLabel(
2142 Asm->GetTempSymbol(USection->getLabelBeginName(), TheU->getUniqueID()));
2144 // Emit size of content not including length itself
2145 Asm->OutStreamer.AddComment("Length of Unit");
2146 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2148 TheU->emitHeader(ASection, ASectionSym);
2150 DD->emitDIE(Die, Abbreviations);
2151 Asm->OutStreamer.EmitLabel(
2152 Asm->GetTempSymbol(USection->getLabelEndName(), TheU->getUniqueID()));
2156 // Emit the debug info section.
2157 void DwarfDebug::emitDebugInfo() {
2158 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2160 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2161 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2162 DwarfAbbrevSectionSym);
2165 // Emit the abbreviation section.
2166 void DwarfDebug::emitAbbreviations() {
2167 if (!useSplitDwarf())
2168 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2171 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2174 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2175 std::vector<DIEAbbrev *> *Abbrevs) {
2176 // Check to see if it is worth the effort.
2177 if (!Abbrevs->empty()) {
2178 // Start the debug abbrev section.
2179 Asm->OutStreamer.SwitchSection(Section);
2181 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2182 Asm->OutStreamer.EmitLabel(Begin);
2184 // For each abbrevation.
2185 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2186 // Get abbreviation data
2187 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2189 // Emit the abbrevations code (base 1 index.)
2190 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2192 // Emit the abbreviations data.
2196 // Mark end of abbreviations.
2197 Asm->EmitULEB128(0, "EOM(3)");
2199 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2200 Asm->OutStreamer.EmitLabel(End);
2204 // Emit the last address of the section and the end of the line matrix.
2205 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2206 // Define last address of section.
2207 Asm->OutStreamer.AddComment("Extended Op");
2210 Asm->OutStreamer.AddComment("Op size");
2211 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2212 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2213 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2215 Asm->OutStreamer.AddComment("Section end label");
2217 Asm->OutStreamer.EmitSymbolValue(
2218 Asm->GetTempSymbol("section_end", SectionEnd),
2219 Asm->getDataLayout().getPointerSize());
2221 // Mark end of matrix.
2222 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2228 // Emit visible names into a hashed accelerator table section.
2229 void DwarfDebug::emitAccelNames() {
2231 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2232 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2233 E = getUnits().end();
2236 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2237 for (StringMap<std::vector<const DIE *> >::const_iterator
2241 StringRef Name = GI->getKey();
2242 const std::vector<const DIE *> &Entities = GI->second;
2243 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2244 DE = Entities.end();
2246 AT.AddName(Name, *DI);
2250 AT.FinalizeTable(Asm, "Names");
2251 Asm->OutStreamer.SwitchSection(
2252 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2253 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2254 Asm->OutStreamer.EmitLabel(SectionBegin);
2256 // Emit the full data.
2257 AT.Emit(Asm, SectionBegin, &InfoHolder);
2260 // Emit objective C classes and categories into a hashed accelerator table
2262 void DwarfDebug::emitAccelObjC() {
2264 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2265 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2266 E = getUnits().end();
2269 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2270 for (StringMap<std::vector<const DIE *> >::const_iterator
2274 StringRef Name = GI->getKey();
2275 const std::vector<const DIE *> &Entities = GI->second;
2276 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2277 DE = Entities.end();
2279 AT.AddName(Name, *DI);
2283 AT.FinalizeTable(Asm, "ObjC");
2284 Asm->OutStreamer.SwitchSection(
2285 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2286 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2287 Asm->OutStreamer.EmitLabel(SectionBegin);
2289 // Emit the full data.
2290 AT.Emit(Asm, SectionBegin, &InfoHolder);
2293 // Emit namespace dies into a hashed accelerator table.
2294 void DwarfDebug::emitAccelNamespaces() {
2296 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2297 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2298 E = getUnits().end();
2301 const StringMap<std::vector<const DIE *> > &Names =
2302 TheU->getAccelNamespace();
2303 for (StringMap<std::vector<const DIE *> >::const_iterator
2307 StringRef Name = GI->getKey();
2308 const std::vector<const DIE *> &Entities = GI->second;
2309 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2310 DE = Entities.end();
2312 AT.AddName(Name, *DI);
2316 AT.FinalizeTable(Asm, "namespac");
2317 Asm->OutStreamer.SwitchSection(
2318 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2319 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2320 Asm->OutStreamer.EmitLabel(SectionBegin);
2322 // Emit the full data.
2323 AT.Emit(Asm, SectionBegin, &InfoHolder);
2326 // Emit type dies into a hashed accelerator table.
2327 void DwarfDebug::emitAccelTypes() {
2328 std::vector<DwarfAccelTable::Atom> Atoms;
2330 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2332 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2334 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2335 DwarfAccelTable AT(Atoms);
2336 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2337 E = getUnits().end();
2340 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2341 TheU->getAccelTypes();
2343 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2347 StringRef Name = GI->getKey();
2348 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2350 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2351 DI = Entities.begin(),
2352 DE = Entities.end();
2354 AT.AddName(Name, DI->first, DI->second);
2358 AT.FinalizeTable(Asm, "types");
2359 Asm->OutStreamer.SwitchSection(
2360 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2361 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2362 Asm->OutStreamer.EmitLabel(SectionBegin);
2364 // Emit the full data.
2365 AT.Emit(Asm, SectionBegin, &InfoHolder);
2368 // Public name handling.
2369 // The format for the various pubnames:
2371 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2372 // for the DIE that is named.
2374 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2375 // into the CU and the index value is computed according to the type of value
2376 // for the DIE that is named.
2378 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2379 // it's the offset within the debug_info/debug_types dwo section, however, the
2380 // reference in the pubname header doesn't change.
2382 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2383 static dwarf::PubIndexEntryDescriptor computeIndexValue(Unit *CU,
2385 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2387 // We could have a specification DIE that has our most of our knowledge,
2388 // look for that now.
2389 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2391 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2392 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2393 Linkage = dwarf::GIEL_EXTERNAL;
2394 } else if (Die->findAttribute(dwarf::DW_AT_external))
2395 Linkage = dwarf::GIEL_EXTERNAL;
2397 switch (Die->getTag()) {
2398 case dwarf::DW_TAG_class_type:
2399 case dwarf::DW_TAG_structure_type:
2400 case dwarf::DW_TAG_union_type:
2401 case dwarf::DW_TAG_enumeration_type:
2402 return dwarf::PubIndexEntryDescriptor(
2403 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2404 ? dwarf::GIEL_STATIC
2405 : dwarf::GIEL_EXTERNAL);
2406 case dwarf::DW_TAG_typedef:
2407 case dwarf::DW_TAG_base_type:
2408 case dwarf::DW_TAG_subrange_type:
2409 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2410 case dwarf::DW_TAG_namespace:
2411 return dwarf::GIEK_TYPE;
2412 case dwarf::DW_TAG_subprogram:
2413 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2414 case dwarf::DW_TAG_constant:
2415 case dwarf::DW_TAG_variable:
2416 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2417 case dwarf::DW_TAG_enumerator:
2418 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2419 dwarf::GIEL_STATIC);
2421 return dwarf::GIEK_NONE;
2425 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2427 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2428 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2429 const MCSection *PSec =
2430 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2431 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2433 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2434 E = getUnits().end();
2437 unsigned ID = TheU->getUniqueID();
2439 // Start the dwarf pubnames section.
2440 Asm->OutStreamer.SwitchSection(PSec);
2442 // Emit a label so we can reference the beginning of this pubname section.
2444 Asm->OutStreamer.EmitLabel(
2445 Asm->GetTempSymbol("gnu_pubnames", TheU->getUniqueID()));
2448 Asm->OutStreamer.AddComment("Length of Public Names Info");
2449 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2450 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2452 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2454 Asm->OutStreamer.AddComment("DWARF Version");
2455 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2457 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2458 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2459 DwarfInfoSectionSym);
2461 Asm->OutStreamer.AddComment("Compilation Unit Length");
2462 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2463 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2466 // Emit the pubnames for this compilation unit.
2467 const StringMap<const DIE *> &Globals = TheU->getGlobalNames();
2468 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2471 const char *Name = GI->getKeyData();
2472 const DIE *Entity = GI->second;
2474 Asm->OutStreamer.AddComment("DIE offset");
2475 Asm->EmitInt32(Entity->getOffset());
2478 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2479 Asm->OutStreamer.AddComment(
2480 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2481 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2482 Asm->EmitInt8(Desc.toBits());
2485 if (Asm->isVerbose())
2486 Asm->OutStreamer.AddComment("External Name");
2487 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2490 Asm->OutStreamer.AddComment("End Mark");
2492 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2496 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2497 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2498 const MCSection *PSec =
2499 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2500 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2502 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2503 E = getUnits().end();
2506 // Start the dwarf pubtypes section.
2507 Asm->OutStreamer.SwitchSection(PSec);
2509 // Emit a label so we can reference the beginning of this pubtype section.
2511 Asm->OutStreamer.EmitLabel(
2512 Asm->GetTempSymbol("gnu_pubtypes", TheU->getUniqueID()));
2515 Asm->OutStreamer.AddComment("Length of Public Types Info");
2516 Asm->EmitLabelDifference(
2517 Asm->GetTempSymbol("pubtypes_end", TheU->getUniqueID()),
2518 Asm->GetTempSymbol("pubtypes_begin", TheU->getUniqueID()), 4);
2520 Asm->OutStreamer.EmitLabel(
2521 Asm->GetTempSymbol("pubtypes_begin", TheU->getUniqueID()));
2523 if (Asm->isVerbose())
2524 Asm->OutStreamer.AddComment("DWARF Version");
2525 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2527 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2528 Asm->EmitSectionOffset(
2529 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()),
2530 DwarfInfoSectionSym);
2532 Asm->OutStreamer.AddComment("Compilation Unit Length");
2533 Asm->EmitLabelDifference(
2534 Asm->GetTempSymbol(ISec->getLabelEndName(), TheU->getUniqueID()),
2535 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()), 4);
2537 // Emit the pubtypes.
2538 const StringMap<const DIE *> &Globals = TheU->getGlobalTypes();
2539 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2542 const char *Name = GI->getKeyData();
2543 const DIE *Entity = GI->second;
2545 if (Asm->isVerbose())
2546 Asm->OutStreamer.AddComment("DIE offset");
2547 Asm->EmitInt32(Entity->getOffset());
2550 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2551 Asm->OutStreamer.AddComment(
2552 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2553 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2554 Asm->EmitInt8(Desc.toBits());
2557 if (Asm->isVerbose())
2558 Asm->OutStreamer.AddComment("External Name");
2560 // Emit the name with a terminating null byte.
2561 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2564 Asm->OutStreamer.AddComment("End Mark");
2566 Asm->OutStreamer.EmitLabel(
2567 Asm->GetTempSymbol("pubtypes_end", TheU->getUniqueID()));
2571 // Emit strings into a string section.
2572 void DwarfUnits::emitStrings(const MCSection *StrSection,
2573 const MCSection *OffsetSection = NULL,
2574 const MCSymbol *StrSecSym = NULL) {
2576 if (StringPool.empty())
2579 // Start the dwarf str section.
2580 Asm->OutStreamer.SwitchSection(StrSection);
2582 // Get all of the string pool entries and put them in an array by their ID so
2583 // we can sort them.
2585 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2588 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2589 I = StringPool.begin(),
2590 E = StringPool.end();
2592 Entries.push_back(std::make_pair(I->second.second, &*I));
2594 array_pod_sort(Entries.begin(), Entries.end());
2596 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2597 // Emit a label for reference from debug information entries.
2598 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2600 // Emit the string itself with a terminating null byte.
2601 Asm->OutStreamer.EmitBytes(
2602 StringRef(Entries[i].second->getKeyData(),
2603 Entries[i].second->getKeyLength() + 1));
2606 // If we've got an offset section go ahead and emit that now as well.
2607 if (OffsetSection) {
2608 Asm->OutStreamer.SwitchSection(OffsetSection);
2609 unsigned offset = 0;
2610 unsigned size = 4; // FIXME: DWARF64 is 8.
2611 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2612 Asm->OutStreamer.EmitIntValue(offset, size);
2613 offset += Entries[i].second->getKeyLength() + 1;
2619 // Emit addresses into the section given.
2620 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2622 if (AddressPool.empty())
2625 // Start the dwarf addr section.
2626 Asm->OutStreamer.SwitchSection(AddrSection);
2628 // Order the address pool entries by ID
2629 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2631 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2632 E = AddressPool.end();
2634 Entries[I->second] = I->first;
2636 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2637 // Emit an expression for reference from debug information entries.
2638 if (const MCExpr *Expr = Entries[i])
2639 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2641 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2645 // Emit visible names into a debug str section.
2646 void DwarfDebug::emitDebugStr() {
2647 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2648 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2651 // Emit locations into the debug loc section.
2652 void DwarfDebug::emitDebugLoc() {
2653 if (DotDebugLocEntries.empty())
2656 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2657 I = DotDebugLocEntries.begin(),
2658 E = DotDebugLocEntries.end();
2660 DotDebugLocEntry &Entry = *I;
2661 if (I + 1 != DotDebugLocEntries.end())
2665 // Start the dwarf loc section.
2666 Asm->OutStreamer.SwitchSection(
2667 Asm->getObjFileLowering().getDwarfLocSection());
2668 unsigned char Size = Asm->getDataLayout().getPointerSize();
2669 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2671 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2672 I = DotDebugLocEntries.begin(),
2673 E = DotDebugLocEntries.end();
2674 I != E; ++I, ++index) {
2675 DotDebugLocEntry &Entry = *I;
2676 if (Entry.isMerged())
2678 if (Entry.isEmpty()) {
2679 Asm->OutStreamer.EmitIntValue(0, Size);
2680 Asm->OutStreamer.EmitIntValue(0, Size);
2681 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2683 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2684 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2685 DIVariable DV(Entry.getVariable());
2686 Asm->OutStreamer.AddComment("Loc expr size");
2687 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2688 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2689 Asm->EmitLabelDifference(end, begin, 2);
2690 Asm->OutStreamer.EmitLabel(begin);
2691 if (Entry.isInt()) {
2692 DIBasicType BTy(DV.getType());
2693 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2694 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2695 Asm->OutStreamer.AddComment("DW_OP_consts");
2696 Asm->EmitInt8(dwarf::DW_OP_consts);
2697 Asm->EmitSLEB128(Entry.getInt());
2699 Asm->OutStreamer.AddComment("DW_OP_constu");
2700 Asm->EmitInt8(dwarf::DW_OP_constu);
2701 Asm->EmitULEB128(Entry.getInt());
2703 } else if (Entry.isLocation()) {
2704 MachineLocation Loc = Entry.getLoc();
2705 if (!DV.hasComplexAddress())
2707 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2709 // Complex address entry.
2710 unsigned N = DV.getNumAddrElements();
2712 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2713 if (Loc.getOffset()) {
2715 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2716 Asm->OutStreamer.AddComment("DW_OP_deref");
2717 Asm->EmitInt8(dwarf::DW_OP_deref);
2718 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2719 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2720 Asm->EmitSLEB128(DV.getAddrElement(1));
2722 // If first address element is OpPlus then emit
2723 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2724 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2725 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2729 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2732 // Emit remaining complex address elements.
2733 for (; i < N; ++i) {
2734 uint64_t Element = DV.getAddrElement(i);
2735 if (Element == DIBuilder::OpPlus) {
2736 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2737 Asm->EmitULEB128(DV.getAddrElement(++i));
2738 } else if (Element == DIBuilder::OpDeref) {
2740 Asm->EmitInt8(dwarf::DW_OP_deref);
2742 llvm_unreachable("unknown Opcode found in complex address");
2746 // else ... ignore constant fp. There is not any good way to
2747 // to represent them here in dwarf.
2748 Asm->OutStreamer.EmitLabel(end);
2753 struct SymbolCUSorter {
2754 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2755 const MCStreamer &Streamer;
2757 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2758 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2759 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2761 // Symbols with no order assigned should be placed at the end.
2762 // (e.g. section end labels)
2764 IA = (unsigned)(-1);
2766 IB = (unsigned)(-1);
2771 static bool CUSort(const Unit *A, const Unit *B) {
2772 return (A->getUniqueID() < B->getUniqueID());
2776 const MCSymbol *Start, *End;
2779 // Emit a debug aranges section, containing a CU lookup for any
2780 // address we can tie back to a CU.
2781 void DwarfDebug::emitDebugARanges() {
2782 // Start the dwarf aranges section.
2783 Asm->OutStreamer.SwitchSection(
2784 Asm->getObjFileLowering().getDwarfARangesSection());
2786 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2790 // Build a list of sections used.
2791 std::vector<const MCSection *> Sections;
2792 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2794 const MCSection *Section = it->first;
2795 Sections.push_back(Section);
2798 // Sort the sections into order.
2799 // This is only done to ensure consistent output order across different runs.
2800 std::sort(Sections.begin(), Sections.end(), SectionSort);
2802 // Build a set of address spans, sorted by CU.
2803 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2804 const MCSection *Section = Sections[SecIdx];
2805 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2806 if (List.size() < 2)
2809 // Sort the symbols by offset within the section.
2810 SymbolCUSorter sorter(Asm->OutStreamer);
2811 std::sort(List.begin(), List.end(), sorter);
2813 // If we have no section (e.g. common), just write out
2814 // individual spans for each symbol.
2815 if (Section == NULL) {
2816 for (size_t n = 0; n < List.size(); n++) {
2817 const SymbolCU &Cur = List[n];
2820 Span.Start = Cur.Sym;
2823 Spans[Cur.CU].push_back(Span);
2826 // Build spans between each label.
2827 const MCSymbol *StartSym = List[0].Sym;
2828 for (size_t n = 1; n < List.size(); n++) {
2829 const SymbolCU &Prev = List[n - 1];
2830 const SymbolCU &Cur = List[n];
2832 // Try and build the longest span we can within the same CU.
2833 if (Cur.CU != Prev.CU) {
2835 Span.Start = StartSym;
2837 Spans[Prev.CU].push_back(Span);
2844 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2845 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2847 // Build a list of CUs used.
2848 std::vector<CompileUnit *> CUs;
2849 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2850 CompileUnit *CU = it->first;
2854 // Sort the CU list (again, to ensure consistent output order).
2855 std::sort(CUs.begin(), CUs.end(), CUSort);
2857 // Emit an arange table for each CU we used.
2858 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2859 CompileUnit *CU = CUs[CUIdx];
2860 std::vector<ArangeSpan> &List = Spans[CU];
2862 // Emit size of content not including length itself.
2863 unsigned ContentSize =
2864 sizeof(int16_t) + // DWARF ARange version number
2865 sizeof(int32_t) + // Offset of CU in the .debug_info section
2866 sizeof(int8_t) + // Pointer Size (in bytes)
2867 sizeof(int8_t); // Segment Size (in bytes)
2869 unsigned TupleSize = PtrSize * 2;
2871 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2872 unsigned Padding = 0;
2873 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2876 ContentSize += Padding;
2877 ContentSize += (List.size() + 1) * TupleSize;
2879 // For each compile unit, write the list of spans it covers.
2880 Asm->OutStreamer.AddComment("Length of ARange Set");
2881 Asm->EmitInt32(ContentSize);
2882 Asm->OutStreamer.AddComment("DWARF Arange version number");
2883 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2884 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2885 Asm->EmitSectionOffset(
2886 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2887 DwarfInfoSectionSym);
2888 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2889 Asm->EmitInt8(PtrSize);
2890 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2893 for (unsigned n = 0; n < Padding; n++)
2894 Asm->EmitInt8(0xff);
2896 for (unsigned n = 0; n < List.size(); n++) {
2897 const ArangeSpan &Span = List[n];
2898 Asm->EmitLabelReference(Span.Start, PtrSize);
2900 // Calculate the size as being from the span start to it's end.
2902 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2904 // For symbols without an end marker (e.g. common), we
2905 // write a single arange entry containing just that one symbol.
2906 uint64_t Size = SymSize[Span.Start];
2910 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2914 Asm->OutStreamer.AddComment("ARange terminator");
2915 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2916 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2920 // Emit visible names into a debug ranges section.
2921 void DwarfDebug::emitDebugRanges() {
2922 // Start the dwarf ranges section.
2923 Asm->OutStreamer.SwitchSection(
2924 Asm->getObjFileLowering().getDwarfRangesSection());
2925 unsigned char Size = Asm->getDataLayout().getPointerSize();
2926 for (uint32_t i = 0, e = DebugRangeSymbols.size(); i < e; ++i) {
2927 // Only emit a symbol for every range pair for now.
2928 // FIXME: Make this per range list.
2930 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_ranges", i));
2932 const MCSymbol *I = DebugRangeSymbols[i];
2934 Asm->OutStreamer.EmitSymbolValue(I, Size);
2936 Asm->OutStreamer.EmitIntValue(0, Size);
2940 // Emit visible names into a debug macinfo section.
2941 void DwarfDebug::emitDebugMacInfo() {
2942 if (const MCSection *LineInfo =
2943 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2944 // Start the dwarf macinfo section.
2945 Asm->OutStreamer.SwitchSection(LineInfo);
2949 // DWARF5 Experimental Separate Dwarf emitters.
2951 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2952 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2953 // DW_AT_ranges_base, DW_AT_addr_base.
2954 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2956 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2957 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2958 Asm, this, &SkeletonHolder);
2960 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2961 CU->getNode().getSplitDebugFilename());
2963 // Relocate to the beginning of the addr_base section, else 0 for the
2964 // beginning of the one for this compile unit.
2965 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2966 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2967 DwarfAddrSectionSym);
2969 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2971 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2972 // into an entity. We're using 0, or a NULL label for this.
2973 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2975 // DW_AT_stmt_list is a offset of line number information for this
2976 // compile unit in debug_line section.
2977 // FIXME: Should handle multiple compile units.
2978 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2979 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
2980 DwarfLineSectionSym);
2982 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2984 if (!CompilationDir.empty())
2985 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2987 // Flags to let the linker know we have emitted new style pubnames.
2988 if (GenerateGnuPubSections) {
2989 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2990 NewCU->addSectionLabel(
2991 Die, dwarf::DW_AT_GNU_pubnames,
2992 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
2994 NewCU->addSectionDelta(
2995 Die, dwarf::DW_AT_GNU_pubnames,
2996 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
2997 DwarfGnuPubNamesSectionSym);
2999 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3000 NewCU->addSectionLabel(
3001 Die, dwarf::DW_AT_GNU_pubtypes,
3002 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
3004 NewCU->addSectionDelta(
3005 Die, dwarf::DW_AT_GNU_pubtypes,
3006 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
3007 DwarfGnuPubTypesSectionSym);
3010 // Flag if we've emitted any ranges and their location for the compile unit.
3011 if (DebugRangeSymbols.size()) {
3012 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3013 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_ranges_base,
3014 DwarfDebugRangeSectionSym);
3016 NewCU->addUInt(Die, dwarf::DW_AT_GNU_ranges_base, dwarf::DW_FORM_data4,
3020 SkeletonHolder.addUnit(NewCU);
3025 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
3026 assert(useSplitDwarf() && "No split dwarf debug info?");
3027 emitAbbrevs(Section, &SkeletonAbbrevs);
3030 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3031 // compile units that would normally be in debug_info.
3032 void DwarfDebug::emitDebugInfoDWO() {
3033 assert(useSplitDwarf() && "No split dwarf debug info?");
3034 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
3035 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3036 DwarfAbbrevDWOSectionSym);
3039 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3040 // abbreviations for the .debug_info.dwo section.
3041 void DwarfDebug::emitDebugAbbrevDWO() {
3042 assert(useSplitDwarf() && "No split dwarf?");
3043 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3047 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3048 // string section and is identical in format to traditional .debug_str
3050 void DwarfDebug::emitDebugStrDWO() {
3051 assert(useSplitDwarf() && "No split dwarf?");
3052 const MCSection *OffSec =
3053 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3054 const MCSymbol *StrSym = DwarfStrSectionSym;
3055 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3059 void DwarfDebug::addTypeUnitType(uint16_t Language, DIE *RefDie,
3060 DICompositeType CTy) {
3061 DenseMap<const MDNode *,
3062 std::pair<uint64_t, SmallVectorImpl<DIE *> *> >::iterator I =
3063 TypeUnits.find(CTy);
3064 SmallVector<DIE *, 8> References;
3065 References.push_back(RefDie);
3066 if (I != TypeUnits.end()) {
3067 if (I->second.second) {
3068 I->second.second->push_back(RefDie);
3072 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3073 TypeUnit *NewTU = new TypeUnit(GlobalCUIndexCount++, UnitDie, Language, Asm,
3075 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3078 // Register the type in the TypeUnits map with a vector of references to be
3079 // populated whenever a reference is required.
3080 I = TypeUnits.insert(std::make_pair(CTy, std::make_pair(0, &References)))
3083 // Construct the type, this may, recursively, require more type units that
3084 // may in turn require this type again - in which case they will add DIEs to
3085 // the References vector.
3086 DIE *Die = NewTU->createTypeDIE(CTy);
3088 if (GenerateODRHash && shouldAddODRHash(NewTU, Die))
3089 NewTU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3090 dwarf::DW_FORM_data8,
3091 DIEHash().computeDIEODRSignature(*Die));
3092 // FIXME: This won't handle circularly referential structures, as the DIE
3093 // may have references to other DIEs still under construction and missing
3094 // their signature. Hashing should walk through the signatures to their
3095 // referenced type, or possibly walk the precomputed hashes of related types
3097 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3099 // Remove the References vector and add the type hash.
3100 I->second.first = Signature;
3101 I->second.second = NULL;
3103 InfoHolder.addUnit(NewTU);
3106 // Populate all the signatures.
3107 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3108 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3109 dwarf::DW_FORM_ref_sig8, I->second.first);