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."), cl::init(0));
111 static const char *const DWARFGroupName = "DWARF Emission";
112 static const char *const DbgTimerName = "DWARF Debug Writer";
114 //===----------------------------------------------------------------------===//
118 /// resolve - Look in the DwarfDebug map for the MDNode that
119 /// corresponds to the reference.
120 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
121 return DD->resolve(Ref);
124 DIType DbgVariable::getType() const {
125 DIType Ty = Var.getType();
126 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
127 // addresses instead.
128 if (Var.isBlockByrefVariable()) {
129 /* Byref variables, in Blocks, are declared by the programmer as
130 "SomeType VarName;", but the compiler creates a
131 __Block_byref_x_VarName struct, and gives the variable VarName
132 either the struct, or a pointer to the struct, as its type. This
133 is necessary for various behind-the-scenes things the compiler
134 needs to do with by-reference variables in blocks.
136 However, as far as the original *programmer* is concerned, the
137 variable should still have type 'SomeType', as originally declared.
139 The following function dives into the __Block_byref_x_VarName
140 struct to find the original type of the variable. This will be
141 passed back to the code generating the type for the Debug
142 Information Entry for the variable 'VarName'. 'VarName' will then
143 have the original type 'SomeType' in its debug information.
145 The original type 'SomeType' will be the type of the field named
146 'VarName' inside the __Block_byref_x_VarName struct.
148 NOTE: In order for this to not completely fail on the debugger
149 side, the Debug Information Entry for the variable VarName needs to
150 have a DW_AT_location that tells the debugger how to unwind through
151 the pointers and __Block_byref_x_VarName struct to find the actual
152 value of the variable. The function addBlockByrefType does this. */
154 uint16_t tag = Ty.getTag();
156 if (tag == dwarf::DW_TAG_pointer_type)
157 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
159 DIArray Elements = DICompositeType(subType).getTypeArray();
160 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
161 DIDerivedType DT(Elements.getElement(i));
162 if (getName() == DT.getName())
163 return (resolve(DT.getTypeDerivedFrom()));
169 } // end llvm namespace
171 /// Return Dwarf Version by checking module flags.
172 static unsigned getDwarfVersionFromModule(const Module *M) {
173 Value *Val = M->getModuleFlag("Dwarf Version");
175 return dwarf::DWARF_VERSION;
176 return cast<ConstantInt>(Val)->getZExtValue();
179 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
180 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
181 PrevLabel(NULL), GlobalRangeCount(0),
182 InfoHolder(A, "info_string", DIEValueAllocator),
183 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
185 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
186 DwarfStrSectionSym = TextSectionSym = 0;
187 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
188 DwarfAddrSectionSym = 0;
189 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
190 FunctionBeginSym = FunctionEndSym = 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<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
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(DwarfUnit *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(DwarfCompileUnit *SPCU,
378 DIE *SPDie = SPCU->getDIE(SP);
380 assert(SPDie && "Unable to find subprogram DIE!");
382 // If we're updating an abstract DIE, then we will be adding the children and
383 // object pointer later on. But what we don't want to do is process the
384 // concrete DIE twice.
385 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
386 // Pick up abstract subprogram DIE.
388 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
389 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
391 DISubprogram SPDecl = SP.getFunctionDeclaration();
392 if (!SPDecl.isSubprogram()) {
393 // There is not any need to generate specification DIE for a function
394 // defined at compile unit level. If a function is defined inside another
395 // function then gdb prefers the definition at top level and but does not
396 // expect specification DIE in parent function. So avoid creating
397 // specification DIE for a function defined inside a function.
398 DIScope SPContext = resolve(SP.getContext());
399 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
400 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
401 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
404 DICompositeType SPTy = SP.getType();
405 DIArray Args = SPTy.getTypeArray();
406 uint16_t SPTag = SPTy.getTag();
407 if (SPTag == dwarf::DW_TAG_subroutine_type)
408 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
410 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
411 DIType ATy(Args.getElement(i));
412 SPCU->addType(Arg, ATy);
413 if (ATy.isArtificial())
414 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
415 if (ATy.isObjectPointer())
416 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
418 DIE *SPDeclDie = SPDie;
419 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
420 *SPCU->getUnitDie());
421 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
426 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
427 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
429 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
430 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
431 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
433 // Add name to the name table, we do this here because we're guaranteed
434 // to have concrete versions of our DW_TAG_subprogram nodes.
435 addSubprogramNames(SPCU, SP, SPDie);
440 /// Check whether we should create a DIE for the given Scope, return true
441 /// if we don't create a DIE (the corresponding DIE is null).
442 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
443 if (Scope->isAbstractScope())
446 // We don't create a DIE if there is no Range.
447 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
451 if (Ranges.size() > 1)
454 // We don't create a DIE if we have a single Range and the end label
456 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
457 MCSymbol *End = getLabelAfterInsn(RI->second);
461 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
462 dwarf::Attribute A, const MCSymbol *L,
463 const MCSymbol *Sec) {
464 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
465 U->addSectionLabel(D, A, L);
467 U->addSectionDelta(D, A, L, Sec);
470 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
471 const SmallVectorImpl<InsnRange> &Range) {
472 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
473 // emitting it appropriately.
474 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
475 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
476 DwarfDebugRangeSectionSym);
478 RangeSpanList List(RangeSym);
479 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
482 RangeSpan Span(getLabelBeforeInsn(RI->first),
483 getLabelAfterInsn(RI->second));
484 List.addRange(llvm_move(Span));
487 // Add the range list to the set of ranges to be emitted.
488 TheCU->addRangeList(llvm_move(List));
491 // Construct new DW_TAG_lexical_block for this scope and attach
492 // DW_AT_low_pc/DW_AT_high_pc labels.
493 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
494 LexicalScope *Scope) {
495 if (isLexicalScopeDIENull(Scope))
498 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
499 if (Scope->isAbstractScope())
502 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
504 // If we have multiple ranges, emit them into the range section.
505 if (ScopeRanges.size() > 1) {
506 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
510 // Construct the address range for this DIE.
511 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
512 MCSymbol *Start = getLabelBeforeInsn(RI->first);
513 MCSymbol *End = getLabelAfterInsn(RI->second);
514 assert(End && "End label should not be null!");
516 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
517 assert(End->isDefined() && "Invalid end label for an inlined scope!");
519 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
520 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
525 // This scope represents inlined body of a function. Construct DIE to
526 // represent this concrete inlined copy of the function.
527 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
528 LexicalScope *Scope) {
529 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
530 assert(!ScopeRanges.empty() &&
531 "LexicalScope does not have instruction markers!");
533 if (!Scope->getScopeNode())
535 DIScope DS(Scope->getScopeNode());
536 DISubprogram InlinedSP = getDISubprogram(DS);
537 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
539 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
543 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
544 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
546 // If we have multiple ranges, emit them into the range section.
547 if (ScopeRanges.size() > 1)
548 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
550 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
551 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
552 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
554 if (StartLabel == 0 || EndLabel == 0)
555 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
557 assert(StartLabel->isDefined() &&
558 "Invalid starting label for an inlined scope!");
559 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
561 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
562 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
565 InlinedSubprogramDIEs.insert(OriginDIE);
567 // Add the call site information to the DIE.
568 DILocation DL(Scope->getInlinedAt());
569 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
570 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
571 TheCU->getUniqueID()));
572 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
574 // Add name to the name table, we do this here because we're guaranteed
575 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
576 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
581 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
583 SmallVectorImpl<DIE *> &Children) {
584 DIE *ObjectPointer = NULL;
586 // Collect arguments for current function.
587 if (LScopes.isCurrentFunctionScope(Scope))
588 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
589 if (DbgVariable *ArgDV = CurrentFnArguments[i])
591 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
592 Children.push_back(Arg);
593 if (ArgDV->isObjectPointer())
597 // Collect lexical scope children first.
598 const SmallVectorImpl<DbgVariable *> &Variables =
599 ScopeVariables.lookup(Scope);
600 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
601 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
602 Scope->isAbstractScope())) {
603 Children.push_back(Variable);
604 if (Variables[i]->isObjectPointer())
605 ObjectPointer = Variable;
607 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
608 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
609 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
610 Children.push_back(Nested);
611 return ObjectPointer;
614 // Construct a DIE for this scope.
615 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
616 LexicalScope *Scope) {
617 if (!Scope || !Scope->getScopeNode())
620 DIScope DS(Scope->getScopeNode());
622 SmallVector<DIE *, 8> Children;
623 DIE *ObjectPointer = NULL;
624 bool ChildrenCreated = false;
626 // We try to create the scope DIE first, then the children DIEs. This will
627 // avoid creating un-used children then removing them later when we find out
628 // the scope DIE is null.
629 DIE *ScopeDIE = NULL;
630 if (Scope->getInlinedAt())
631 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
632 else if (DS.isSubprogram()) {
633 ProcessedSPNodes.insert(DS);
634 if (Scope->isAbstractScope()) {
635 ScopeDIE = TheCU->getDIE(DS);
636 // Note down abstract DIE.
638 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
640 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
642 // Early exit when we know the scope DIE is going to be null.
643 if (isLexicalScopeDIENull(Scope))
646 // We create children here when we know the scope DIE is not going to be
647 // null and the children will be added to the scope DIE.
648 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
649 ChildrenCreated = true;
651 // There is no need to emit empty lexical block DIE.
652 std::pair<ImportedEntityMap::const_iterator,
653 ImportedEntityMap::const_iterator> Range =
655 ScopesWithImportedEntities.begin(),
656 ScopesWithImportedEntities.end(),
657 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
659 if (Children.empty() && Range.first == Range.second)
661 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
662 assert(ScopeDIE && "Scope DIE should not be null.");
663 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
665 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
669 assert(Children.empty() &&
670 "We create children only when the scope DIE is not null.");
673 if (!ChildrenCreated)
674 // We create children when the scope DIE is not null.
675 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
678 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
681 ScopeDIE->addChild(*I);
683 if (DS.isSubprogram() && ObjectPointer != NULL)
684 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
689 // Look up the source id with the given directory and source file names.
690 // If none currently exists, create a new id and insert it in the
691 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
693 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
695 // If we use .loc in assembly, we can't separate .file entries according to
696 // compile units. Thus all files will belong to the default compile unit.
698 // FIXME: add a better feature test than hasRawTextSupport. Even better,
699 // extend .file to support this.
700 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
703 // If FE did not provide a file name, then assume stdin.
704 if (FileName.empty())
705 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
707 // TODO: this might not belong here. See if we can factor this better.
708 if (DirName == CompilationDir)
711 // FileIDCUMap stores the current ID for the given compile unit.
712 unsigned SrcId = FileIDCUMap[CUID] + 1;
714 // We look up the CUID/file/dir by concatenating them with a zero byte.
715 SmallString<128> NamePair;
716 NamePair += utostr(CUID);
719 NamePair += '\0'; // Zero bytes are not allowed in paths.
720 NamePair += FileName;
722 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
723 if (Ent.getValue() != SrcId)
724 return Ent.getValue();
726 FileIDCUMap[CUID] = SrcId;
727 // Print out a .file directive to specify files for .loc directives.
728 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
733 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
734 if (!GenerateGnuPubSections)
737 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
738 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
739 DwarfGnuPubNamesSectionSym);
741 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
742 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
743 DwarfGnuPubTypesSectionSym);
746 // Create new DwarfCompileUnit for the given metadata node with tag
747 // DW_TAG_compile_unit.
748 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
749 StringRef FN = DIUnit.getFilename();
750 CompilationDir = DIUnit.getDirectory();
752 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
753 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
754 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
755 InfoHolder.addUnit(NewCU);
757 FileIDCUMap[NewCU->getUniqueID()] = 0;
758 // Call this to emit a .file directive if it wasn't emitted for the source
759 // file this CU comes from yet.
760 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
762 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
763 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
764 DIUnit.getLanguage());
765 NewCU->addString(Die, dwarf::DW_AT_name, FN);
767 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
768 // into an entity. We're using 0 (or a NULL label) for this. For
769 // split dwarf it's in the skeleton CU so omit it here.
770 if (!useSplitDwarf())
771 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
773 // Define start line table label for each Compile Unit.
774 MCSymbol *LineTableStartSym =
775 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
776 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
777 NewCU->getUniqueID());
779 // Use a single line table if we are using .loc and generating assembly.
781 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
782 (NewCU->getUniqueID() == 0);
784 if (!useSplitDwarf()) {
785 // DW_AT_stmt_list is a offset of line number information for this
786 // compile unit in debug_line section. For split dwarf this is
787 // left in the skeleton CU and so not included.
788 // The line table entries are not always emitted in assembly, so it
789 // is not okay to use line_table_start here.
790 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
791 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
792 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
793 : LineTableStartSym);
794 else if (UseTheFirstCU)
795 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
797 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
798 DwarfLineSectionSym);
800 // If we're using split dwarf the compilation dir is going to be in the
801 // skeleton CU and so we don't need to duplicate it here.
802 if (!CompilationDir.empty())
803 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
805 addGnuPubAttributes(NewCU, Die);
808 if (DIUnit.isOptimized())
809 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
811 StringRef Flags = DIUnit.getFlags();
813 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
815 if (unsigned RVer = DIUnit.getRunTimeVersion())
816 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
817 dwarf::DW_FORM_data1, RVer);
823 useSplitDwarf() ? Asm->getObjFileLowering().getDwarfInfoDWOSection()
824 : Asm->getObjFileLowering().getDwarfInfoSection(),
825 // FIXME: This is subtle (using the info section even when
826 // this CU is in the dwo section) and necessary for the
827 // current arange code - ideally it should iterate
828 // skeleton units, not full units, if it's going to reference skeletons
829 DwarfInfoSectionSym);
831 CUMap.insert(std::make_pair(DIUnit, NewCU));
832 CUDieMap.insert(std::make_pair(Die, NewCU));
836 // Construct subprogram DIE.
837 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
839 // FIXME: We should only call this routine once, however, during LTO if a
840 // program is defined in multiple CUs we could end up calling it out of
841 // beginModule as we walk the CUs.
843 DwarfCompileUnit *&CURef = SPMap[N];
849 if (!SP.isDefinition())
850 // This is a method declaration which will be handled while constructing
854 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
856 // Expose as a global name.
857 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
860 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
862 DIImportedEntity Module(N);
863 if (!Module.Verify())
865 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
866 constructImportedEntityDIE(TheCU, Module, D);
869 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
870 const MDNode *N, DIE *Context) {
871 DIImportedEntity Module(N);
872 if (!Module.Verify())
874 return constructImportedEntityDIE(TheCU, Module, Context);
877 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
878 const DIImportedEntity &Module,
880 assert(Module.Verify() &&
881 "Use one of the MDNode * overloads to handle invalid metadata");
882 assert(Context && "Should always have a context for an imported_module");
883 DIE *IMDie = new DIE(Module.getTag());
884 TheCU->insertDIE(Module, IMDie);
886 DIDescriptor Entity = Module.getEntity();
887 if (Entity.isNameSpace())
888 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
889 else if (Entity.isSubprogram())
890 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
891 else if (Entity.isType())
892 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
894 EntityDie = TheCU->getDIE(Entity);
895 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
896 Module.getContext().getDirectory(),
897 TheCU->getUniqueID());
898 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
899 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
900 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
901 StringRef Name = Module.getName();
903 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
904 Context->addChild(IMDie);
907 // Emit all Dwarf sections that should come prior to the content. Create
908 // global DIEs and emit initial debug info sections. This is invoked by
909 // the target AsmPrinter.
910 void DwarfDebug::beginModule() {
911 if (DisableDebugInfoPrinting)
914 const Module *M = MMI->getModule();
916 // If module has named metadata anchors then use them, otherwise scan the
917 // module using debug info finder to collect debug info.
918 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
921 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
923 // Emit initial sections so we can reference labels later.
926 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
927 DICompileUnit CUNode(CU_Nodes->getOperand(i));
928 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
929 DIArray ImportedEntities = CUNode.getImportedEntities();
930 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
931 ScopesWithImportedEntities.push_back(std::make_pair(
932 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
933 ImportedEntities.getElement(i)));
934 std::sort(ScopesWithImportedEntities.begin(),
935 ScopesWithImportedEntities.end(), less_first());
936 DIArray GVs = CUNode.getGlobalVariables();
937 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
938 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
939 DIArray SPs = CUNode.getSubprograms();
940 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
941 constructSubprogramDIE(CU, SPs.getElement(i));
942 DIArray EnumTypes = CUNode.getEnumTypes();
943 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
944 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
945 DIArray RetainedTypes = CUNode.getRetainedTypes();
946 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
947 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
948 // Emit imported_modules last so that the relevant context is already
950 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
951 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
954 // Tell MMI that we have debug info.
955 MMI->setDebugInfoAvailability(true);
957 // Prime section data.
958 SectionMap[Asm->getObjFileLowering().getTextSection()];
961 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
962 void DwarfDebug::computeInlinedDIEs() {
963 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
964 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
965 AE = InlinedSubprogramDIEs.end();
968 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
970 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
971 AE = AbstractSPDies.end();
973 DIE *ISP = AI->second;
974 if (InlinedSubprogramDIEs.count(ISP))
976 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
980 // Collect info for variables that were optimized out.
981 void DwarfDebug::collectDeadVariables() {
982 const Module *M = MMI->getModule();
984 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
985 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
986 DICompileUnit TheCU(CU_Nodes->getOperand(i));
987 DIArray Subprograms = TheCU.getSubprograms();
988 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
989 DISubprogram SP(Subprograms.getElement(i));
990 if (ProcessedSPNodes.count(SP) != 0)
992 if (!SP.isSubprogram())
994 if (!SP.isDefinition())
996 DIArray Variables = SP.getVariables();
997 if (Variables.getNumElements() == 0)
1000 // Construct subprogram DIE and add variables DIEs.
1001 DwarfCompileUnit *SPCU =
1002 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
1003 assert(SPCU && "Unable to find Compile Unit!");
1004 // FIXME: See the comment in constructSubprogramDIE about duplicate
1006 constructSubprogramDIE(SPCU, SP);
1007 DIE *SPDIE = SPCU->getDIE(SP);
1008 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1009 DIVariable DV(Variables.getElement(vi));
1010 if (!DV.isVariable())
1012 DbgVariable NewVar(DV, NULL, this);
1013 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1014 SPDIE->addChild(VariableDIE);
1021 // Type Signature [7.27] and ODR Hash code.
1023 /// \brief Grabs the string in whichever attribute is passed in and returns
1024 /// a reference to it. Returns "" if the attribute doesn't exist.
1025 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1026 DIEValue *V = Die->findAttribute(Attr);
1028 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1029 return S->getString();
1031 return StringRef("");
1034 /// Return true if the current DIE is contained within an anonymous namespace.
1035 static bool isContainedInAnonNamespace(DIE *Die) {
1036 DIE *Parent = Die->getParent();
1039 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1040 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1042 Parent = Parent->getParent();
1048 /// Test if the current CU language is C++ and that we have
1049 /// a named type that is not contained in an anonymous namespace.
1050 static bool shouldAddODRHash(DwarfTypeUnit *CU, DIE *Die) {
1051 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1052 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1053 !isContainedInAnonNamespace(Die);
1056 void DwarfDebug::finalizeModuleInfo() {
1057 // Collect info for variables that were optimized out.
1058 collectDeadVariables();
1060 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1061 computeInlinedDIEs();
1063 // Handle anything that needs to be done on a per-unit basis after
1064 // all other generation.
1065 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1066 E = getUnits().end();
1068 DwarfUnit *TheU = *I;
1069 // Emit DW_AT_containing_type attribute to connect types with their
1070 // vtable holding type.
1071 TheU->constructContainingTypeDIEs();
1073 // If we're splitting the dwarf out now that we've got the entire
1074 // CU then construct a skeleton CU based upon it.
1075 if (useSplitDwarf() &&
1076 TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1078 if (GenerateCUHash) {
1080 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1082 // This should be a unique identifier when we want to build .dwp files.
1083 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1084 dwarf::DW_FORM_data8, ID);
1085 // Now construct the skeleton CU associated.
1086 DwarfCompileUnit *SkCU =
1087 constructSkeletonCU(static_cast<DwarfCompileUnit *>(TheU));
1088 // This should be a unique identifier when we want to build .dwp files.
1089 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1090 dwarf::DW_FORM_data8, ID);
1094 // Compute DIE offsets and sizes.
1095 InfoHolder.computeSizeAndOffsets();
1096 if (useSplitDwarf())
1097 SkeletonHolder.computeSizeAndOffsets();
1100 void DwarfDebug::endSections() {
1101 // Filter labels by section.
1102 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1103 const SymbolCU &SCU = ArangeLabels[n];
1104 if (SCU.Sym->isInSection()) {
1105 // Make a note of this symbol and it's section.
1106 const MCSection *Section = &SCU.Sym->getSection();
1107 if (!Section->getKind().isMetadata())
1108 SectionMap[Section].push_back(SCU);
1110 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1111 // appear in the output. This sucks as we rely on sections to build
1112 // arange spans. We can do it without, but it's icky.
1113 SectionMap[NULL].push_back(SCU);
1117 // Build a list of sections used.
1118 std::vector<const MCSection *> Sections;
1119 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1121 const MCSection *Section = it->first;
1122 Sections.push_back(Section);
1125 // Sort the sections into order.
1126 // This is only done to ensure consistent output order across different runs.
1127 std::sort(Sections.begin(), Sections.end(), SectionSort);
1129 // Add terminating symbols for each section.
1130 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1131 const MCSection *Section = Sections[ID];
1132 MCSymbol *Sym = NULL;
1135 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1136 // if we know the section name up-front. For user-created sections, the
1138 // label may not be valid to use as a label. (section names can use a
1140 // set of characters on some systems)
1141 Sym = Asm->GetTempSymbol("debug_end", ID);
1142 Asm->OutStreamer.SwitchSection(Section);
1143 Asm->OutStreamer.EmitLabel(Sym);
1146 // Insert a final terminator.
1147 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1151 // Emit all Dwarf sections that should come after the content.
1152 void DwarfDebug::endModule() {
1159 // End any existing sections.
1160 // TODO: Does this need to happen?
1163 // Finalize the debug info for the module.
1164 finalizeModuleInfo();
1168 // Emit all the DIEs into a debug info section.
1171 // Corresponding abbreviations into a abbrev section.
1172 emitAbbreviations();
1174 // Emit info into a debug loc section.
1177 // Emit info into a debug aranges section.
1180 // Emit info into a debug ranges section.
1183 if (useSplitDwarf()) {
1186 emitDebugAbbrevDWO();
1187 // Emit DWO addresses.
1188 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1191 // Emit info into the dwarf accelerator table sections.
1192 if (useDwarfAccelTables()) {
1195 emitAccelNamespaces();
1199 // Emit the pubnames and pubtypes sections if requested.
1200 if (HasDwarfPubSections) {
1201 emitDebugPubNames(GenerateGnuPubSections);
1202 emitDebugPubTypes(GenerateGnuPubSections);
1208 // Reset these for the next Module if we have one.
1212 // Find abstract variable, if any, associated with Var.
1213 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1214 DebugLoc ScopeLoc) {
1215 LLVMContext &Ctx = DV->getContext();
1216 // More then one inlined variable corresponds to one abstract variable.
1217 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1218 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1220 return AbsDbgVariable;
1222 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1226 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1227 addScopeVariable(Scope, AbsDbgVariable);
1228 AbstractVariables[Var] = AbsDbgVariable;
1229 return AbsDbgVariable;
1232 // If Var is a current function argument then add it to CurrentFnArguments list.
1233 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1234 if (!LScopes.isCurrentFunctionScope(Scope))
1236 DIVariable DV = Var->getVariable();
1237 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1239 unsigned ArgNo = DV.getArgNumber();
1243 size_t Size = CurrentFnArguments.size();
1245 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1246 // llvm::Function argument size is not good indicator of how many
1247 // arguments does the function have at source level.
1249 CurrentFnArguments.resize(ArgNo * 2);
1250 CurrentFnArguments[ArgNo - 1] = Var;
1254 // Collect variable information from side table maintained by MMI.
1255 void DwarfDebug::collectVariableInfoFromMMITable(
1256 SmallPtrSet<const MDNode *, 16> &Processed) {
1257 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1258 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1261 const MDNode *Var = VI->first;
1264 Processed.insert(Var);
1266 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1268 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1270 // If variable scope is not found then skip this variable.
1274 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1275 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1276 RegVar->setFrameIndex(VP.first);
1277 if (!addCurrentFnArgument(RegVar, Scope))
1278 addScopeVariable(Scope, RegVar);
1280 AbsDbgVariable->setFrameIndex(VP.first);
1284 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1286 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1287 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1288 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1289 MI->getOperand(0).getReg() &&
1290 (MI->getOperand(1).isImm() ||
1291 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1294 // Get .debug_loc entry for the instruction range starting at MI.
1295 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1296 const MCSymbol *FLabel,
1297 const MCSymbol *SLabel,
1298 const MachineInstr *MI) {
1299 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1301 assert(MI->getNumOperands() == 3);
1302 if (MI->getOperand(0).isReg()) {
1303 MachineLocation MLoc;
1304 // If the second operand is an immediate, this is a
1305 // register-indirect address.
1306 if (!MI->getOperand(1).isImm())
1307 MLoc.set(MI->getOperand(0).getReg());
1309 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1310 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1312 if (MI->getOperand(0).isImm())
1313 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1314 if (MI->getOperand(0).isFPImm())
1315 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1316 if (MI->getOperand(0).isCImm())
1317 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1319 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1322 // Find variables for each lexical scope.
1324 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1326 // Grab the variable info that was squirreled away in the MMI side-table.
1327 collectVariableInfoFromMMITable(Processed);
1329 for (SmallVectorImpl<const MDNode *>::const_iterator
1330 UVI = UserVariables.begin(),
1331 UVE = UserVariables.end();
1332 UVI != UVE; ++UVI) {
1333 const MDNode *Var = *UVI;
1334 if (Processed.count(Var))
1337 // History contains relevant DBG_VALUE instructions for Var and instructions
1339 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1340 if (History.empty())
1342 const MachineInstr *MInsn = History.front();
1345 LexicalScope *Scope = NULL;
1346 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1347 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1348 Scope = LScopes.getCurrentFunctionScope();
1349 else if (MDNode *IA = DV.getInlinedAt())
1350 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1352 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1353 // If variable scope is not found then skip this variable.
1357 Processed.insert(DV);
1358 assert(MInsn->isDebugValue() && "History must begin with debug value");
1359 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1360 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1361 if (!addCurrentFnArgument(RegVar, Scope))
1362 addScopeVariable(Scope, RegVar);
1364 AbsVar->setMInsn(MInsn);
1366 // Simplify ranges that are fully coalesced.
1367 if (History.size() <= 1 ||
1368 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1369 RegVar->setMInsn(MInsn);
1373 // Handle multiple DBG_VALUE instructions describing one variable.
1374 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1376 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1377 HI = History.begin(),
1380 const MachineInstr *Begin = *HI;
1381 assert(Begin->isDebugValue() && "Invalid History entry");
1383 // Check if DBG_VALUE is truncating a range.
1384 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1385 !Begin->getOperand(0).getReg())
1388 // Compute the range for a register location.
1389 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1390 const MCSymbol *SLabel = 0;
1393 // If Begin is the last instruction in History then its value is valid
1394 // until the end of the function.
1395 SLabel = FunctionEndSym;
1397 const MachineInstr *End = HI[1];
1398 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1399 << "\t" << *Begin << "\t" << *End << "\n");
1400 if (End->isDebugValue())
1401 SLabel = getLabelBeforeInsn(End);
1403 // End is a normal instruction clobbering the range.
1404 SLabel = getLabelAfterInsn(End);
1405 assert(SLabel && "Forgot label after clobber instruction");
1410 // The value is valid until the next DBG_VALUE or clobber.
1411 DotDebugLocEntries.push_back(
1412 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1414 DotDebugLocEntries.push_back(DotDebugLocEntry());
1417 // Collect info for variables that were optimized out.
1418 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1419 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1420 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1421 DIVariable DV(Variables.getElement(i));
1422 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1424 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1425 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1429 // Return Label preceding the instruction.
1430 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1431 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1432 assert(Label && "Didn't insert label before instruction");
1436 // Return Label immediately following the instruction.
1437 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1438 return LabelsAfterInsn.lookup(MI);
1441 // Process beginning of an instruction.
1442 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1445 // Check if source location changes, but ignore DBG_VALUE locations.
1446 if (!MI->isDebugValue()) {
1447 DebugLoc DL = MI->getDebugLoc();
1448 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1451 if (DL == PrologEndLoc) {
1452 Flags |= DWARF2_FLAG_PROLOGUE_END;
1453 PrologEndLoc = DebugLoc();
1455 if (PrologEndLoc.isUnknown())
1456 Flags |= DWARF2_FLAG_IS_STMT;
1458 if (!DL.isUnknown()) {
1459 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1460 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1462 recordSourceLine(0, 0, 0, 0);
1466 // Insert labels where requested.
1467 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1468 LabelsBeforeInsn.find(MI);
1471 if (I == LabelsBeforeInsn.end())
1474 // Label already assigned.
1479 PrevLabel = MMI->getContext().CreateTempSymbol();
1480 Asm->OutStreamer.EmitLabel(PrevLabel);
1482 I->second = PrevLabel;
1485 // Process end of an instruction.
1486 void DwarfDebug::endInstruction() {
1488 // Don't create a new label after DBG_VALUE instructions.
1489 // They don't generate code.
1490 if (!CurMI->isDebugValue())
1493 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1494 LabelsAfterInsn.find(CurMI);
1498 if (I == LabelsAfterInsn.end())
1501 // Label already assigned.
1505 // We need a label after this instruction.
1507 PrevLabel = MMI->getContext().CreateTempSymbol();
1508 Asm->OutStreamer.EmitLabel(PrevLabel);
1510 I->second = PrevLabel;
1513 // Each LexicalScope has first instruction and last instruction to mark
1514 // beginning and end of a scope respectively. Create an inverse map that list
1515 // scopes starts (and ends) with an instruction. One instruction may start (or
1516 // end) multiple scopes. Ignore scopes that are not reachable.
1517 void DwarfDebug::identifyScopeMarkers() {
1518 SmallVector<LexicalScope *, 4> WorkList;
1519 WorkList.push_back(LScopes.getCurrentFunctionScope());
1520 while (!WorkList.empty()) {
1521 LexicalScope *S = WorkList.pop_back_val();
1523 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1524 if (!Children.empty())
1525 for (SmallVectorImpl<LexicalScope *>::const_iterator
1526 SI = Children.begin(),
1527 SE = Children.end();
1529 WorkList.push_back(*SI);
1531 if (S->isAbstractScope())
1534 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1537 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1540 assert(RI->first && "InsnRange does not have first instruction!");
1541 assert(RI->second && "InsnRange does not have second instruction!");
1542 requestLabelBeforeInsn(RI->first);
1543 requestLabelAfterInsn(RI->second);
1548 // Get MDNode for DebugLoc's scope.
1549 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1550 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1551 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1552 return DL.getScope(Ctx);
1555 // Walk up the scope chain of given debug loc and find line number info
1556 // for the function.
1557 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1558 const MDNode *Scope = getScopeNode(DL, Ctx);
1559 DISubprogram SP = getDISubprogram(Scope);
1560 if (SP.isSubprogram()) {
1561 // Check for number of operands since the compatibility is
1563 if (SP->getNumOperands() > 19)
1564 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1566 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1572 // Gather pre-function debug information. Assumes being called immediately
1573 // after the function entry point has been emitted.
1574 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1577 // If there's no debug info for the function we're not going to do anything.
1578 if (!MMI->hasDebugInfo())
1581 // Grab the lexical scopes for the function, if we don't have any of those
1582 // then we're not going to be able to do anything.
1583 LScopes.initialize(*MF);
1584 if (LScopes.empty())
1587 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1589 // Make sure that each lexical scope will have a begin/end label.
1590 identifyScopeMarkers();
1592 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1593 // belongs to so that we add to the correct per-cu line table in the
1595 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1596 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1597 assert(TheCU && "Unable to find compile unit!");
1598 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1599 // Use a single line table if we are using .loc and generating assembly.
1600 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1602 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1604 // Emit a label for the function so that we have a beginning address.
1605 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1606 // Assumes in correct section after the entry point.
1607 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1609 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1610 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1611 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1613 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1615 bool AtBlockEntry = true;
1616 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1618 const MachineInstr *MI = II;
1620 if (MI->isDebugValue()) {
1621 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1623 // Keep track of user variables.
1625 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1627 // Variable is in a register, we need to check for clobbers.
1628 if (isDbgValueInDefinedReg(MI))
1629 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1631 // Check the history of this variable.
1632 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1633 if (History.empty()) {
1634 UserVariables.push_back(Var);
1635 // The first mention of a function argument gets the FunctionBeginSym
1636 // label, so arguments are visible when breaking at function entry.
1638 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1639 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1640 LabelsBeforeInsn[MI] = FunctionBeginSym;
1642 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1643 const MachineInstr *Prev = History.back();
1644 if (Prev->isDebugValue()) {
1645 // Coalesce identical entries at the end of History.
1646 if (History.size() >= 2 &&
1647 Prev->isIdenticalTo(History[History.size() - 2])) {
1648 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1649 << "\t" << *Prev << "\t"
1650 << *History[History.size() - 2] << "\n");
1654 // Terminate old register assignments that don't reach MI;
1655 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1656 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1657 isDbgValueInDefinedReg(Prev)) {
1658 // Previous register assignment needs to terminate at the end of
1660 MachineBasicBlock::const_iterator LastMI =
1661 PrevMBB->getLastNonDebugInstr();
1662 if (LastMI == PrevMBB->end()) {
1663 // Drop DBG_VALUE for empty range.
1664 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1665 << "\t" << *Prev << "\n");
1667 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1668 // Terminate after LastMI.
1669 History.push_back(LastMI);
1673 History.push_back(MI);
1675 // Not a DBG_VALUE instruction.
1677 AtBlockEntry = false;
1679 // First known non-DBG_VALUE and non-frame setup location marks
1680 // the beginning of the function body.
1681 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1682 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1683 PrologEndLoc = MI->getDebugLoc();
1685 // Check if the instruction clobbers any registers with debug vars.
1686 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1687 MOE = MI->operands_end();
1688 MOI != MOE; ++MOI) {
1689 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1691 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1694 const MDNode *Var = LiveUserVar[Reg];
1697 // Reg is now clobbered.
1698 LiveUserVar[Reg] = 0;
1700 // Was MD last defined by a DBG_VALUE referring to Reg?
1701 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1702 if (HistI == DbgValues.end())
1704 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1705 if (History.empty())
1707 const MachineInstr *Prev = History.back();
1708 // Sanity-check: Register assignments are terminated at the end of
1710 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1712 // Is the variable still in Reg?
1713 if (!isDbgValueInDefinedReg(Prev) ||
1714 Prev->getOperand(0).getReg() != Reg)
1716 // Var is clobbered. Make sure the next instruction gets a label.
1717 History.push_back(MI);
1724 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1726 SmallVectorImpl<const MachineInstr *> &History = I->second;
1727 if (History.empty())
1730 // Make sure the final register assignments are terminated.
1731 const MachineInstr *Prev = History.back();
1732 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1733 const MachineBasicBlock *PrevMBB = Prev->getParent();
1734 MachineBasicBlock::const_iterator LastMI =
1735 PrevMBB->getLastNonDebugInstr();
1736 if (LastMI == PrevMBB->end())
1737 // Drop DBG_VALUE for empty range.
1739 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1740 // Terminate after LastMI.
1741 History.push_back(LastMI);
1744 // Request labels for the full history.
1745 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1746 const MachineInstr *MI = History[i];
1747 if (MI->isDebugValue())
1748 requestLabelBeforeInsn(MI);
1750 requestLabelAfterInsn(MI);
1754 PrevInstLoc = DebugLoc();
1755 PrevLabel = FunctionBeginSym;
1757 // Record beginning of function.
1758 if (!PrologEndLoc.isUnknown()) {
1759 DebugLoc FnStartDL =
1760 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1762 FnStartDL.getLine(), FnStartDL.getCol(),
1763 FnStartDL.getScope(MF->getFunction()->getContext()),
1764 // We'd like to list the prologue as "not statements" but GDB behaves
1765 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1766 DWARF2_FLAG_IS_STMT);
1770 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1771 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1772 DIVariable DV = Var->getVariable();
1773 // Variables with positive arg numbers are parameters.
1774 if (unsigned ArgNum = DV.getArgNumber()) {
1775 // Keep all parameters in order at the start of the variable list to ensure
1776 // function types are correct (no out-of-order parameters)
1778 // This could be improved by only doing it for optimized builds (unoptimized
1779 // builds have the right order to begin with), searching from the back (this
1780 // would catch the unoptimized case quickly), or doing a binary search
1781 // rather than linear search.
1782 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1783 while (I != Vars.end()) {
1784 unsigned CurNum = (*I)->getVariable().getArgNumber();
1785 // A local (non-parameter) variable has been found, insert immediately
1789 // A later indexed parameter has been found, insert immediately before it.
1790 if (CurNum > ArgNum)
1794 Vars.insert(I, Var);
1798 Vars.push_back(Var);
1801 // Gather and emit post-function debug information.
1802 void DwarfDebug::endFunction(const MachineFunction *MF) {
1803 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1804 // though the beginFunction may not be called at all.
1805 // We should handle both cases.
1809 assert(CurFn == MF);
1812 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1817 // Define end label for subprogram.
1818 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1819 // Assumes in correct section after the entry point.
1820 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1821 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1822 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1824 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1825 collectVariableInfo(ProcessedVars);
1827 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1828 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1829 assert(TheCU && "Unable to find compile unit!");
1831 // Construct abstract scopes.
1832 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1833 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1834 LexicalScope *AScope = AList[i];
1835 DISubprogram SP(AScope->getScopeNode());
1836 if (SP.isSubprogram()) {
1837 // Collect info for variables that were optimized out.
1838 DIArray Variables = SP.getVariables();
1839 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1840 DIVariable DV(Variables.getElement(i));
1841 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1843 // Check that DbgVariable for DV wasn't created earlier, when
1844 // findAbstractVariable() was called for inlined instance of DV.
1845 LLVMContext &Ctx = DV->getContext();
1846 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1847 if (AbstractVariables.lookup(CleanDV))
1849 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1850 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1853 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1854 constructScopeDIE(TheCU, AScope);
1857 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1859 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1860 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1863 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1864 E = ScopeVariables.end();
1866 DeleteContainerPointers(I->second);
1867 ScopeVariables.clear();
1868 DeleteContainerPointers(CurrentFnArguments);
1869 UserVariables.clear();
1871 AbstractVariables.clear();
1872 LabelsBeforeInsn.clear();
1873 LabelsAfterInsn.clear();
1878 // Register a source line with debug info. Returns the unique label that was
1879 // emitted and which provides correspondence to the source line list.
1880 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1886 DIDescriptor Scope(S);
1888 if (Scope.isCompileUnit()) {
1889 DICompileUnit CU(S);
1890 Fn = CU.getFilename();
1891 Dir = CU.getDirectory();
1892 } else if (Scope.isFile()) {
1894 Fn = F.getFilename();
1895 Dir = F.getDirectory();
1896 } else if (Scope.isSubprogram()) {
1898 Fn = SP.getFilename();
1899 Dir = SP.getDirectory();
1900 } else if (Scope.isLexicalBlockFile()) {
1901 DILexicalBlockFile DBF(S);
1902 Fn = DBF.getFilename();
1903 Dir = DBF.getDirectory();
1904 } else if (Scope.isLexicalBlock()) {
1905 DILexicalBlock DB(S);
1906 Fn = DB.getFilename();
1907 Dir = DB.getDirectory();
1909 llvm_unreachable("Unexpected scope info");
1911 Src = getOrCreateSourceID(
1912 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1914 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1917 //===----------------------------------------------------------------------===//
1919 //===----------------------------------------------------------------------===//
1921 // Compute the size and offset of a DIE. The offset is relative to start of the
1922 // CU. It returns the offset after laying out the DIE.
1923 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1924 // Get the children.
1925 const std::vector<DIE *> &Children = Die->getChildren();
1927 // Record the abbreviation.
1928 assignAbbrevNumber(Die->getAbbrev());
1930 // Get the abbreviation for this DIE.
1931 const DIEAbbrev &Abbrev = Die->getAbbrev();
1934 Die->setOffset(Offset);
1936 // Start the size with the size of abbreviation code.
1937 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1939 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1940 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1942 // Size the DIE attribute values.
1943 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1944 // Size attribute value.
1945 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1947 // Size the DIE children if any.
1948 if (!Children.empty()) {
1949 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1950 "Children flag not set");
1952 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1953 Offset = computeSizeAndOffset(Children[j], Offset);
1955 // End of children marker.
1956 Offset += sizeof(int8_t);
1959 Die->setSize(Offset - Die->getOffset());
1963 // Compute the size and offset for each DIE.
1964 void DwarfFile::computeSizeAndOffsets() {
1965 // Offset from the first CU in the debug info section is 0 initially.
1966 unsigned SecOffset = 0;
1968 // Iterate over each compile unit and set the size and offsets for each
1969 // DIE within each compile unit. All offsets are CU relative.
1970 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1973 (*I)->setDebugInfoOffset(SecOffset);
1975 // CU-relative offset is reset to 0 here.
1976 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1977 (*I)->getHeaderSize(); // Unit-specific headers
1979 // EndOffset here is CU-relative, after laying out
1980 // all of the CU DIE.
1981 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1982 SecOffset += EndOffset;
1986 // Emit initial Dwarf sections with a label at the start of each one.
1987 void DwarfDebug::emitSectionLabels() {
1988 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1990 // Dwarf sections base addresses.
1991 DwarfInfoSectionSym =
1992 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1993 DwarfAbbrevSectionSym =
1994 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1995 if (useSplitDwarf())
1996 DwarfAbbrevDWOSectionSym = emitSectionSym(
1997 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1998 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
2000 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2001 emitSectionSym(Asm, MacroInfo);
2003 DwarfLineSectionSym =
2004 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2005 emitSectionSym(Asm, TLOF.getDwarfLocSection());
2006 if (GenerateGnuPubSections) {
2007 DwarfGnuPubNamesSectionSym =
2008 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2009 DwarfGnuPubTypesSectionSym =
2010 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2011 } else if (HasDwarfPubSections) {
2012 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2013 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2016 DwarfStrSectionSym =
2017 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2018 if (useSplitDwarf()) {
2019 DwarfStrDWOSectionSym =
2020 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2021 DwarfAddrSectionSym =
2022 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2024 DwarfDebugRangeSectionSym =
2025 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2027 DwarfDebugLocSectionSym =
2028 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2030 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2031 emitSectionSym(Asm, TLOF.getDataSection());
2034 // Recursively emits a debug information entry.
2035 void DwarfDebug::emitDIE(DIE *Die) {
2036 // Get the abbreviation for this DIE.
2037 const DIEAbbrev &Abbrev = Die->getAbbrev();
2039 // Emit the code (index) for the abbreviation.
2040 if (Asm->isVerbose())
2041 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2042 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2043 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2044 dwarf::TagString(Abbrev.getTag()));
2045 Asm->EmitULEB128(Abbrev.getNumber());
2047 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2048 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2050 // Emit the DIE attribute values.
2051 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2052 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2053 dwarf::Form Form = AbbrevData[i].getForm();
2054 assert(Form && "Too many attributes for DIE (check abbreviation)");
2056 if (Asm->isVerbose())
2057 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2060 case dwarf::DW_AT_abstract_origin:
2061 case dwarf::DW_AT_type:
2062 case dwarf::DW_AT_friend:
2063 case dwarf::DW_AT_specification:
2064 case dwarf::DW_AT_import:
2065 case dwarf::DW_AT_containing_type: {
2066 DIEEntry *E = cast<DIEEntry>(Values[i]);
2067 DIE *Origin = E->getEntry();
2068 unsigned Addr = Origin->getOffset();
2069 if (Form == dwarf::DW_FORM_ref_addr) {
2070 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2071 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2072 // section. Origin->getOffset() returns the offset from start of the
2074 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2075 assert(CU && "CUDie should belong to a CU.");
2076 Addr += CU->getDebugInfoOffset();
2077 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2078 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2079 DIEEntry::getRefAddrSize(Asm));
2081 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2082 CU->getSectionSym(),
2083 DIEEntry::getRefAddrSize(Asm));
2085 // Make sure Origin belong to the same CU.
2086 assert(Die->getUnit() == Origin->getUnit() &&
2087 "The referenced DIE should belong to the same CU in ref4");
2088 Asm->EmitInt32(Addr);
2092 case dwarf::DW_AT_location: {
2093 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2094 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2095 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2097 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2099 Values[i]->EmitValue(Asm, Form);
2103 case dwarf::DW_AT_accessibility: {
2104 if (Asm->isVerbose()) {
2105 DIEInteger *V = cast<DIEInteger>(Values[i]);
2106 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2108 Values[i]->EmitValue(Asm, Form);
2112 // Emit an attribute using the defined form.
2113 Values[i]->EmitValue(Asm, Form);
2118 // Emit the DIE children if any.
2119 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2120 const std::vector<DIE *> &Children = Die->getChildren();
2122 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2123 emitDIE(Children[j]);
2125 Asm->OutStreamer.AddComment("End Of Children Mark");
2130 // Emit the various dwarf units to the unit section USection with
2131 // the abbreviations going into ASection.
2132 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2133 const MCSymbol *ASectionSym) {
2134 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2136 DwarfUnit *TheU = *I;
2137 DIE *Die = TheU->getUnitDie();
2138 const MCSection *USection = TheU->getSection();
2139 Asm->OutStreamer.SwitchSection(USection);
2141 // Emit the compile units header.
2142 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2144 // Emit size of content not including length itself
2145 Asm->OutStreamer.AddComment("Length of Unit");
2146 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2148 TheU->emitHeader(ASection, ASectionSym);
2151 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
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<DwarfUnit *>::const_iterator I = getUnits().begin(),
2222 E = getUnits().end();
2224 DwarfUnit *TheU = *I;
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<DwarfUnit *>::const_iterator I = getUnits().begin(),
2255 E = getUnits().end();
2257 DwarfUnit *TheU = *I;
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<DwarfUnit *>::const_iterator I = getUnits().begin(),
2287 E = getUnits().end();
2289 DwarfUnit *TheU = *I;
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<DwarfUnit *>::const_iterator I = getUnits().begin(),
2326 E = getUnits().end();
2328 DwarfUnit *TheU = *I;
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(DwarfUnit *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 *PSec =
2418 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2419 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2421 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2422 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2423 for (unsigned i = 0; i != Units.size(); ++i) {
2424 DwarfUnit *TheU = Units[i];
2425 unsigned ID = TheU->getUniqueID();
2427 // Start the dwarf pubnames section.
2428 Asm->OutStreamer.SwitchSection(PSec);
2430 // Emit a label so we can reference the beginning of this pubname section.
2432 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2435 Asm->OutStreamer.AddComment("Length of Public Names Info");
2436 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2437 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2438 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2440 Asm->OutStreamer.EmitLabel(BeginLabel);
2442 Asm->OutStreamer.AddComment("DWARF Version");
2443 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2445 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2446 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2448 Asm->OutStreamer.AddComment("Compilation Unit Length");
2449 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2451 // Emit the pubnames for this compilation unit.
2452 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2453 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2456 const char *Name = GI->getKeyData();
2457 const DIE *Entity = GI->second;
2459 Asm->OutStreamer.AddComment("DIE offset");
2460 Asm->EmitInt32(Entity->getOffset());
2463 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2464 Asm->OutStreamer.AddComment(
2465 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2466 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2467 Asm->EmitInt8(Desc.toBits());
2470 Asm->OutStreamer.AddComment("External Name");
2471 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2474 Asm->OutStreamer.AddComment("End Mark");
2476 Asm->OutStreamer.EmitLabel(EndLabel);
2480 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2481 const MCSection *PSec =
2482 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2483 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2485 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2486 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2487 for (unsigned i = 0; i != Units.size(); ++i) {
2488 DwarfUnit *TheU = Units[i];
2489 unsigned ID = TheU->getUniqueID();
2491 // Start the dwarf pubtypes section.
2492 Asm->OutStreamer.SwitchSection(PSec);
2494 // Emit a label so we can reference the beginning of this pubtype section.
2496 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2499 Asm->OutStreamer.AddComment("Length of Public Types Info");
2500 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2501 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2502 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2504 Asm->OutStreamer.EmitLabel(BeginLabel);
2506 Asm->OutStreamer.AddComment("DWARF Version");
2507 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2509 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2510 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2512 Asm->OutStreamer.AddComment("Compilation Unit Length");
2513 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2515 // Emit the pubtypes.
2516 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2517 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2520 const char *Name = GI->getKeyData();
2521 const DIE *Entity = GI->second;
2523 Asm->OutStreamer.AddComment("DIE offset");
2524 Asm->EmitInt32(Entity->getOffset());
2527 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2528 Asm->OutStreamer.AddComment(
2529 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2530 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2531 Asm->EmitInt8(Desc.toBits());
2534 Asm->OutStreamer.AddComment("External Name");
2536 // Emit the name with a terminating null byte.
2537 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2540 Asm->OutStreamer.AddComment("End Mark");
2542 Asm->OutStreamer.EmitLabel(EndLabel);
2546 // Emit strings into a string section.
2547 void DwarfFile::emitStrings(const MCSection *StrSection,
2548 const MCSection *OffsetSection = NULL,
2549 const MCSymbol *StrSecSym = NULL) {
2551 if (StringPool.empty())
2554 // Start the dwarf str section.
2555 Asm->OutStreamer.SwitchSection(StrSection);
2557 // Get all of the string pool entries and put them in an array by their ID so
2558 // we can sort them.
2560 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2563 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2564 I = StringPool.begin(),
2565 E = StringPool.end();
2567 Entries.push_back(std::make_pair(I->second.second, &*I));
2569 array_pod_sort(Entries.begin(), Entries.end());
2571 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2572 // Emit a label for reference from debug information entries.
2573 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2575 // Emit the string itself with a terminating null byte.
2576 Asm->OutStreamer.EmitBytes(
2577 StringRef(Entries[i].second->getKeyData(),
2578 Entries[i].second->getKeyLength() + 1));
2581 // If we've got an offset section go ahead and emit that now as well.
2582 if (OffsetSection) {
2583 Asm->OutStreamer.SwitchSection(OffsetSection);
2584 unsigned offset = 0;
2585 unsigned size = 4; // FIXME: DWARF64 is 8.
2586 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2587 Asm->OutStreamer.EmitIntValue(offset, size);
2588 offset += Entries[i].second->getKeyLength() + 1;
2593 // Emit addresses into the section given.
2594 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2596 if (AddressPool.empty())
2599 // Start the dwarf addr section.
2600 Asm->OutStreamer.SwitchSection(AddrSection);
2602 // Order the address pool entries by ID
2603 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2605 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2606 E = AddressPool.end();
2608 Entries[I->second] = I->first;
2610 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2611 // Emit an expression for reference from debug information entries.
2612 if (const MCExpr *Expr = Entries[i])
2613 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2615 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2619 // Emit visible names into a debug str section.
2620 void DwarfDebug::emitDebugStr() {
2621 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2622 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2625 // Emit locations into the debug loc section.
2626 void DwarfDebug::emitDebugLoc() {
2627 if (DotDebugLocEntries.empty())
2630 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2631 I = DotDebugLocEntries.begin(),
2632 E = DotDebugLocEntries.end();
2634 DotDebugLocEntry &Entry = *I;
2635 if (I + 1 != DotDebugLocEntries.end())
2639 // Start the dwarf loc section.
2640 Asm->OutStreamer.SwitchSection(
2641 Asm->getObjFileLowering().getDwarfLocSection());
2642 unsigned char Size = Asm->getDataLayout().getPointerSize();
2643 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2645 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2646 I = DotDebugLocEntries.begin(),
2647 E = DotDebugLocEntries.end();
2648 I != E; ++I, ++index) {
2649 DotDebugLocEntry &Entry = *I;
2650 if (Entry.isMerged())
2652 if (Entry.isEmpty()) {
2653 Asm->OutStreamer.EmitIntValue(0, Size);
2654 Asm->OutStreamer.EmitIntValue(0, Size);
2655 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2657 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2658 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2659 DIVariable DV(Entry.getVariable());
2660 Asm->OutStreamer.AddComment("Loc expr size");
2661 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2662 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2663 Asm->EmitLabelDifference(end, begin, 2);
2664 Asm->OutStreamer.EmitLabel(begin);
2665 if (Entry.isInt()) {
2666 DIBasicType BTy(DV.getType());
2667 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2668 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2669 Asm->OutStreamer.AddComment("DW_OP_consts");
2670 Asm->EmitInt8(dwarf::DW_OP_consts);
2671 Asm->EmitSLEB128(Entry.getInt());
2673 Asm->OutStreamer.AddComment("DW_OP_constu");
2674 Asm->EmitInt8(dwarf::DW_OP_constu);
2675 Asm->EmitULEB128(Entry.getInt());
2677 } else if (Entry.isLocation()) {
2678 MachineLocation Loc = Entry.getLoc();
2679 if (!DV.hasComplexAddress())
2681 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2683 // Complex address entry.
2684 unsigned N = DV.getNumAddrElements();
2686 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2687 if (Loc.getOffset()) {
2689 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2690 Asm->OutStreamer.AddComment("DW_OP_deref");
2691 Asm->EmitInt8(dwarf::DW_OP_deref);
2692 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2693 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2694 Asm->EmitSLEB128(DV.getAddrElement(1));
2696 // If first address element is OpPlus then emit
2697 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2698 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2699 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2703 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2706 // Emit remaining complex address elements.
2707 for (; i < N; ++i) {
2708 uint64_t Element = DV.getAddrElement(i);
2709 if (Element == DIBuilder::OpPlus) {
2710 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2711 Asm->EmitULEB128(DV.getAddrElement(++i));
2712 } else if (Element == DIBuilder::OpDeref) {
2714 Asm->EmitInt8(dwarf::DW_OP_deref);
2716 llvm_unreachable("unknown Opcode found in complex address");
2720 // else ... ignore constant fp. There is not any good way to
2721 // to represent them here in dwarf.
2722 Asm->OutStreamer.EmitLabel(end);
2727 struct SymbolCUSorter {
2728 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2729 const MCStreamer &Streamer;
2731 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2732 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2733 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2735 // Symbols with no order assigned should be placed at the end.
2736 // (e.g. section end labels)
2738 IA = (unsigned)(-1);
2740 IB = (unsigned)(-1);
2745 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2746 return (A->getUniqueID() < B->getUniqueID());
2750 const MCSymbol *Start, *End;
2753 // Emit a debug aranges section, containing a CU lookup for any
2754 // address we can tie back to a CU.
2755 void DwarfDebug::emitDebugARanges() {
2756 // Start the dwarf aranges section.
2757 Asm->OutStreamer.SwitchSection(
2758 Asm->getObjFileLowering().getDwarfARangesSection());
2760 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2764 // Build a list of sections used.
2765 std::vector<const MCSection *> Sections;
2766 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2768 const MCSection *Section = it->first;
2769 Sections.push_back(Section);
2772 // Sort the sections into order.
2773 // This is only done to ensure consistent output order across different runs.
2774 std::sort(Sections.begin(), Sections.end(), SectionSort);
2776 // Build a set of address spans, sorted by CU.
2777 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2778 const MCSection *Section = Sections[SecIdx];
2779 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2780 if (List.size() < 2)
2783 // Sort the symbols by offset within the section.
2784 SymbolCUSorter sorter(Asm->OutStreamer);
2785 std::sort(List.begin(), List.end(), sorter);
2787 // If we have no section (e.g. common), just write out
2788 // individual spans for each symbol.
2789 if (Section == NULL) {
2790 for (size_t n = 0; n < List.size(); n++) {
2791 const SymbolCU &Cur = List[n];
2794 Span.Start = Cur.Sym;
2797 Spans[Cur.CU].push_back(Span);
2800 // Build spans between each label.
2801 const MCSymbol *StartSym = List[0].Sym;
2802 for (size_t n = 1; n < List.size(); n++) {
2803 const SymbolCU &Prev = List[n - 1];
2804 const SymbolCU &Cur = List[n];
2806 // Try and build the longest span we can within the same CU.
2807 if (Cur.CU != Prev.CU) {
2809 Span.Start = StartSym;
2811 Spans[Prev.CU].push_back(Span);
2818 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2820 // Build a list of CUs used.
2821 std::vector<DwarfCompileUnit *> CUs;
2822 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2823 DwarfCompileUnit *CU = it->first;
2827 // Sort the CU list (again, to ensure consistent output order).
2828 std::sort(CUs.begin(), CUs.end(), CUSort);
2830 // Emit an arange table for each CU we used.
2831 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2832 DwarfCompileUnit *CU = CUs[CUIdx];
2833 std::vector<ArangeSpan> &List = Spans[CU];
2835 // Emit size of content not including length itself.
2836 unsigned ContentSize =
2837 sizeof(int16_t) + // DWARF ARange version number
2838 sizeof(int32_t) + // Offset of CU in the .debug_info section
2839 sizeof(int8_t) + // Pointer Size (in bytes)
2840 sizeof(int8_t); // Segment Size (in bytes)
2842 unsigned TupleSize = PtrSize * 2;
2844 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2845 unsigned Padding = 0;
2846 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2849 ContentSize += Padding;
2850 ContentSize += (List.size() + 1) * TupleSize;
2852 // For each compile unit, write the list of spans it covers.
2853 Asm->OutStreamer.AddComment("Length of ARange Set");
2854 Asm->EmitInt32(ContentSize);
2855 Asm->OutStreamer.AddComment("DWARF Arange version number");
2856 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2857 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2858 Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
2859 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2860 Asm->EmitInt8(PtrSize);
2861 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2864 for (unsigned n = 0; n < Padding; n++)
2865 Asm->EmitInt8(0xff);
2867 for (unsigned n = 0; n < List.size(); n++) {
2868 const ArangeSpan &Span = List[n];
2869 Asm->EmitLabelReference(Span.Start, PtrSize);
2871 // Calculate the size as being from the span start to it's end.
2873 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2875 // For symbols without an end marker (e.g. common), we
2876 // write a single arange entry containing just that one symbol.
2877 uint64_t Size = SymSize[Span.Start];
2881 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2885 Asm->OutStreamer.AddComment("ARange terminator");
2886 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2887 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2891 // Emit visible names into a debug ranges section.
2892 void DwarfDebug::emitDebugRanges() {
2893 // Start the dwarf ranges section.
2894 Asm->OutStreamer.SwitchSection(
2895 Asm->getObjFileLowering().getDwarfRangesSection());
2897 // Size for our labels.
2898 unsigned char Size = Asm->getDataLayout().getPointerSize();
2900 // Grab the specific ranges for the compile units in the module.
2901 for (DenseMap<const MDNode *, DwarfCompileUnit *>::iterator I = CUMap.begin(),
2904 DwarfCompileUnit *TheCU = I->second;
2906 // Emit a symbol so we can find the beginning of our ranges.
2907 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2909 // Iterate over the misc ranges for the compile units in the module.
2910 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2911 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2912 E = RangeLists.end();
2914 const RangeSpanList &List = *I;
2916 // Emit our symbol so we can find the beginning of the range.
2917 Asm->OutStreamer.EmitLabel(List.getSym());
2919 for (SmallVectorImpl<RangeSpan>::const_iterator
2920 RI = List.getRanges().begin(),
2921 RE = List.getRanges().end();
2923 const RangeSpan &Range = *RI;
2924 // We occasionally have ranges without begin/end labels.
2925 // FIXME: Verify and fix.
2926 const MCSymbol *Begin = Range.getStart();
2927 const MCSymbol *End = Range.getEnd();
2928 Begin ? Asm->OutStreamer.EmitSymbolValue(Begin, Size)
2929 : Asm->OutStreamer.EmitIntValue(0, Size);
2930 End ? Asm->OutStreamer.EmitSymbolValue(End, Size)
2931 : Asm->OutStreamer.EmitIntValue(0, Size);
2934 // And terminate the list with two 0 values.
2935 Asm->OutStreamer.EmitIntValue(0, Size);
2936 Asm->OutStreamer.EmitIntValue(0, Size);
2941 // DWARF5 Experimental Separate Dwarf emitters.
2943 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2944 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2945 // DW_AT_ranges_base, DW_AT_addr_base.
2946 // TODO: Implement DW_AT_ranges_base.
2947 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2949 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2950 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2951 CU->getUniqueID(), Die, CU->getNode(), Asm, this, &SkeletonHolder);
2952 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2953 DwarfInfoSectionSym);
2955 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2956 CU->getNode().getSplitDebugFilename());
2958 // Relocate to the beginning of the addr_base section, else 0 for the
2959 // beginning of the one for this compile unit.
2960 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2961 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2962 DwarfAddrSectionSym);
2964 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2966 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2967 // into an entity. We're using 0, or a NULL label for this.
2968 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2970 // DW_AT_stmt_list is a offset of line number information for this
2971 // compile unit in debug_line section.
2972 // FIXME: Should handle multiple compile units.
2973 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2974 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2976 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2978 if (!CompilationDir.empty())
2979 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2981 addGnuPubAttributes(NewCU, Die);
2983 SkeletonHolder.addUnit(NewCU);
2988 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2989 // compile units that would normally be in debug_info.
2990 void DwarfDebug::emitDebugInfoDWO() {
2991 assert(useSplitDwarf() && "No split dwarf debug info?");
2992 InfoHolder.emitUnits(this,
2993 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2994 DwarfAbbrevDWOSectionSym);
2997 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2998 // abbreviations for the .debug_info.dwo section.
2999 void DwarfDebug::emitDebugAbbrevDWO() {
3000 assert(useSplitDwarf() && "No split dwarf?");
3001 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3004 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3005 // string section and is identical in format to traditional .debug_str
3007 void DwarfDebug::emitDebugStrDWO() {
3008 assert(useSplitDwarf() && "No split dwarf?");
3009 const MCSection *OffSec =
3010 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3011 const MCSymbol *StrSym = DwarfStrSectionSym;
3012 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3016 void DwarfDebug::addDwarfTypeUnitType(uint16_t Language, DIE *RefDie,
3017 DICompositeType CTy) {
3018 DenseMap<const MDNode *,
3019 std::pair<uint64_t, SmallVectorImpl<DIE *> *> >::iterator I =
3020 DwarfTypeUnits.find(CTy);
3021 SmallVector<DIE *, 8> References;
3022 References.push_back(RefDie);
3023 if (I != DwarfTypeUnits.end()) {
3024 if (I->second.second) {
3025 I->second.second->push_back(RefDie);
3029 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3030 DwarfTypeUnit *NewTU =
3031 new DwarfTypeUnit(InfoHolder.getUnits().size(), UnitDie, Language, Asm,
3033 InfoHolder.addUnit(NewTU);
3035 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3038 // Register the type in the DwarfTypeUnits map with a vector of references
3040 // populated whenever a reference is required.
3041 I = DwarfTypeUnits.insert(std::make_pair(
3042 CTy, std::make_pair(0, &References))).first;
3044 // Construct the type, this may, recursively, require more type units that
3045 // may in turn require this type again - in which case they will add DIEs to
3046 // the References vector.
3047 DIE *Die = NewTU->createTypeDIE(CTy);
3049 if (GenerateODRHash && shouldAddODRHash(NewTU, Die))
3050 NewTU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3051 dwarf::DW_FORM_data8,
3052 DIEHash().computeDIEODRSignature(*Die));
3053 // FIXME: This won't handle circularly referential structures, as the DIE
3054 // may have references to other DIEs still under construction and missing
3055 // their signature. Hashing should walk through the signatures to their
3056 // referenced type, or possibly walk the precomputed hashes of related types
3058 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3060 // Remove the References vector and add the type hash.
3061 I->second.first = Signature;
3062 I->second.second = NULL;
3065 useSplitDwarf() ? Asm->getObjFileLowering().getDwarfInfoDWOSection()
3066 : Asm->getObjFileLowering().getDwarfInfoSection(),
3067 // FIXME: This is subtle (using the info section even when
3068 // this CU is in the dwo section) and necessary for the
3069 // current arange code - ideally it should iterate
3070 // skeleton units, not full units, if it's going to reference skeletons
3071 useSplitDwarf() ? NULL : DwarfInfoSectionSym);
3074 // Populate all the signatures.
3075 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3076 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3077 dwarf::DW_FORM_ref_sig8, I->second.first);