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 DWARF5 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 //===----------------------------------------------------------------------===//
119 /// resolve - Look in the DwarfDebug map for the MDNode that
120 /// corresponds to the reference.
121 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
122 return DD->resolve(Ref);
125 DIType DbgVariable::getType() const {
126 DIType Ty = Var.getType();
127 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
128 // addresses instead.
129 if (Var.isBlockByrefVariable()) {
130 /* Byref variables, in Blocks, are declared by the programmer as
131 "SomeType VarName;", but the compiler creates a
132 __Block_byref_x_VarName struct, and gives the variable VarName
133 either the struct, or a pointer to the struct, as its type. This
134 is necessary for various behind-the-scenes things the compiler
135 needs to do with by-reference variables in blocks.
137 However, as far as the original *programmer* is concerned, the
138 variable should still have type 'SomeType', as originally declared.
140 The following function dives into the __Block_byref_x_VarName
141 struct to find the original type of the variable. This will be
142 passed back to the code generating the type for the Debug
143 Information Entry for the variable 'VarName'. 'VarName' will then
144 have the original type 'SomeType' in its debug information.
146 The original type 'SomeType' will be the type of the field named
147 'VarName' inside the __Block_byref_x_VarName struct.
149 NOTE: In order for this to not completely fail on the debugger
150 side, the Debug Information Entry for the variable VarName needs to
151 have a DW_AT_location that tells the debugger how to unwind through
152 the pointers and __Block_byref_x_VarName struct to find the actual
153 value of the variable. The function addBlockByrefType does this. */
155 uint16_t tag = Ty.getTag();
157 if (tag == dwarf::DW_TAG_pointer_type)
158 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
160 DIArray Elements = DICompositeType(subType).getTypeArray();
161 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
162 DIDerivedType DT(Elements.getElement(i));
163 if (getName() == DT.getName())
164 return (resolve(DT.getTypeDerivedFrom()));
170 } // end llvm namespace
172 /// Return Dwarf Version by checking module flags.
173 static unsigned getDwarfVersionFromModule(const Module *M) {
174 Value *Val = M->getModuleFlag("Dwarf Version");
176 return dwarf::DWARF_VERSION;
177 return cast<ConstantInt>(Val)->getZExtValue();
180 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
181 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
182 PrevLabel(NULL), GlobalRangeCount(0),
183 InfoHolder(A, "info_string", DIEValueAllocator),
184 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
186 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
187 DwarfStrSectionSym = TextSectionSym = 0;
188 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
189 DwarfAddrSectionSym = 0;
190 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
191 FunctionBeginSym = FunctionEndSym = 0;
192 CurFn = 0; CurMI = 0;
194 // Turn on accelerator tables for Darwin by default, pubnames by
195 // default for non-Darwin, and handle split dwarf.
196 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
198 if (DwarfAccelTables == Default)
199 HasDwarfAccelTables = IsDarwin;
201 HasDwarfAccelTables = DwarfAccelTables == Enable;
203 if (SplitDwarf == Default)
204 HasSplitDwarf = false;
206 HasSplitDwarf = SplitDwarf == Enable;
208 if (DwarfPubSections == Default)
209 HasDwarfPubSections = !IsDarwin;
211 HasDwarfPubSections = DwarfPubSections == Enable;
213 DwarfVersion = DwarfVersionNumber
215 : getDwarfVersionFromModule(MMI->getModule());
218 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
223 // Switch to the specified MCSection and emit an assembler
224 // temporary label to it if SymbolStem is specified.
225 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
226 const char *SymbolStem = 0) {
227 Asm->OutStreamer.SwitchSection(Section);
231 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
232 Asm->OutStreamer.EmitLabel(TmpSym);
236 DwarfFile::~DwarfFile() {
237 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
242 MCSymbol *DwarfFile::getStringPoolSym() {
243 return Asm->GetTempSymbol(StringPref);
246 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
247 std::pair<MCSymbol *, unsigned> &Entry =
248 StringPool.GetOrCreateValue(Str).getValue();
252 Entry.second = NextStringPoolNumber++;
253 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
256 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
257 std::pair<MCSymbol *, unsigned> &Entry =
258 StringPool.GetOrCreateValue(Str).getValue();
262 Entry.second = NextStringPoolNumber++;
263 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
267 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
268 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
271 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
272 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
273 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
275 ++NextAddrPoolNumber;
276 return P.first->second;
279 // Define a unique number for the abbreviation.
281 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
282 // Check the set for priors.
283 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
285 // If it's newly added.
286 if (InSet == &Abbrev) {
287 // Add to abbreviation list.
288 Abbreviations.push_back(&Abbrev);
290 // Assign the vector position + 1 as its number.
291 Abbrev.setNumber(Abbreviations.size());
293 // Assign existing abbreviation number.
294 Abbrev.setNumber(InSet->getNumber());
298 static bool isObjCClass(StringRef Name) {
299 return Name.startswith("+") || Name.startswith("-");
302 static bool hasObjCCategory(StringRef Name) {
303 if (!isObjCClass(Name))
306 return Name.find(") ") != StringRef::npos;
309 static void getObjCClassCategory(StringRef In, StringRef &Class,
310 StringRef &Category) {
311 if (!hasObjCCategory(In)) {
312 Class = In.slice(In.find('[') + 1, In.find(' '));
317 Class = In.slice(In.find('[') + 1, In.find('('));
318 Category = In.slice(In.find('[') + 1, In.find(' '));
322 static StringRef getObjCMethodName(StringRef In) {
323 return In.slice(In.find(' ') + 1, In.find(']'));
326 // Helper for sorting sections into a stable output order.
327 static bool SectionSort(const MCSection *A, const MCSection *B) {
328 std::string LA = (A ? A->getLabelBeginName() : "");
329 std::string LB = (B ? B->getLabelBeginName() : "");
333 // Add the various names to the Dwarf accelerator table names.
334 // TODO: Determine whether or not we should add names for programs
335 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
336 // is only slightly different than the lookup of non-standard ObjC names.
337 static void addSubprogramNames(Unit *TheU, DISubprogram SP, DIE *Die) {
338 if (!SP.isDefinition())
340 TheU->addAccelName(SP.getName(), Die);
342 // If the linkage name is different than the name, go ahead and output
343 // that as well into the name table.
344 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
345 TheU->addAccelName(SP.getLinkageName(), Die);
347 // If this is an Objective-C selector name add it to the ObjC accelerator
349 if (isObjCClass(SP.getName())) {
350 StringRef Class, Category;
351 getObjCClassCategory(SP.getName(), Class, Category);
352 TheU->addAccelObjC(Class, Die);
354 TheU->addAccelObjC(Category, Die);
355 // Also add the base method name to the name table.
356 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
360 /// isSubprogramContext - Return true if Context is either a subprogram
361 /// or another context nested inside a subprogram.
362 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
365 DIDescriptor D(Context);
366 if (D.isSubprogram())
369 return isSubprogramContext(resolve(DIType(Context).getContext()));
373 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
374 // and DW_AT_high_pc attributes. If there are global variables in this
375 // scope then create and insert DIEs for these variables.
376 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, DISubprogram SP) {
377 DIE *SPDie = SPCU->getDIE(SP);
379 assert(SPDie && "Unable to find subprogram DIE!");
381 // If we're updating an abstract DIE, then we will be adding the children and
382 // object pointer later on. But what we don't want to do is process the
383 // concrete DIE twice.
384 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
385 // Pick up abstract subprogram DIE.
387 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
388 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
390 DISubprogram SPDecl = SP.getFunctionDeclaration();
391 if (!SPDecl.isSubprogram()) {
392 // There is not any need to generate specification DIE for a function
393 // defined at compile unit level. If a function is defined inside another
394 // function then gdb prefers the definition at top level and but does not
395 // expect specification DIE in parent function. So avoid creating
396 // specification DIE for a function defined inside a function.
397 DIScope SPContext = resolve(SP.getContext());
398 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
399 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
400 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
403 DICompositeType SPTy = SP.getType();
404 DIArray Args = SPTy.getTypeArray();
405 uint16_t SPTag = SPTy.getTag();
406 if (SPTag == dwarf::DW_TAG_subroutine_type)
407 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
409 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
410 DIType ATy(Args.getElement(i));
411 SPCU->addType(Arg, ATy);
412 if (ATy.isArtificial())
413 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
414 if (ATy.isObjectPointer())
415 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
417 DIE *SPDeclDie = SPDie;
418 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
419 *SPCU->getUnitDie());
420 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
425 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
426 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
428 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
429 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
430 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
432 // Add name to the name table, we do this here because we're guaranteed
433 // to have concrete versions of our DW_TAG_subprogram nodes.
434 addSubprogramNames(SPCU, SP, SPDie);
439 /// Check whether we should create a DIE for the given Scope, return true
440 /// if we don't create a DIE (the corresponding DIE is null).
441 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
442 if (Scope->isAbstractScope())
445 // We don't create a DIE if there is no Range.
446 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
450 if (Ranges.size() > 1)
453 // We don't create a DIE if we have a single Range and the end label
455 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
456 MCSymbol *End = getLabelAfterInsn(RI->second);
460 static void addSectionLabel(AsmPrinter *Asm, Unit *U, DIE *D,
461 dwarf::Attribute A, const MCSymbol *L,
462 const MCSymbol *Sec) {
463 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
464 U->addSectionLabel(D, A, L);
466 U->addSectionDelta(D, A, L, Sec);
469 void DwarfDebug::addScopeRangeList(CompileUnit *TheCU, DIE *ScopeDIE,
470 const SmallVectorImpl<InsnRange> &Range) {
471 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
472 // emitting it appropriately.
473 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
474 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
475 DwarfDebugRangeSectionSym);
477 RangeSpanList List(RangeSym);
478 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
481 RangeSpan Span(getLabelBeforeInsn(RI->first),
482 getLabelAfterInsn(RI->second));
483 List.addRange(llvm_move(Span));
486 // Add the range list to the set of ranges to be emitted.
487 TheCU->addRangeList(llvm_move(List));
490 // Construct new DW_TAG_lexical_block for this scope and attach
491 // DW_AT_low_pc/DW_AT_high_pc labels.
492 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
493 LexicalScope *Scope) {
494 if (isLexicalScopeDIENull(Scope))
497 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
498 if (Scope->isAbstractScope())
501 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
503 // If we have multiple ranges, emit them into the range section.
504 if (ScopeRanges.size() > 1) {
505 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
509 // Construct the address range for this DIE.
510 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
511 MCSymbol *Start = getLabelBeforeInsn(RI->first);
512 MCSymbol *End = getLabelAfterInsn(RI->second);
513 assert(End && "End label should not be null!");
515 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
516 assert(End->isDefined() && "Invalid end label for an inlined scope!");
518 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
519 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
524 // This scope represents inlined body of a function. Construct DIE to
525 // represent this concrete inlined copy of the function.
526 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
527 LexicalScope *Scope) {
528 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
529 assert(!ScopeRanges.empty() &&
530 "LexicalScope does not have instruction markers!");
532 if (!Scope->getScopeNode())
534 DIScope DS(Scope->getScopeNode());
535 DISubprogram InlinedSP = getDISubprogram(DS);
536 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
538 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
542 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
543 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
545 // If we have multiple ranges, emit them into the range section.
546 if (ScopeRanges.size() > 1)
547 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
549 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
550 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
551 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
553 if (StartLabel == 0 || EndLabel == 0)
554 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
556 assert(StartLabel->isDefined() &&
557 "Invalid starting label for an inlined scope!");
558 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
560 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
561 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
564 InlinedSubprogramDIEs.insert(OriginDIE);
566 // Add the call site information to the DIE.
567 DILocation DL(Scope->getInlinedAt());
568 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
569 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
570 TheCU->getUniqueID()));
571 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
573 // Add name to the name table, we do this here because we're guaranteed
574 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
575 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
580 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
581 SmallVectorImpl<DIE *> &Children) {
582 DIE *ObjectPointer = NULL;
584 // Collect arguments for current function.
585 if (LScopes.isCurrentFunctionScope(Scope))
586 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
587 if (DbgVariable *ArgDV = CurrentFnArguments[i])
589 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
590 Children.push_back(Arg);
591 if (ArgDV->isObjectPointer())
595 // Collect lexical scope children first.
596 const SmallVectorImpl<DbgVariable *> &Variables =
597 ScopeVariables.lookup(Scope);
598 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
599 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
600 Scope->isAbstractScope())) {
601 Children.push_back(Variable);
602 if (Variables[i]->isObjectPointer())
603 ObjectPointer = Variable;
605 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
606 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
607 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
608 Children.push_back(Nested);
609 return ObjectPointer;
612 // Construct a DIE for this scope.
613 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
614 if (!Scope || !Scope->getScopeNode())
617 DIScope DS(Scope->getScopeNode());
619 SmallVector<DIE *, 8> Children;
620 DIE *ObjectPointer = NULL;
621 bool ChildrenCreated = false;
623 // We try to create the scope DIE first, then the children DIEs. This will
624 // avoid creating un-used children then removing them later when we find out
625 // the scope DIE is null.
626 DIE *ScopeDIE = NULL;
627 if (Scope->getInlinedAt())
628 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
629 else if (DS.isSubprogram()) {
630 ProcessedSPNodes.insert(DS);
631 if (Scope->isAbstractScope()) {
632 ScopeDIE = TheCU->getDIE(DS);
633 // Note down abstract DIE.
635 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
637 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
639 // Early exit when we know the scope DIE is going to be null.
640 if (isLexicalScopeDIENull(Scope))
643 // We create children here when we know the scope DIE is not going to be
644 // null and the children will be added to the scope DIE.
645 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
646 ChildrenCreated = true;
648 // There is no need to emit empty lexical block DIE.
649 std::pair<ImportedEntityMap::const_iterator,
650 ImportedEntityMap::const_iterator> Range =
652 ScopesWithImportedEntities.begin(),
653 ScopesWithImportedEntities.end(),
654 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
656 if (Children.empty() && Range.first == Range.second)
658 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
659 assert(ScopeDIE && "Scope DIE should not be null.");
660 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
662 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
666 assert(Children.empty() &&
667 "We create children only when the scope DIE is not null.");
670 if (!ChildrenCreated)
671 // We create children when the scope DIE is not null.
672 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
675 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
678 ScopeDIE->addChild(*I);
680 if (DS.isSubprogram() && ObjectPointer != NULL)
681 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
686 // Look up the source id with the given directory and source file names.
687 // If none currently exists, create a new id and insert it in the
688 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
690 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
692 // If we use .loc in assembly, we can't separate .file entries according to
693 // compile units. Thus all files will belong to the default compile unit.
695 // FIXME: add a better feature test than hasRawTextSupport. Even better,
696 // extend .file to support this.
697 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
700 // If FE did not provide a file name, then assume stdin.
701 if (FileName.empty())
702 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
704 // TODO: this might not belong here. See if we can factor this better.
705 if (DirName == CompilationDir)
708 // FileIDCUMap stores the current ID for the given compile unit.
709 unsigned SrcId = FileIDCUMap[CUID] + 1;
711 // We look up the CUID/file/dir by concatenating them with a zero byte.
712 SmallString<128> NamePair;
713 NamePair += utostr(CUID);
716 NamePair += '\0'; // Zero bytes are not allowed in paths.
717 NamePair += FileName;
719 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
720 if (Ent.getValue() != SrcId)
721 return Ent.getValue();
723 FileIDCUMap[CUID] = SrcId;
724 // Print out a .file directive to specify files for .loc directives.
725 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
730 void DwarfDebug::addGnuPubAttributes(Unit *U, DIE *D) const {
731 if (!GenerateGnuPubSections)
734 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
735 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
736 DwarfGnuPubNamesSectionSym);
738 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
739 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
740 DwarfGnuPubTypesSectionSym);
743 // Create new CompileUnit for the given metadata node with tag
744 // DW_TAG_compile_unit.
745 CompileUnit *DwarfDebug::constructCompileUnit(DICompileUnit DIUnit) {
746 StringRef FN = DIUnit.getFilename();
747 CompilationDir = DIUnit.getDirectory();
749 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
750 CompileUnit *NewCU = new CompileUnit(InfoHolder.getUnits().size(), Die,
751 DIUnit, Asm, this, &InfoHolder);
752 InfoHolder.addUnit(NewCU);
755 FileIDCUMap[NewCU->getUniqueID()] = 0;
756 // Call this to emit a .file directive if it wasn't emitted for the source
757 // file this CU comes from yet.
758 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
760 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
761 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
762 DIUnit.getLanguage());
763 NewCU->addString(Die, dwarf::DW_AT_name, FN);
765 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
766 // into an entity. We're using 0 (or a NULL label) for this. For
767 // split dwarf it's in the skeleton CU so omit it here.
768 if (!useSplitDwarf())
769 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
771 // Define start line table label for each Compile Unit.
772 MCSymbol *LineTableStartSym =
773 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
774 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
775 NewCU->getUniqueID());
777 // Use a single line table if we are using .loc and generating assembly.
779 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
780 (NewCU->getUniqueID() == 0);
782 if (!useSplitDwarf()) {
783 // DW_AT_stmt_list is a offset of line number information for this
784 // compile unit in debug_line section. For split dwarf this is
785 // left in the skeleton CU and so not included.
786 // The line table entries are not always emitted in assembly, so it
787 // is not okay to use line_table_start here.
788 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
789 NewCU->addSectionLabel(
790 Die, dwarf::DW_AT_stmt_list,
791 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
792 : LineTableStartSym);
793 else if (UseTheFirstCU)
794 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
796 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list,
797 LineTableStartSym, DwarfLineSectionSym);
799 // If we're using split dwarf the compilation dir is going to be in the
800 // skeleton CU and so we don't need to duplicate it here.
801 if (!CompilationDir.empty())
802 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
804 addGnuPubAttributes(NewCU, Die);
807 if (DIUnit.isOptimized())
808 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
810 StringRef Flags = DIUnit.getFlags();
812 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
814 if (unsigned RVer = DIUnit.getRunTimeVersion())
815 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
816 dwarf::DW_FORM_data1, RVer);
822 useSplitDwarf() ? Asm->getObjFileLowering().getDwarfInfoDWOSection()
823 : Asm->getObjFileLowering().getDwarfInfoSection(),
824 // FIXME: This is subtle (using the info section even when
825 // this CU is in the dwo section) and necessary for the
826 // current arange code - ideally it should iterate
827 // skeleton units, not full units, if it's going to reference skeletons
828 DwarfInfoSectionSym);
830 CUMap.insert(std::make_pair(DIUnit, NewCU));
831 CUDieMap.insert(std::make_pair(Die, NewCU));
835 // Construct subprogram DIE.
836 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
837 // FIXME: We should only call this routine once, however, during LTO if a
838 // program is defined in multiple CUs we could end up calling it out of
839 // beginModule as we walk the CUs.
841 CompileUnit *&CURef = SPMap[N];
847 if (!SP.isDefinition())
848 // This is a method declaration which will be handled while constructing
852 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
854 // Expose as a global name.
855 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
858 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
860 DIImportedEntity Module(N);
861 if (!Module.Verify())
863 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
864 constructImportedEntityDIE(TheCU, Module, D);
867 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
869 DIImportedEntity Module(N);
870 if (!Module.Verify())
872 return constructImportedEntityDIE(TheCU, Module, Context);
875 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
876 const DIImportedEntity &Module,
878 assert(Module.Verify() &&
879 "Use one of the MDNode * overloads to handle invalid metadata");
880 assert(Context && "Should always have a context for an imported_module");
881 DIE *IMDie = new DIE(Module.getTag());
882 TheCU->insertDIE(Module, IMDie);
884 DIDescriptor Entity = Module.getEntity();
885 if (Entity.isNameSpace())
886 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
887 else if (Entity.isSubprogram())
888 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
889 else if (Entity.isType())
890 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
892 EntityDie = TheCU->getDIE(Entity);
893 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
894 Module.getContext().getDirectory(),
895 TheCU->getUniqueID());
896 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
897 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
898 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
899 StringRef Name = Module.getName();
901 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
902 Context->addChild(IMDie);
905 // Emit all Dwarf sections that should come prior to the content. Create
906 // global DIEs and emit initial debug info sections. This is invoked by
907 // the target AsmPrinter.
908 void DwarfDebug::beginModule() {
909 if (DisableDebugInfoPrinting)
912 const Module *M = MMI->getModule();
914 // If module has named metadata anchors then use them, otherwise scan the
915 // module using debug info finder to collect debug info.
916 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
919 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
921 // Emit initial sections so we can reference labels later.
924 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
925 DICompileUnit CUNode(CU_Nodes->getOperand(i));
926 CompileUnit *CU = constructCompileUnit(CUNode);
927 DIArray ImportedEntities = CUNode.getImportedEntities();
928 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
929 ScopesWithImportedEntities.push_back(std::make_pair(
930 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
931 ImportedEntities.getElement(i)));
932 std::sort(ScopesWithImportedEntities.begin(),
933 ScopesWithImportedEntities.end(), less_first());
934 DIArray GVs = CUNode.getGlobalVariables();
935 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
936 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
937 DIArray SPs = CUNode.getSubprograms();
938 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
939 constructSubprogramDIE(CU, SPs.getElement(i));
940 DIArray EnumTypes = CUNode.getEnumTypes();
941 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
942 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
943 DIArray RetainedTypes = CUNode.getRetainedTypes();
944 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
945 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
946 // Emit imported_modules last so that the relevant context is already
948 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
949 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
952 // Tell MMI that we have debug info.
953 MMI->setDebugInfoAvailability(true);
955 // Prime section data.
956 SectionMap[Asm->getObjFileLowering().getTextSection()];
959 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
960 void DwarfDebug::computeInlinedDIEs() {
961 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
962 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
963 AE = InlinedSubprogramDIEs.end();
966 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
968 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
969 AE = AbstractSPDies.end();
971 DIE *ISP = AI->second;
972 if (InlinedSubprogramDIEs.count(ISP))
974 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
978 // Collect info for variables that were optimized out.
979 void DwarfDebug::collectDeadVariables() {
980 const Module *M = MMI->getModule();
982 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
983 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
984 DICompileUnit TheCU(CU_Nodes->getOperand(i));
985 DIArray Subprograms = TheCU.getSubprograms();
986 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
987 DISubprogram SP(Subprograms.getElement(i));
988 if (ProcessedSPNodes.count(SP) != 0)
990 if (!SP.isSubprogram())
992 if (!SP.isDefinition())
994 DIArray Variables = SP.getVariables();
995 if (Variables.getNumElements() == 0)
998 // Construct subprogram DIE and add variables DIEs.
999 CompileUnit *SPCU = static_cast<CompileUnit *>(CUMap.lookup(TheCU));
1000 assert(SPCU && "Unable to find Compile Unit!");
1001 // FIXME: See the comment in constructSubprogramDIE about duplicate
1003 constructSubprogramDIE(SPCU, SP);
1004 DIE *SPDIE = SPCU->getDIE(SP);
1005 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1006 DIVariable DV(Variables.getElement(vi));
1007 if (!DV.isVariable())
1009 DbgVariable NewVar(DV, NULL, this);
1010 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1011 SPDIE->addChild(VariableDIE);
1018 // Type Signature [7.27] and ODR Hash code.
1020 /// \brief Grabs the string in whichever attribute is passed in and returns
1021 /// a reference to it. Returns "" if the attribute doesn't exist.
1022 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1023 DIEValue *V = Die->findAttribute(Attr);
1025 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1026 return S->getString();
1028 return StringRef("");
1031 /// Return true if the current DIE is contained within an anonymous namespace.
1032 static bool isContainedInAnonNamespace(DIE *Die) {
1033 DIE *Parent = Die->getParent();
1036 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1037 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1039 Parent = Parent->getParent();
1045 /// Test if the current CU language is C++ and that we have
1046 /// a named type that is not contained in an anonymous namespace.
1047 static bool shouldAddODRHash(TypeUnit *CU, DIE *Die) {
1048 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1049 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1050 !isContainedInAnonNamespace(Die);
1053 void DwarfDebug::finalizeModuleInfo() {
1054 // Collect info for variables that were optimized out.
1055 collectDeadVariables();
1057 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1058 computeInlinedDIEs();
1060 // Handle anything that needs to be done on a per-unit basis after
1061 // all other generation.
1062 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
1063 E = getUnits().end();
1066 // Emit DW_AT_containing_type attribute to connect types with their
1067 // vtable holding type.
1068 TheU->constructContainingTypeDIEs();
1070 // If we're splitting the dwarf out now that we've got the entire
1071 // CU then construct a skeleton CU based upon it.
1072 if (useSplitDwarf() &&
1073 TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1075 if (GenerateCUHash) {
1077 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1079 // This should be a unique identifier when we want to build .dwp files.
1080 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1081 dwarf::DW_FORM_data8, ID);
1082 // Now construct the skeleton CU associated.
1083 CompileUnit *SkCU = constructSkeletonCU(static_cast<CompileUnit *>(TheU));
1084 // This should be a unique identifier when we want to build .dwp files.
1085 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1086 dwarf::DW_FORM_data8, ID);
1090 // Compute DIE offsets and sizes.
1091 InfoHolder.computeSizeAndOffsets();
1092 if (useSplitDwarf())
1093 SkeletonHolder.computeSizeAndOffsets();
1096 void DwarfDebug::endSections() {
1097 // Filter labels by section.
1098 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1099 const SymbolCU &SCU = ArangeLabels[n];
1100 if (SCU.Sym->isInSection()) {
1101 // Make a note of this symbol and it's section.
1102 const MCSection *Section = &SCU.Sym->getSection();
1103 if (!Section->getKind().isMetadata())
1104 SectionMap[Section].push_back(SCU);
1106 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1107 // appear in the output. This sucks as we rely on sections to build
1108 // arange spans. We can do it without, but it's icky.
1109 SectionMap[NULL].push_back(SCU);
1113 // Build a list of sections used.
1114 std::vector<const MCSection *> Sections;
1115 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1117 const MCSection *Section = it->first;
1118 Sections.push_back(Section);
1121 // Sort the sections into order.
1122 // This is only done to ensure consistent output order across different runs.
1123 std::sort(Sections.begin(), Sections.end(), SectionSort);
1125 // Add terminating symbols for each section.
1126 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1127 const MCSection *Section = Sections[ID];
1128 MCSymbol *Sym = NULL;
1131 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1132 // if we know the section name up-front. For user-created sections, the
1134 // label may not be valid to use as a label. (section names can use a
1136 // set of characters on some systems)
1137 Sym = Asm->GetTempSymbol("debug_end", ID);
1138 Asm->OutStreamer.SwitchSection(Section);
1139 Asm->OutStreamer.EmitLabel(Sym);
1142 // Insert a final terminator.
1143 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1147 // Emit all Dwarf sections that should come after the content.
1148 void DwarfDebug::endModule() {
1155 // End any existing sections.
1156 // TODO: Does this need to happen?
1159 // Finalize the debug info for the module.
1160 finalizeModuleInfo();
1164 // Emit all the DIEs into a debug info section.
1167 // Corresponding abbreviations into a abbrev section.
1168 emitAbbreviations();
1170 // Emit info into a debug loc section.
1173 // Emit info into a debug aranges section.
1176 // Emit info into a debug ranges section.
1179 // Emit info into a debug macinfo section.
1182 if (useSplitDwarf()) {
1185 emitDebugAbbrevDWO();
1186 // Emit DWO addresses.
1187 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1190 // Emit info into the dwarf accelerator table sections.
1191 if (useDwarfAccelTables()) {
1194 emitAccelNamespaces();
1198 // Emit the pubnames and pubtypes sections if requested.
1199 if (HasDwarfPubSections) {
1200 emitDebugPubNames(GenerateGnuPubSections);
1201 emitDebugPubTypes(GenerateGnuPubSections);
1207 // Reset these for the next Module if we have one.
1211 // Find abstract variable, if any, associated with Var.
1212 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1213 DebugLoc ScopeLoc) {
1214 LLVMContext &Ctx = DV->getContext();
1215 // More then one inlined variable corresponds to one abstract variable.
1216 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1217 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1219 return AbsDbgVariable;
1221 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1225 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1226 addScopeVariable(Scope, AbsDbgVariable);
1227 AbstractVariables[Var] = AbsDbgVariable;
1228 return AbsDbgVariable;
1231 // If Var is a current function argument then add it to CurrentFnArguments list.
1232 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1233 if (!LScopes.isCurrentFunctionScope(Scope))
1235 DIVariable DV = Var->getVariable();
1236 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1238 unsigned ArgNo = DV.getArgNumber();
1242 size_t Size = CurrentFnArguments.size();
1244 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1245 // llvm::Function argument size is not good indicator of how many
1246 // arguments does the function have at source level.
1248 CurrentFnArguments.resize(ArgNo * 2);
1249 CurrentFnArguments[ArgNo - 1] = Var;
1253 // Collect variable information from side table maintained by MMI.
1254 void DwarfDebug::collectVariableInfoFromMMITable(
1255 SmallPtrSet<const MDNode *, 16> &Processed) {
1256 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1257 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1260 const MDNode *Var = VI->first;
1263 Processed.insert(Var);
1265 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1267 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1269 // If variable scope is not found then skip this variable.
1273 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1274 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1275 RegVar->setFrameIndex(VP.first);
1276 if (!addCurrentFnArgument(RegVar, Scope))
1277 addScopeVariable(Scope, RegVar);
1279 AbsDbgVariable->setFrameIndex(VP.first);
1283 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1285 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1286 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1287 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1288 MI->getOperand(0).getReg() &&
1289 (MI->getOperand(1).isImm() ||
1290 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1293 // Get .debug_loc entry for the instruction range starting at MI.
1294 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1295 const MCSymbol *FLabel,
1296 const MCSymbol *SLabel,
1297 const MachineInstr *MI) {
1298 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1300 assert(MI->getNumOperands() == 3);
1301 if (MI->getOperand(0).isReg()) {
1302 MachineLocation MLoc;
1303 // If the second operand is an immediate, this is a
1304 // register-indirect address.
1305 if (!MI->getOperand(1).isImm())
1306 MLoc.set(MI->getOperand(0).getReg());
1308 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1309 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1311 if (MI->getOperand(0).isImm())
1312 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1313 if (MI->getOperand(0).isFPImm())
1314 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1315 if (MI->getOperand(0).isCImm())
1316 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1318 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1321 // Find variables for each lexical scope.
1323 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1325 // Grab the variable info that was squirreled away in the MMI side-table.
1326 collectVariableInfoFromMMITable(Processed);
1328 for (SmallVectorImpl<const MDNode *>::const_iterator
1329 UVI = UserVariables.begin(),
1330 UVE = UserVariables.end();
1331 UVI != UVE; ++UVI) {
1332 const MDNode *Var = *UVI;
1333 if (Processed.count(Var))
1336 // History contains relevant DBG_VALUE instructions for Var and instructions
1338 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1339 if (History.empty())
1341 const MachineInstr *MInsn = History.front();
1344 LexicalScope *Scope = NULL;
1345 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1346 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1347 Scope = LScopes.getCurrentFunctionScope();
1348 else if (MDNode *IA = DV.getInlinedAt())
1349 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1351 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1352 // If variable scope is not found then skip this variable.
1356 Processed.insert(DV);
1357 assert(MInsn->isDebugValue() && "History must begin with debug value");
1358 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1359 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1360 if (!addCurrentFnArgument(RegVar, Scope))
1361 addScopeVariable(Scope, RegVar);
1363 AbsVar->setMInsn(MInsn);
1365 // Simplify ranges that are fully coalesced.
1366 if (History.size() <= 1 ||
1367 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1368 RegVar->setMInsn(MInsn);
1372 // Handle multiple DBG_VALUE instructions describing one variable.
1373 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1375 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1376 HI = History.begin(),
1379 const MachineInstr *Begin = *HI;
1380 assert(Begin->isDebugValue() && "Invalid History entry");
1382 // Check if DBG_VALUE is truncating a range.
1383 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1384 !Begin->getOperand(0).getReg())
1387 // Compute the range for a register location.
1388 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1389 const MCSymbol *SLabel = 0;
1392 // If Begin is the last instruction in History then its value is valid
1393 // until the end of the function.
1394 SLabel = FunctionEndSym;
1396 const MachineInstr *End = HI[1];
1397 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1398 << "\t" << *Begin << "\t" << *End << "\n");
1399 if (End->isDebugValue())
1400 SLabel = getLabelBeforeInsn(End);
1402 // End is a normal instruction clobbering the range.
1403 SLabel = getLabelAfterInsn(End);
1404 assert(SLabel && "Forgot label after clobber instruction");
1409 // The value is valid until the next DBG_VALUE or clobber.
1410 DotDebugLocEntries.push_back(
1411 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1413 DotDebugLocEntries.push_back(DotDebugLocEntry());
1416 // Collect info for variables that were optimized out.
1417 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1418 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1419 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1420 DIVariable DV(Variables.getElement(i));
1421 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1423 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1424 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1428 // Return Label preceding the instruction.
1429 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1430 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1431 assert(Label && "Didn't insert label before instruction");
1435 // Return Label immediately following the instruction.
1436 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1437 return LabelsAfterInsn.lookup(MI);
1440 // Process beginning of an instruction.
1441 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1444 // Check if source location changes, but ignore DBG_VALUE locations.
1445 if (!MI->isDebugValue()) {
1446 DebugLoc DL = MI->getDebugLoc();
1447 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1450 if (DL == PrologEndLoc) {
1451 Flags |= DWARF2_FLAG_PROLOGUE_END;
1452 PrologEndLoc = DebugLoc();
1454 if (PrologEndLoc.isUnknown())
1455 Flags |= DWARF2_FLAG_IS_STMT;
1457 if (!DL.isUnknown()) {
1458 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1459 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1461 recordSourceLine(0, 0, 0, 0);
1465 // Insert labels where requested.
1466 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1467 LabelsBeforeInsn.find(MI);
1470 if (I == LabelsBeforeInsn.end())
1473 // Label already assigned.
1478 PrevLabel = MMI->getContext().CreateTempSymbol();
1479 Asm->OutStreamer.EmitLabel(PrevLabel);
1481 I->second = PrevLabel;
1484 // Process end of an instruction.
1485 void DwarfDebug::endInstruction() {
1487 // Don't create a new label after DBG_VALUE instructions.
1488 // They don't generate code.
1489 if (!CurMI->isDebugValue())
1492 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1493 LabelsAfterInsn.find(CurMI);
1497 if (I == LabelsAfterInsn.end())
1500 // Label already assigned.
1504 // We need a label after this instruction.
1506 PrevLabel = MMI->getContext().CreateTempSymbol();
1507 Asm->OutStreamer.EmitLabel(PrevLabel);
1509 I->second = PrevLabel;
1512 // Each LexicalScope has first instruction and last instruction to mark
1513 // beginning and end of a scope respectively. Create an inverse map that list
1514 // scopes starts (and ends) with an instruction. One instruction may start (or
1515 // end) multiple scopes. Ignore scopes that are not reachable.
1516 void DwarfDebug::identifyScopeMarkers() {
1517 SmallVector<LexicalScope *, 4> WorkList;
1518 WorkList.push_back(LScopes.getCurrentFunctionScope());
1519 while (!WorkList.empty()) {
1520 LexicalScope *S = WorkList.pop_back_val();
1522 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1523 if (!Children.empty())
1524 for (SmallVectorImpl<LexicalScope *>::const_iterator
1525 SI = Children.begin(),
1526 SE = Children.end();
1528 WorkList.push_back(*SI);
1530 if (S->isAbstractScope())
1533 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1536 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1539 assert(RI->first && "InsnRange does not have first instruction!");
1540 assert(RI->second && "InsnRange does not have second instruction!");
1541 requestLabelBeforeInsn(RI->first);
1542 requestLabelAfterInsn(RI->second);
1547 // Get MDNode for DebugLoc's scope.
1548 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1549 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1550 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1551 return DL.getScope(Ctx);
1554 // Walk up the scope chain of given debug loc and find line number info
1555 // for the function.
1556 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1557 const MDNode *Scope = getScopeNode(DL, Ctx);
1558 DISubprogram SP = getDISubprogram(Scope);
1559 if (SP.isSubprogram()) {
1560 // Check for number of operands since the compatibility is
1562 if (SP->getNumOperands() > 19)
1563 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1565 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1571 // Gather pre-function debug information. Assumes being called immediately
1572 // after the function entry point has been emitted.
1573 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 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1803 // though the beginFunction may not be called at all.
1804 // We should handle both cases.
1808 assert(CurFn == MF);
1811 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1816 // Define end label for subprogram.
1817 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1818 // Assumes in correct section after the entry point.
1819 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1820 // Set DwarfCompileUnitID in MCContext to default value.
1821 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1823 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1824 collectVariableInfo(ProcessedVars);
1826 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1827 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1828 assert(TheCU && "Unable to find compile unit!");
1830 // Construct abstract scopes.
1831 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1832 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1833 LexicalScope *AScope = AList[i];
1834 DISubprogram SP(AScope->getScopeNode());
1835 if (SP.isSubprogram()) {
1836 // Collect info for variables that were optimized out.
1837 DIArray Variables = SP.getVariables();
1838 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1839 DIVariable DV(Variables.getElement(i));
1840 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1842 // Check that DbgVariable for DV wasn't created earlier, when
1843 // findAbstractVariable() was called for inlined instance of DV.
1844 LLVMContext &Ctx = DV->getContext();
1845 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1846 if (AbstractVariables.lookup(CleanDV))
1848 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1849 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1852 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1853 constructScopeDIE(TheCU, AScope);
1856 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1858 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1859 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1862 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1863 E = ScopeVariables.end();
1865 DeleteContainerPointers(I->second);
1866 ScopeVariables.clear();
1867 DeleteContainerPointers(CurrentFnArguments);
1868 UserVariables.clear();
1870 AbstractVariables.clear();
1871 LabelsBeforeInsn.clear();
1872 LabelsAfterInsn.clear();
1877 // Register a source line with debug info. Returns the unique label that was
1878 // emitted and which provides correspondence to the source line list.
1879 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1885 DIDescriptor Scope(S);
1887 if (Scope.isCompileUnit()) {
1888 DICompileUnit CU(S);
1889 Fn = CU.getFilename();
1890 Dir = CU.getDirectory();
1891 } else if (Scope.isFile()) {
1893 Fn = F.getFilename();
1894 Dir = F.getDirectory();
1895 } else if (Scope.isSubprogram()) {
1897 Fn = SP.getFilename();
1898 Dir = SP.getDirectory();
1899 } else if (Scope.isLexicalBlockFile()) {
1900 DILexicalBlockFile DBF(S);
1901 Fn = DBF.getFilename();
1902 Dir = DBF.getDirectory();
1903 } else if (Scope.isLexicalBlock()) {
1904 DILexicalBlock DB(S);
1905 Fn = DB.getFilename();
1906 Dir = DB.getDirectory();
1908 llvm_unreachable("Unexpected scope info");
1910 Src = getOrCreateSourceID(
1911 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1913 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1916 //===----------------------------------------------------------------------===//
1918 //===----------------------------------------------------------------------===//
1920 // Compute the size and offset of a DIE. The offset is relative to start of the
1921 // CU. It returns the offset after laying out the DIE.
1922 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1923 // Get the children.
1924 const std::vector<DIE *> &Children = Die->getChildren();
1926 // Record the abbreviation.
1927 assignAbbrevNumber(Die->getAbbrev());
1929 // Get the abbreviation for this DIE.
1930 const DIEAbbrev &Abbrev = Die->getAbbrev();
1933 Die->setOffset(Offset);
1935 // Start the size with the size of abbreviation code.
1936 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1938 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1939 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1941 // Size the DIE attribute values.
1942 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1943 // Size attribute value.
1944 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1946 // Size the DIE children if any.
1947 if (!Children.empty()) {
1948 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1949 "Children flag not set");
1951 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1952 Offset = computeSizeAndOffset(Children[j], Offset);
1954 // End of children marker.
1955 Offset += sizeof(int8_t);
1958 Die->setSize(Offset - Die->getOffset());
1962 // Compute the size and offset for each DIE.
1963 void DwarfFile::computeSizeAndOffsets() {
1964 // Offset from the first CU in the debug info section is 0 initially.
1965 unsigned SecOffset = 0;
1967 // Iterate over each compile unit and set the size and offsets for each
1968 // DIE within each compile unit. All offsets are CU relative.
1969 for (SmallVectorImpl<Unit *>::const_iterator I = CUs.begin(), E = CUs.end();
1971 (*I)->setDebugInfoOffset(SecOffset);
1973 // CU-relative offset is reset to 0 here.
1974 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1975 (*I)->getHeaderSize(); // Unit-specific headers
1977 // EndOffset here is CU-relative, after laying out
1978 // all of the CU DIE.
1979 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1980 SecOffset += EndOffset;
1984 // Emit initial Dwarf sections with a label at the start of each one.
1985 void DwarfDebug::emitSectionLabels() {
1986 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1988 // Dwarf sections base addresses.
1989 DwarfInfoSectionSym =
1990 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1991 DwarfAbbrevSectionSym =
1992 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1993 if (useSplitDwarf())
1994 DwarfAbbrevDWOSectionSym = emitSectionSym(
1995 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1996 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1998 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1999 emitSectionSym(Asm, MacroInfo);
2001 DwarfLineSectionSym =
2002 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2003 emitSectionSym(Asm, TLOF.getDwarfLocSection());
2004 if (GenerateGnuPubSections) {
2005 DwarfGnuPubNamesSectionSym =
2006 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2007 DwarfGnuPubTypesSectionSym =
2008 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2009 } else if (HasDwarfPubSections) {
2010 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2011 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2014 DwarfStrSectionSym =
2015 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2016 if (useSplitDwarf()) {
2017 DwarfStrDWOSectionSym =
2018 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2019 DwarfAddrSectionSym =
2020 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2022 DwarfDebugRangeSectionSym =
2023 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2025 DwarfDebugLocSectionSym =
2026 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2028 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2029 emitSectionSym(Asm, TLOF.getDataSection());
2032 // Recursively emits a debug information entry.
2033 void DwarfDebug::emitDIE(DIE *Die) {
2034 // Get the abbreviation for this DIE.
2035 const DIEAbbrev &Abbrev = Die->getAbbrev();
2037 // Emit the code (index) for the abbreviation.
2038 if (Asm->isVerbose())
2039 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2040 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2041 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2042 dwarf::TagString(Abbrev.getTag()));
2043 Asm->EmitULEB128(Abbrev.getNumber());
2045 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2046 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2048 // Emit the DIE attribute values.
2049 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2050 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2051 dwarf::Form Form = AbbrevData[i].getForm();
2052 assert(Form && "Too many attributes for DIE (check abbreviation)");
2054 if (Asm->isVerbose())
2055 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2058 case dwarf::DW_AT_abstract_origin:
2059 case dwarf::DW_AT_type:
2060 case dwarf::DW_AT_friend:
2061 case dwarf::DW_AT_specification:
2062 case dwarf::DW_AT_import:
2063 case dwarf::DW_AT_containing_type: {
2064 DIEEntry *E = cast<DIEEntry>(Values[i]);
2065 DIE *Origin = E->getEntry();
2066 unsigned Addr = Origin->getOffset();
2067 if (Form == dwarf::DW_FORM_ref_addr) {
2068 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2069 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2070 // section. Origin->getOffset() returns the offset from start of the
2072 CompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2073 assert(CU && "CUDie should belong to a CU.");
2074 Addr += CU->getDebugInfoOffset();
2075 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2076 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2077 DIEEntry::getRefAddrSize(Asm));
2079 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2080 CU->getSectionSym(),
2081 DIEEntry::getRefAddrSize(Asm));
2083 // Make sure Origin belong to the same CU.
2084 assert(Die->getUnit() == Origin->getUnit() &&
2085 "The referenced DIE should belong to the same CU in ref4");
2086 Asm->EmitInt32(Addr);
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]);
2123 Asm->OutStreamer.AddComment("End Of Children Mark");
2128 // Emit the various dwarf units to the unit section USection with
2129 // the abbreviations going into ASection.
2130 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2131 const MCSymbol *ASectionSym) {
2132 for (SmallVectorImpl<Unit *>::iterator I = CUs.begin(), E = CUs.end(); I != E;
2135 DIE *Die = TheU->getUnitDie();
2136 const MCSection *USection = TheU->getSection();
2137 Asm->OutStreamer.SwitchSection(USection);
2139 // Emit the compile units header.
2140 Asm->OutStreamer.EmitLabel(
2141 Asm->GetTempSymbol(USection->getLabelBeginName(), TheU->getUniqueID()));
2143 // Emit size of content not including length itself
2144 Asm->OutStreamer.AddComment("Length of Unit");
2145 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2147 TheU->emitHeader(ASection, ASectionSym);
2150 Asm->OutStreamer.EmitLabel(
2151 Asm->GetTempSymbol(USection->getLabelEndName(), TheU->getUniqueID()));
2155 // Emit the debug info section.
2156 void DwarfDebug::emitDebugInfo() {
2157 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2159 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2160 DwarfAbbrevSectionSym);
2163 // Emit the abbreviation section.
2164 void DwarfDebug::emitAbbreviations() {
2165 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2167 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2170 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2171 // Check to see if it is worth the effort.
2172 if (!Abbreviations.empty()) {
2173 // Start the debug abbrev section.
2174 Asm->OutStreamer.SwitchSection(Section);
2176 // For each abbrevation.
2177 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2178 // Get abbreviation data
2179 const DIEAbbrev *Abbrev = Abbreviations[i];
2181 // Emit the abbrevations code (base 1 index.)
2182 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2184 // Emit the abbreviations data.
2188 // Mark end of abbreviations.
2189 Asm->EmitULEB128(0, "EOM(3)");
2193 // Emit the last address of the section and the end of the line matrix.
2194 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2195 // Define last address of section.
2196 Asm->OutStreamer.AddComment("Extended Op");
2199 Asm->OutStreamer.AddComment("Op size");
2200 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2201 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2202 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2204 Asm->OutStreamer.AddComment("Section end label");
2206 Asm->OutStreamer.EmitSymbolValue(
2207 Asm->GetTempSymbol("section_end", SectionEnd),
2208 Asm->getDataLayout().getPointerSize());
2210 // Mark end of matrix.
2211 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2217 // Emit visible names into a hashed accelerator table section.
2218 void DwarfDebug::emitAccelNames() {
2220 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2221 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2222 E = getUnits().end();
2225 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2226 for (StringMap<std::vector<const DIE *> >::const_iterator
2230 StringRef Name = GI->getKey();
2231 const std::vector<const DIE *> &Entities = GI->second;
2232 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2233 DE = Entities.end();
2235 AT.AddName(Name, *DI);
2239 AT.FinalizeTable(Asm, "Names");
2240 Asm->OutStreamer.SwitchSection(
2241 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2242 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2243 Asm->OutStreamer.EmitLabel(SectionBegin);
2245 // Emit the full data.
2246 AT.Emit(Asm, SectionBegin, &InfoHolder);
2249 // Emit objective C classes and categories into a hashed accelerator table
2251 void DwarfDebug::emitAccelObjC() {
2253 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2254 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2255 E = getUnits().end();
2258 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2259 for (StringMap<std::vector<const DIE *> >::const_iterator
2263 StringRef Name = GI->getKey();
2264 const std::vector<const DIE *> &Entities = GI->second;
2265 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2266 DE = Entities.end();
2268 AT.AddName(Name, *DI);
2272 AT.FinalizeTable(Asm, "ObjC");
2273 Asm->OutStreamer.SwitchSection(
2274 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2275 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2276 Asm->OutStreamer.EmitLabel(SectionBegin);
2278 // Emit the full data.
2279 AT.Emit(Asm, SectionBegin, &InfoHolder);
2282 // Emit namespace dies into a hashed accelerator table.
2283 void DwarfDebug::emitAccelNamespaces() {
2285 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2286 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2287 E = getUnits().end();
2290 const StringMap<std::vector<const DIE *> > &Names =
2291 TheU->getAccelNamespace();
2292 for (StringMap<std::vector<const DIE *> >::const_iterator
2296 StringRef Name = GI->getKey();
2297 const std::vector<const DIE *> &Entities = GI->second;
2298 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2299 DE = Entities.end();
2301 AT.AddName(Name, *DI);
2305 AT.FinalizeTable(Asm, "namespac");
2306 Asm->OutStreamer.SwitchSection(
2307 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2308 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2309 Asm->OutStreamer.EmitLabel(SectionBegin);
2311 // Emit the full data.
2312 AT.Emit(Asm, SectionBegin, &InfoHolder);
2315 // Emit type dies into a hashed accelerator table.
2316 void DwarfDebug::emitAccelTypes() {
2317 std::vector<DwarfAccelTable::Atom> Atoms;
2319 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2321 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2323 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2324 DwarfAccelTable AT(Atoms);
2325 for (SmallVectorImpl<Unit *>::const_iterator I = getUnits().begin(),
2326 E = getUnits().end();
2329 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2330 TheU->getAccelTypes();
2332 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2336 StringRef Name = GI->getKey();
2337 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2339 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2340 DI = Entities.begin(),
2341 DE = Entities.end();
2343 AT.AddName(Name, DI->first, DI->second);
2347 AT.FinalizeTable(Asm, "types");
2348 Asm->OutStreamer.SwitchSection(
2349 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2350 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2351 Asm->OutStreamer.EmitLabel(SectionBegin);
2353 // Emit the full data.
2354 AT.Emit(Asm, SectionBegin, &InfoHolder);
2357 // Public name handling.
2358 // The format for the various pubnames:
2360 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2361 // for the DIE that is named.
2363 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2364 // into the CU and the index value is computed according to the type of value
2365 // for the DIE that is named.
2367 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2368 // it's the offset within the debug_info/debug_types dwo section, however, the
2369 // reference in the pubname header doesn't change.
2371 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2372 static dwarf::PubIndexEntryDescriptor computeIndexValue(Unit *CU,
2374 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2376 // We could have a specification DIE that has our most of our knowledge,
2377 // look for that now.
2378 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2380 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2381 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2382 Linkage = dwarf::GIEL_EXTERNAL;
2383 } else if (Die->findAttribute(dwarf::DW_AT_external))
2384 Linkage = dwarf::GIEL_EXTERNAL;
2386 switch (Die->getTag()) {
2387 case dwarf::DW_TAG_class_type:
2388 case dwarf::DW_TAG_structure_type:
2389 case dwarf::DW_TAG_union_type:
2390 case dwarf::DW_TAG_enumeration_type:
2391 return dwarf::PubIndexEntryDescriptor(
2392 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2393 ? dwarf::GIEL_STATIC
2394 : dwarf::GIEL_EXTERNAL);
2395 case dwarf::DW_TAG_typedef:
2396 case dwarf::DW_TAG_base_type:
2397 case dwarf::DW_TAG_subrange_type:
2398 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2399 case dwarf::DW_TAG_namespace:
2400 return dwarf::GIEK_TYPE;
2401 case dwarf::DW_TAG_subprogram:
2402 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2403 case dwarf::DW_TAG_constant:
2404 case dwarf::DW_TAG_variable:
2405 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2406 case dwarf::DW_TAG_enumerator:
2407 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2408 dwarf::GIEL_STATIC);
2410 return dwarf::GIEK_NONE;
2414 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2416 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2417 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2418 const MCSection *PSec =
2419 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2420 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2422 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2423 const SmallVectorImpl<Unit *> &Units = Holder.getUnits();
2424 for (unsigned i = 0; i != Units.size(); ++i) {
2425 Unit *TheU = Units[i];
2426 unsigned ID = TheU->getUniqueID();
2428 // Start the dwarf pubnames section.
2429 Asm->OutStreamer.SwitchSection(PSec);
2431 // Emit a label so we can reference the beginning of this pubname section.
2433 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2436 Asm->OutStreamer.AddComment("Length of Public Names Info");
2437 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2438 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2439 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2441 Asm->OutStreamer.EmitLabel(BeginLabel);
2443 Asm->OutStreamer.AddComment("DWARF Version");
2444 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2446 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2447 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2448 TheU->getSectionSym());
2450 Asm->OutStreamer.AddComment("Compilation Unit Length");
2451 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2452 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2455 // Emit the pubnames for this compilation unit.
2456 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2457 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2460 const char *Name = GI->getKeyData();
2461 const DIE *Entity = GI->second;
2463 Asm->OutStreamer.AddComment("DIE offset");
2464 Asm->EmitInt32(Entity->getOffset());
2467 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2468 Asm->OutStreamer.AddComment(
2469 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2470 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2471 Asm->EmitInt8(Desc.toBits());
2474 Asm->OutStreamer.AddComment("External Name");
2475 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2478 Asm->OutStreamer.AddComment("End Mark");
2480 Asm->OutStreamer.EmitLabel(EndLabel);
2484 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2485 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2486 const MCSection *PSec =
2487 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2488 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2490 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2491 const SmallVectorImpl<Unit *> &Units = Holder.getUnits();
2492 for (unsigned i = 0; i != Units.size(); ++i) {
2493 Unit *TheU = Units[i];
2494 unsigned ID = TheU->getUniqueID();
2496 // Start the dwarf pubtypes section.
2497 Asm->OutStreamer.SwitchSection(PSec);
2499 // Emit a label so we can reference the beginning of this pubtype section.
2501 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2504 Asm->OutStreamer.AddComment("Length of Public Types Info");
2505 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2506 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2507 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2509 Asm->OutStreamer.EmitLabel(BeginLabel);
2511 Asm->OutStreamer.AddComment("DWARF Version");
2512 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2514 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2515 Asm->EmitSectionOffset(
2516 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()),
2517 TheU->getSectionSym());
2519 Asm->OutStreamer.AddComment("Compilation Unit Length");
2520 Asm->EmitLabelDifference(
2521 Asm->GetTempSymbol(ISec->getLabelEndName(), TheU->getUniqueID()),
2522 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheU->getUniqueID()), 4);
2524 // Emit the pubtypes.
2525 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2526 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2529 const char *Name = GI->getKeyData();
2530 const DIE *Entity = GI->second;
2532 Asm->OutStreamer.AddComment("DIE offset");
2533 Asm->EmitInt32(Entity->getOffset());
2536 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2537 Asm->OutStreamer.AddComment(
2538 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2539 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2540 Asm->EmitInt8(Desc.toBits());
2543 Asm->OutStreamer.AddComment("External Name");
2545 // Emit the name with a terminating null byte.
2546 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2549 Asm->OutStreamer.AddComment("End Mark");
2551 Asm->OutStreamer.EmitLabel(EndLabel);
2555 // Emit strings into a string section.
2556 void DwarfFile::emitStrings(const MCSection *StrSection,
2557 const MCSection *OffsetSection = NULL,
2558 const MCSymbol *StrSecSym = NULL) {
2560 if (StringPool.empty())
2563 // Start the dwarf str section.
2564 Asm->OutStreamer.SwitchSection(StrSection);
2566 // Get all of the string pool entries and put them in an array by their ID so
2567 // we can sort them.
2569 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2572 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2573 I = StringPool.begin(),
2574 E = StringPool.end();
2576 Entries.push_back(std::make_pair(I->second.second, &*I));
2578 array_pod_sort(Entries.begin(), Entries.end());
2580 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2581 // Emit a label for reference from debug information entries.
2582 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2584 // Emit the string itself with a terminating null byte.
2585 Asm->OutStreamer.EmitBytes(
2586 StringRef(Entries[i].second->getKeyData(),
2587 Entries[i].second->getKeyLength() + 1));
2590 // If we've got an offset section go ahead and emit that now as well.
2591 if (OffsetSection) {
2592 Asm->OutStreamer.SwitchSection(OffsetSection);
2593 unsigned offset = 0;
2594 unsigned size = 4; // FIXME: DWARF64 is 8.
2595 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2596 Asm->OutStreamer.EmitIntValue(offset, size);
2597 offset += Entries[i].second->getKeyLength() + 1;
2603 // Emit addresses into the section given.
2604 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2606 if (AddressPool.empty())
2609 // Start the dwarf addr section.
2610 Asm->OutStreamer.SwitchSection(AddrSection);
2612 // Order the address pool entries by ID
2613 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2615 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2616 E = AddressPool.end();
2618 Entries[I->second] = I->first;
2620 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2621 // Emit an expression for reference from debug information entries.
2622 if (const MCExpr *Expr = Entries[i])
2623 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2625 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2629 // Emit visible names into a debug str section.
2630 void DwarfDebug::emitDebugStr() {
2631 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2632 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2635 // Emit locations into the debug loc section.
2636 void DwarfDebug::emitDebugLoc() {
2637 if (DotDebugLocEntries.empty())
2640 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2641 I = DotDebugLocEntries.begin(),
2642 E = DotDebugLocEntries.end();
2644 DotDebugLocEntry &Entry = *I;
2645 if (I + 1 != DotDebugLocEntries.end())
2649 // Start the dwarf loc section.
2650 Asm->OutStreamer.SwitchSection(
2651 Asm->getObjFileLowering().getDwarfLocSection());
2652 unsigned char Size = Asm->getDataLayout().getPointerSize();
2653 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2655 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2656 I = DotDebugLocEntries.begin(),
2657 E = DotDebugLocEntries.end();
2658 I != E; ++I, ++index) {
2659 DotDebugLocEntry &Entry = *I;
2660 if (Entry.isMerged())
2662 if (Entry.isEmpty()) {
2663 Asm->OutStreamer.EmitIntValue(0, Size);
2664 Asm->OutStreamer.EmitIntValue(0, Size);
2665 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2667 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2668 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2669 DIVariable DV(Entry.getVariable());
2670 Asm->OutStreamer.AddComment("Loc expr size");
2671 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2672 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2673 Asm->EmitLabelDifference(end, begin, 2);
2674 Asm->OutStreamer.EmitLabel(begin);
2675 if (Entry.isInt()) {
2676 DIBasicType BTy(DV.getType());
2677 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2678 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2679 Asm->OutStreamer.AddComment("DW_OP_consts");
2680 Asm->EmitInt8(dwarf::DW_OP_consts);
2681 Asm->EmitSLEB128(Entry.getInt());
2683 Asm->OutStreamer.AddComment("DW_OP_constu");
2684 Asm->EmitInt8(dwarf::DW_OP_constu);
2685 Asm->EmitULEB128(Entry.getInt());
2687 } else if (Entry.isLocation()) {
2688 MachineLocation Loc = Entry.getLoc();
2689 if (!DV.hasComplexAddress())
2691 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2693 // Complex address entry.
2694 unsigned N = DV.getNumAddrElements();
2696 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2697 if (Loc.getOffset()) {
2699 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2700 Asm->OutStreamer.AddComment("DW_OP_deref");
2701 Asm->EmitInt8(dwarf::DW_OP_deref);
2702 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2703 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2704 Asm->EmitSLEB128(DV.getAddrElement(1));
2706 // If first address element is OpPlus then emit
2707 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2708 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2709 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2713 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2716 // Emit remaining complex address elements.
2717 for (; i < N; ++i) {
2718 uint64_t Element = DV.getAddrElement(i);
2719 if (Element == DIBuilder::OpPlus) {
2720 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2721 Asm->EmitULEB128(DV.getAddrElement(++i));
2722 } else if (Element == DIBuilder::OpDeref) {
2724 Asm->EmitInt8(dwarf::DW_OP_deref);
2726 llvm_unreachable("unknown Opcode found in complex address");
2730 // else ... ignore constant fp. There is not any good way to
2731 // to represent them here in dwarf.
2732 Asm->OutStreamer.EmitLabel(end);
2737 struct SymbolCUSorter {
2738 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2739 const MCStreamer &Streamer;
2741 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2742 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2743 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2745 // Symbols with no order assigned should be placed at the end.
2746 // (e.g. section end labels)
2748 IA = (unsigned)(-1);
2750 IB = (unsigned)(-1);
2755 static bool CUSort(const Unit *A, const Unit *B) {
2756 return (A->getUniqueID() < B->getUniqueID());
2760 const MCSymbol *Start, *End;
2763 // Emit a debug aranges section, containing a CU lookup for any
2764 // address we can tie back to a CU.
2765 void DwarfDebug::emitDebugARanges() {
2766 // Start the dwarf aranges section.
2767 Asm->OutStreamer.SwitchSection(
2768 Asm->getObjFileLowering().getDwarfARangesSection());
2770 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2774 // Build a list of sections used.
2775 std::vector<const MCSection *> Sections;
2776 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2778 const MCSection *Section = it->first;
2779 Sections.push_back(Section);
2782 // Sort the sections into order.
2783 // This is only done to ensure consistent output order across different runs.
2784 std::sort(Sections.begin(), Sections.end(), SectionSort);
2786 // Build a set of address spans, sorted by CU.
2787 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2788 const MCSection *Section = Sections[SecIdx];
2789 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2790 if (List.size() < 2)
2793 // Sort the symbols by offset within the section.
2794 SymbolCUSorter sorter(Asm->OutStreamer);
2795 std::sort(List.begin(), List.end(), sorter);
2797 // If we have no section (e.g. common), just write out
2798 // individual spans for each symbol.
2799 if (Section == NULL) {
2800 for (size_t n = 0; n < List.size(); n++) {
2801 const SymbolCU &Cur = List[n];
2804 Span.Start = Cur.Sym;
2807 Spans[Cur.CU].push_back(Span);
2810 // Build spans between each label.
2811 const MCSymbol *StartSym = List[0].Sym;
2812 for (size_t n = 1; n < List.size(); n++) {
2813 const SymbolCU &Prev = List[n - 1];
2814 const SymbolCU &Cur = List[n];
2816 // Try and build the longest span we can within the same CU.
2817 if (Cur.CU != Prev.CU) {
2819 Span.Start = StartSym;
2821 Spans[Prev.CU].push_back(Span);
2828 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2829 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2831 // Build a list of CUs used.
2832 std::vector<CompileUnit *> CUs;
2833 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2834 CompileUnit *CU = it->first;
2838 // Sort the CU list (again, to ensure consistent output order).
2839 std::sort(CUs.begin(), CUs.end(), CUSort);
2841 // Emit an arange table for each CU we used.
2842 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2843 CompileUnit *CU = CUs[CUIdx];
2844 std::vector<ArangeSpan> &List = Spans[CU];
2846 // Emit size of content not including length itself.
2847 unsigned ContentSize =
2848 sizeof(int16_t) + // DWARF ARange version number
2849 sizeof(int32_t) + // Offset of CU in the .debug_info section
2850 sizeof(int8_t) + // Pointer Size (in bytes)
2851 sizeof(int8_t); // Segment Size (in bytes)
2853 unsigned TupleSize = PtrSize * 2;
2855 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2856 unsigned Padding = 0;
2857 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2860 ContentSize += Padding;
2861 ContentSize += (List.size() + 1) * TupleSize;
2863 // For each compile unit, write the list of spans it covers.
2864 Asm->OutStreamer.AddComment("Length of ARange Set");
2865 Asm->EmitInt32(ContentSize);
2866 Asm->OutStreamer.AddComment("DWARF Arange version number");
2867 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2868 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2869 Asm->EmitSectionOffset(
2870 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2871 CU->getSectionSym());
2872 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2873 Asm->EmitInt8(PtrSize);
2874 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2877 for (unsigned n = 0; n < Padding; n++)
2878 Asm->EmitInt8(0xff);
2880 for (unsigned n = 0; n < List.size(); n++) {
2881 const ArangeSpan &Span = List[n];
2882 Asm->EmitLabelReference(Span.Start, PtrSize);
2884 // Calculate the size as being from the span start to it's end.
2886 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2888 // For symbols without an end marker (e.g. common), we
2889 // write a single arange entry containing just that one symbol.
2890 uint64_t Size = SymSize[Span.Start];
2894 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2898 Asm->OutStreamer.AddComment("ARange terminator");
2899 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2900 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2904 // Emit visible names into a debug ranges section.
2905 void DwarfDebug::emitDebugRanges() {
2906 // Start the dwarf ranges section.
2907 Asm->OutStreamer.SwitchSection(
2908 Asm->getObjFileLowering().getDwarfRangesSection());
2910 // Size for our labels.
2911 unsigned char Size = Asm->getDataLayout().getPointerSize();
2913 // Grab the specific ranges for the compile units in the module.
2914 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2917 CompileUnit *TheCU = I->second;
2918 unsigned ID = TheCU->getUniqueID();
2920 // Emit a symbol so we can find the beginning of our ranges.
2921 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_ranges", ID));
2923 // Iterate over the misc ranges for the compile units in the module.
2924 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2925 for (SmallVectorImpl<RangeSpanList>::const_iterator
2926 I = RangeLists.begin(),
2927 E = RangeLists.end();
2929 const RangeSpanList &List = *I;
2931 // Emit our symbol so we can find the beginning of the range.
2932 Asm->OutStreamer.EmitLabel(List.getSym());
2934 for (SmallVectorImpl<RangeSpan>::const_iterator
2935 RI = List.getRanges().begin(),
2936 RE = List.getRanges().end();
2938 const RangeSpan &Range = *RI;
2939 // We occasionally have ranges without begin/end labels.
2940 // FIXME: Verify and fix.
2941 const MCSymbol *Begin = Range.getStart();
2942 const MCSymbol *End = Range.getEnd();
2943 Begin ? Asm->OutStreamer.EmitSymbolValue(Begin, Size)
2944 : Asm->OutStreamer.EmitIntValue(0, Size);
2945 End ? Asm->OutStreamer.EmitSymbolValue(End, Size)
2946 : Asm->OutStreamer.EmitIntValue(0, Size);
2949 // And terminate the list with two 0 values.
2950 Asm->OutStreamer.EmitIntValue(0, Size);
2951 Asm->OutStreamer.EmitIntValue(0, Size);
2956 // Emit visible names into a debug macinfo section.
2957 void DwarfDebug::emitDebugMacInfo() {
2958 if (const MCSection *LineInfo =
2959 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2960 // Start the dwarf macinfo section.
2961 Asm->OutStreamer.SwitchSection(LineInfo);
2965 // DWARF5 Experimental Separate Dwarf emitters.
2967 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2968 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2969 // DW_AT_ranges_base, DW_AT_addr_base.
2970 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2972 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2973 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2974 Asm, this, &SkeletonHolder);
2976 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2977 CU->getNode().getSplitDebugFilename());
2979 // Relocate to the beginning of the addr_base section, else 0 for the
2980 // beginning of the one for this compile unit.
2981 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2982 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2983 DwarfAddrSectionSym);
2985 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2987 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2988 // into an entity. We're using 0, or a NULL label for this.
2989 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2991 // DW_AT_stmt_list is a offset of line number information for this
2992 // compile unit in debug_line section.
2993 // FIXME: Should handle multiple compile units.
2994 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2995 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
2996 DwarfLineSectionSym);
2998 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
3000 if (!CompilationDir.empty())
3001 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3003 addGnuPubAttributes(NewCU, Die);
3005 // Attribute if we've emitted any ranges and their location for the compile
3007 if (!CU->getRangeLists().empty())
3008 addSectionLabel(Asm, NewCU, Die, dwarf::DW_AT_GNU_ranges_base,
3009 Asm->GetTempSymbol("gnu_ranges", NewCU->getUniqueID()),
3010 DwarfDebugRangeSectionSym);
3012 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
3013 DwarfInfoSectionSym);
3014 SkeletonHolder.addUnit(NewCU);
3019 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3020 // compile units that would normally be in debug_info.
3021 void DwarfDebug::emitDebugInfoDWO() {
3022 assert(useSplitDwarf() && "No split dwarf debug info?");
3023 InfoHolder.emitUnits(this,
3024 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3025 DwarfAbbrevDWOSectionSym);
3028 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3029 // abbreviations for the .debug_info.dwo section.
3030 void DwarfDebug::emitDebugAbbrevDWO() {
3031 assert(useSplitDwarf() && "No split dwarf?");
3032 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3035 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3036 // string section and is identical in format to traditional .debug_str
3038 void DwarfDebug::emitDebugStrDWO() {
3039 assert(useSplitDwarf() && "No split dwarf?");
3040 const MCSection *OffSec =
3041 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3042 const MCSymbol *StrSym = DwarfStrSectionSym;
3043 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3047 void DwarfDebug::addTypeUnitType(uint16_t Language, DIE *RefDie,
3048 DICompositeType CTy) {
3049 DenseMap<const MDNode *,
3050 std::pair<uint64_t, SmallVectorImpl<DIE *> *> >::iterator I =
3051 TypeUnits.find(CTy);
3052 SmallVector<DIE *, 8> References;
3053 References.push_back(RefDie);
3054 if (I != TypeUnits.end()) {
3055 if (I->second.second) {
3056 I->second.second->push_back(RefDie);
3060 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3061 TypeUnit *NewTU = new TypeUnit(InfoHolder.getUnits().size(), UnitDie,
3062 Language, Asm, this, &InfoHolder);
3063 InfoHolder.addUnit(NewTU);
3065 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3068 // Register the type in the TypeUnits map with a vector of references to be
3069 // populated whenever a reference is required.
3070 I = TypeUnits.insert(std::make_pair(CTy, std::make_pair(0, &References)))
3073 // Construct the type, this may, recursively, require more type units that
3074 // may in turn require this type again - in which case they will add DIEs to
3075 // the References vector.
3076 DIE *Die = NewTU->createTypeDIE(CTy);
3078 if (GenerateODRHash && shouldAddODRHash(NewTU, Die))
3079 NewTU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3080 dwarf::DW_FORM_data8,
3081 DIEHash().computeDIEODRSignature(*Die));
3082 // FIXME: This won't handle circularly referential structures, as the DIE
3083 // may have references to other DIEs still under construction and missing
3084 // their signature. Hashing should walk through the signatures to their
3085 // referenced type, or possibly walk the precomputed hashes of related types
3087 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3089 // Remove the References vector and add the type hash.
3090 I->second.first = Signature;
3091 I->second.second = NULL;
3094 useSplitDwarf() ? Asm->getObjFileLowering().getDwarfInfoDWOSection()
3095 : Asm->getObjFileLowering().getDwarfInfoSection(),
3096 // FIXME: This is subtle (using the info section even when
3097 // this CU is in the dwo section) and necessary for the
3098 // current arange code - ideally it should iterate
3099 // skeleton units, not full units, if it's going to reference skeletons
3100 useSplitDwarf() ? NULL : DwarfInfoSectionSym);
3103 // Populate all the signatures.
3104 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3105 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3106 dwarf::DW_FORM_ref_sig8, I->second.first);