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."),
61 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
62 cl::desc("Add the CU hash as the dwo_id."),
66 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
67 cl::desc("Generate GNU-style pubnames and pubtypes"),
71 enum DefaultOnOff { Default, Enable, Disable };
74 static cl::opt<DefaultOnOff>
75 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
76 cl::desc("Output prototype dwarf accelerator tables."),
77 cl::values(clEnumVal(Default, "Default for platform"),
78 clEnumVal(Enable, "Enabled"),
79 clEnumVal(Disable, "Disabled"), clEnumValEnd),
82 static cl::opt<DefaultOnOff>
83 SplitDwarf("split-dwarf", cl::Hidden,
84 cl::desc("Output DWARF5 split debug info."),
85 cl::values(clEnumVal(Default, "Default for platform"),
86 clEnumVal(Enable, "Enabled"),
87 clEnumVal(Disable, "Disabled"), clEnumValEnd),
90 static cl::opt<DefaultOnOff>
91 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
92 cl::desc("Generate DWARF pubnames and pubtypes sections"),
93 cl::values(clEnumVal(Default, "Default for platform"),
94 clEnumVal(Enable, "Enabled"),
95 clEnumVal(Disable, "Disabled"), clEnumValEnd),
98 static cl::opt<unsigned>
99 DwarfVersionNumber("dwarf-version", cl::Hidden,
100 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
103 DwarfCURanges("generate-dwarf-cu-ranges", cl::Hidden,
104 cl::desc("Generate DW_AT_ranges for compile units"),
107 static const char *const DWARFGroupName = "DWARF Emission";
108 static const char *const DbgTimerName = "DWARF Debug Writer";
110 //===----------------------------------------------------------------------===//
114 /// resolve - Look in the DwarfDebug map for the MDNode that
115 /// corresponds to the reference.
116 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
117 return DD->resolve(Ref);
120 DIType DbgVariable::getType() const {
121 DIType Ty = Var.getType();
122 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
123 // addresses instead.
124 if (Var.isBlockByrefVariable()) {
125 /* Byref variables, in Blocks, are declared by the programmer as
126 "SomeType VarName;", but the compiler creates a
127 __Block_byref_x_VarName struct, and gives the variable VarName
128 either the struct, or a pointer to the struct, as its type. This
129 is necessary for various behind-the-scenes things the compiler
130 needs to do with by-reference variables in blocks.
132 However, as far as the original *programmer* is concerned, the
133 variable should still have type 'SomeType', as originally declared.
135 The following function dives into the __Block_byref_x_VarName
136 struct to find the original type of the variable. This will be
137 passed back to the code generating the type for the Debug
138 Information Entry for the variable 'VarName'. 'VarName' will then
139 have the original type 'SomeType' in its debug information.
141 The original type 'SomeType' will be the type of the field named
142 'VarName' inside the __Block_byref_x_VarName struct.
144 NOTE: In order for this to not completely fail on the debugger
145 side, the Debug Information Entry for the variable VarName needs to
146 have a DW_AT_location that tells the debugger how to unwind through
147 the pointers and __Block_byref_x_VarName struct to find the actual
148 value of the variable. The function addBlockByrefType does this. */
150 uint16_t tag = Ty.getTag();
152 if (tag == dwarf::DW_TAG_pointer_type)
153 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
155 DIArray Elements = DICompositeType(subType).getTypeArray();
156 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
157 DIDerivedType DT(Elements.getElement(i));
158 if (getName() == DT.getName())
159 return (resolve(DT.getTypeDerivedFrom()));
165 } // end llvm namespace
167 /// Return Dwarf Version by checking module flags.
168 static unsigned getDwarfVersionFromModule(const Module *M) {
169 Value *Val = M->getModuleFlag("Dwarf Version");
171 return dwarf::DWARF_VERSION;
172 return cast<ConstantInt>(Val)->getZExtValue();
175 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
176 : Asm(A), MMI(Asm->MMI), FirstCU(0), SourceIdMap(DIEValueAllocator),
177 PrevLabel(NULL), GlobalRangeCount(0),
178 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
179 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
181 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
182 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
183 DwarfAddrSectionSym = 0;
184 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
185 FunctionBeginSym = FunctionEndSym = 0;
189 // Turn on accelerator tables for Darwin by default, pubnames by
190 // default for non-Darwin, and handle split dwarf.
191 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
193 if (DwarfAccelTables == Default)
194 HasDwarfAccelTables = IsDarwin;
196 HasDwarfAccelTables = DwarfAccelTables == Enable;
198 if (SplitDwarf == Default)
199 HasSplitDwarf = false;
201 HasSplitDwarf = SplitDwarf == Enable;
203 if (DwarfPubSections == Default)
204 HasDwarfPubSections = !IsDarwin;
206 HasDwarfPubSections = DwarfPubSections == Enable;
208 DwarfVersion = DwarfVersionNumber
210 : getDwarfVersionFromModule(MMI->getModule());
213 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
218 // Switch to the specified MCSection and emit an assembler
219 // temporary label to it if SymbolStem is specified.
220 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
221 const char *SymbolStem = 0) {
222 Asm->OutStreamer.SwitchSection(Section);
226 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
227 Asm->OutStreamer.EmitLabel(TmpSym);
231 DwarfFile::~DwarfFile() {
232 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
237 MCSymbol *DwarfFile::getStringPoolSym() {
238 return Asm->GetTempSymbol(StringPref);
241 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
242 std::pair<MCSymbol *, unsigned> &Entry =
243 StringPool.GetOrCreateValue(Str).getValue();
247 Entry.second = NextStringPoolNumber++;
248 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
251 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
252 std::pair<MCSymbol *, unsigned> &Entry =
253 StringPool.GetOrCreateValue(Str).getValue();
257 Entry.second = NextStringPoolNumber++;
258 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
262 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym) {
263 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
266 unsigned DwarfFile::getAddrPoolIndex(const MCExpr *Sym) {
267 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
268 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
270 ++NextAddrPoolNumber;
271 return P.first->second;
274 // Define a unique number for the abbreviation.
276 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
277 // Check the set for priors.
278 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
280 // If it's newly added.
281 if (InSet == &Abbrev) {
282 // Add to abbreviation list.
283 Abbreviations.push_back(&Abbrev);
285 // Assign the vector position + 1 as its number.
286 Abbrev.setNumber(Abbreviations.size());
288 // Assign existing abbreviation number.
289 Abbrev.setNumber(InSet->getNumber());
293 static bool isObjCClass(StringRef Name) {
294 return Name.startswith("+") || Name.startswith("-");
297 static bool hasObjCCategory(StringRef Name) {
298 if (!isObjCClass(Name))
301 return Name.find(") ") != StringRef::npos;
304 static void getObjCClassCategory(StringRef In, StringRef &Class,
305 StringRef &Category) {
306 if (!hasObjCCategory(In)) {
307 Class = In.slice(In.find('[') + 1, In.find(' '));
312 Class = In.slice(In.find('[') + 1, In.find('('));
313 Category = In.slice(In.find('[') + 1, In.find(' '));
317 static StringRef getObjCMethodName(StringRef In) {
318 return In.slice(In.find(' ') + 1, In.find(']'));
321 // Helper for sorting sections into a stable output order.
322 static bool SectionSort(const MCSection *A, const MCSection *B) {
323 std::string LA = (A ? A->getLabelBeginName() : "");
324 std::string LB = (B ? B->getLabelBeginName() : "");
328 // Add the various names to the Dwarf accelerator table names.
329 // TODO: Determine whether or not we should add names for programs
330 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
331 // is only slightly different than the lookup of non-standard ObjC names.
332 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
333 if (!SP.isDefinition())
335 TheU->addAccelName(SP.getName(), Die);
337 // If the linkage name is different than the name, go ahead and output
338 // that as well into the name table.
339 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
340 TheU->addAccelName(SP.getLinkageName(), Die);
342 // If this is an Objective-C selector name add it to the ObjC accelerator
344 if (isObjCClass(SP.getName())) {
345 StringRef Class, Category;
346 getObjCClassCategory(SP.getName(), Class, Category);
347 TheU->addAccelObjC(Class, Die);
349 TheU->addAccelObjC(Category, Die);
350 // Also add the base method name to the name table.
351 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
355 /// isSubprogramContext - Return true if Context is either a subprogram
356 /// or another context nested inside a subprogram.
357 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
360 DIDescriptor D(Context);
361 if (D.isSubprogram())
364 return isSubprogramContext(resolve(DIType(Context).getContext()));
368 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
369 // and DW_AT_high_pc attributes. If there are global variables in this
370 // scope then create and insert DIEs for these variables.
371 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
373 DIE *SPDie = SPCU->getDIE(SP);
375 assert(SPDie && "Unable to find subprogram DIE!");
377 // If we're updating an abstract DIE, then we will be adding the children and
378 // object pointer later on. But what we don't want to do is process the
379 // concrete DIE twice.
380 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
381 // Pick up abstract subprogram DIE.
383 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
384 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
386 DISubprogram SPDecl = SP.getFunctionDeclaration();
387 if (!SPDecl.isSubprogram()) {
388 // There is not any need to generate specification DIE for a function
389 // defined at compile unit level. If a function is defined inside another
390 // function then gdb prefers the definition at top level and but does not
391 // expect specification DIE in parent function. So avoid creating
392 // specification DIE for a function defined inside a function.
393 DIScope SPContext = resolve(SP.getContext());
394 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
395 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
396 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
399 DICompositeType SPTy = SP.getType();
400 DIArray Args = SPTy.getTypeArray();
401 uint16_t SPTag = SPTy.getTag();
402 if (SPTag == dwarf::DW_TAG_subroutine_type)
403 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
405 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
406 DIType ATy(Args.getElement(i));
407 SPCU->addType(Arg, ATy);
408 if (ATy.isArtificial())
409 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
410 if (ATy.isObjectPointer())
411 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
413 DIE *SPDeclDie = SPDie;
414 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
415 *SPCU->getUnitDie());
416 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
421 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc, FunctionBeginSym);
422 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc, FunctionEndSym);
424 // Add this range to the list of ranges for the CU.
425 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
426 SPCU->addRange(llvm_move(Span));
428 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
429 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
430 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
432 // Add name to the name table, we do this here because we're guaranteed
433 // to have concrete versions of our DW_TAG_subprogram nodes.
434 addSubprogramNames(SPCU, SP, SPDie);
439 /// Check whether we should create a DIE for the given Scope, return true
440 /// if we don't create a DIE (the corresponding DIE is null).
441 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
442 if (Scope->isAbstractScope())
445 // We don't create a DIE if there is no Range.
446 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
450 if (Ranges.size() > 1)
453 // We don't create a DIE if we have a single Range and the end label
455 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
456 MCSymbol *End = getLabelAfterInsn(RI->second);
460 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
461 dwarf::Attribute A, const MCSymbol *L,
462 const MCSymbol *Sec) {
463 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
464 U->addSectionLabel(D, A, L);
466 U->addSectionDelta(D, A, L, Sec);
469 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
470 const SmallVectorImpl<InsnRange> &Range) {
471 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
472 // emitting it appropriately.
473 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
474 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
475 DwarfDebugRangeSectionSym);
477 RangeSpanList List(RangeSym);
478 for (SmallVectorImpl<InsnRange>::const_iterator RI = Range.begin(),
481 RangeSpan Span(getLabelBeforeInsn(RI->first),
482 getLabelAfterInsn(RI->second));
483 List.addRange(llvm_move(Span));
486 // Add the range list to the set of ranges to be emitted.
487 TheCU->addRangeList(llvm_move(List));
490 // Construct new DW_TAG_lexical_block for this scope and attach
491 // DW_AT_low_pc/DW_AT_high_pc labels.
492 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
493 LexicalScope *Scope) {
494 if (isLexicalScopeDIENull(Scope))
497 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
498 if (Scope->isAbstractScope())
501 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
503 // If we have multiple ranges, emit them into the range section.
504 if (ScopeRanges.size() > 1) {
505 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
509 // Construct the address range for this DIE.
510 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
511 MCSymbol *Start = getLabelBeforeInsn(RI->first);
512 MCSymbol *End = getLabelAfterInsn(RI->second);
513 assert(End && "End label should not be null!");
515 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
516 assert(End->isDefined() && "Invalid end label for an inlined scope!");
518 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
519 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
524 // This scope represents inlined body of a function. Construct DIE to
525 // represent this concrete inlined copy of the function.
526 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
527 LexicalScope *Scope) {
528 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
529 assert(!ScopeRanges.empty() &&
530 "LexicalScope does not have instruction markers!");
532 if (!Scope->getScopeNode())
534 DIScope DS(Scope->getScopeNode());
535 DISubprogram InlinedSP = getDISubprogram(DS);
536 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
538 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
542 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
543 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
545 // If we have multiple ranges, emit them into the range section.
546 if (ScopeRanges.size() > 1)
547 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
549 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
550 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
551 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
553 if (StartLabel == 0 || EndLabel == 0)
554 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
556 assert(StartLabel->isDefined() &&
557 "Invalid starting label for an inlined scope!");
558 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
560 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
561 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
564 InlinedSubprogramDIEs.insert(OriginDIE);
566 // Add the call site information to the DIE.
567 DILocation DL(Scope->getInlinedAt());
568 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
569 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
570 TheCU->getUniqueID()));
571 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
573 // Add name to the name table, we do this here because we're guaranteed
574 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
575 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
580 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
582 SmallVectorImpl<DIE *> &Children) {
583 DIE *ObjectPointer = NULL;
585 // Collect arguments for current function.
586 if (LScopes.isCurrentFunctionScope(Scope))
587 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
588 if (DbgVariable *ArgDV = CurrentFnArguments[i])
590 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
591 Children.push_back(Arg);
592 if (ArgDV->isObjectPointer())
596 // Collect lexical scope children first.
597 const SmallVectorImpl<DbgVariable *> &Variables =
598 ScopeVariables.lookup(Scope);
599 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
600 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
601 Scope->isAbstractScope())) {
602 Children.push_back(Variable);
603 if (Variables[i]->isObjectPointer())
604 ObjectPointer = Variable;
606 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
607 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
608 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
609 Children.push_back(Nested);
610 return ObjectPointer;
613 // Construct a DIE for this scope.
614 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
615 LexicalScope *Scope) {
616 if (!Scope || !Scope->getScopeNode())
619 DIScope DS(Scope->getScopeNode());
621 SmallVector<DIE *, 8> Children;
622 DIE *ObjectPointer = NULL;
623 bool ChildrenCreated = false;
625 // We try to create the scope DIE first, then the children DIEs. This will
626 // avoid creating un-used children then removing them later when we find out
627 // the scope DIE is null.
628 DIE *ScopeDIE = NULL;
629 if (Scope->getInlinedAt())
630 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
631 else if (DS.isSubprogram()) {
632 ProcessedSPNodes.insert(DS);
633 if (Scope->isAbstractScope()) {
634 ScopeDIE = TheCU->getDIE(DS);
635 // Note down abstract DIE.
637 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
639 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
641 // Early exit when we know the scope DIE is going to be null.
642 if (isLexicalScopeDIENull(Scope))
645 // We create children here when we know the scope DIE is not going to be
646 // null and the children will be added to the scope DIE.
647 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
648 ChildrenCreated = true;
650 // There is no need to emit empty lexical block DIE.
651 std::pair<ImportedEntityMap::const_iterator,
652 ImportedEntityMap::const_iterator> Range =
654 ScopesWithImportedEntities.begin(),
655 ScopesWithImportedEntities.end(),
656 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
658 if (Children.empty() && Range.first == Range.second)
660 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
661 assert(ScopeDIE && "Scope DIE should not be null.");
662 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
664 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
668 assert(Children.empty() &&
669 "We create children only when the scope DIE is not null.");
672 if (!ChildrenCreated)
673 // We create children when the scope DIE is not null.
674 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
677 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
680 ScopeDIE->addChild(*I);
682 if (DS.isSubprogram() && ObjectPointer != NULL)
683 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
688 // Look up the source id with the given directory and source file names.
689 // If none currently exists, create a new id and insert it in the
690 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
692 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName, StringRef DirName,
694 // If we use .loc in assembly, we can't separate .file entries according to
695 // compile units. Thus all files will belong to the default compile unit.
697 // FIXME: add a better feature test than hasRawTextSupport. Even better,
698 // extend .file to support this.
699 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
702 // If FE did not provide a file name, then assume stdin.
703 if (FileName.empty())
704 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
706 // TODO: this might not belong here. See if we can factor this better.
707 if (DirName == CompilationDir)
710 // FileIDCUMap stores the current ID for the given compile unit.
711 unsigned SrcId = FileIDCUMap[CUID] + 1;
713 // We look up the CUID/file/dir by concatenating them with a zero byte.
714 SmallString<128> NamePair;
715 NamePair += utostr(CUID);
718 NamePair += '\0'; // Zero bytes are not allowed in paths.
719 NamePair += FileName;
721 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
722 if (Ent.getValue() != SrcId)
723 return Ent.getValue();
725 FileIDCUMap[CUID] = SrcId;
726 // Print out a .file directive to specify files for .loc directives.
727 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
732 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
733 if (!GenerateGnuPubSections)
736 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubnames,
737 Asm->GetTempSymbol("gnu_pubnames", U->getUniqueID()),
738 DwarfGnuPubNamesSectionSym);
740 addSectionLabel(Asm, U, D, dwarf::DW_AT_GNU_pubtypes,
741 Asm->GetTempSymbol("gnu_pubtypes", U->getUniqueID()),
742 DwarfGnuPubTypesSectionSym);
745 // Create new DwarfCompileUnit for the given metadata node with tag
746 // DW_TAG_compile_unit.
747 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
748 StringRef FN = DIUnit.getFilename();
749 CompilationDir = DIUnit.getDirectory();
751 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
752 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
753 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
754 InfoHolder.addUnit(NewCU);
756 FileIDCUMap[NewCU->getUniqueID()] = 0;
757 // Call this to emit a .file directive if it wasn't emitted for the source
758 // file this CU comes from yet.
759 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
761 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
762 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
763 DIUnit.getLanguage());
764 NewCU->addString(Die, dwarf::DW_AT_name, FN);
766 // Define start line table label for each Compile Unit.
767 MCSymbol *LineTableStartSym =
768 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
769 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
770 NewCU->getUniqueID());
772 // Use a single line table if we are using .loc and generating assembly.
774 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
775 (NewCU->getUniqueID() == 0);
777 if (!useSplitDwarf()) {
778 // DW_AT_stmt_list is a offset of line number information for this
779 // compile unit in debug_line section. For split dwarf this is
780 // left in the skeleton CU and so not included.
781 // The line table entries are not always emitted in assembly, so it
782 // is not okay to use line_table_start here.
783 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
784 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
785 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
786 : LineTableStartSym);
787 else if (UseTheFirstCU)
788 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
790 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list, LineTableStartSym,
791 DwarfLineSectionSym);
793 // If we're using split dwarf the compilation dir is going to be in the
794 // skeleton CU and so we don't need to duplicate it here.
795 if (!CompilationDir.empty())
796 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
798 addGnuPubAttributes(NewCU, Die);
801 if (DIUnit.isOptimized())
802 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
804 StringRef Flags = DIUnit.getFlags();
806 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
808 if (unsigned RVer = DIUnit.getRunTimeVersion())
809 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
810 dwarf::DW_FORM_data1, RVer);
815 if (useSplitDwarf()) {
816 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
817 DwarfInfoDWOSectionSym);
818 NewCU->setSkeleton(constructSkeletonCU(NewCU));
820 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
821 DwarfInfoSectionSym);
823 CUMap.insert(std::make_pair(DIUnit, NewCU));
824 CUDieMap.insert(std::make_pair(Die, NewCU));
828 // Construct subprogram DIE.
829 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
831 // FIXME: We should only call this routine once, however, during LTO if a
832 // program is defined in multiple CUs we could end up calling it out of
833 // beginModule as we walk the CUs.
835 DwarfCompileUnit *&CURef = SPMap[N];
841 if (!SP.isDefinition())
842 // This is a method declaration which will be handled while constructing
846 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
848 // Expose as a global name.
849 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
852 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
854 DIImportedEntity Module(N);
855 if (!Module.Verify())
857 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
858 constructImportedEntityDIE(TheCU, Module, D);
861 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
862 const MDNode *N, DIE *Context) {
863 DIImportedEntity Module(N);
864 if (!Module.Verify())
866 return constructImportedEntityDIE(TheCU, Module, Context);
869 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
870 const DIImportedEntity &Module,
872 assert(Module.Verify() &&
873 "Use one of the MDNode * overloads to handle invalid metadata");
874 assert(Context && "Should always have a context for an imported_module");
875 DIE *IMDie = new DIE(Module.getTag());
876 TheCU->insertDIE(Module, IMDie);
878 DIDescriptor Entity = Module.getEntity();
879 if (Entity.isNameSpace())
880 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
881 else if (Entity.isSubprogram())
882 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
883 else if (Entity.isType())
884 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
886 EntityDie = TheCU->getDIE(Entity);
887 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
888 Module.getContext().getDirectory(),
889 TheCU->getUniqueID());
890 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
891 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
892 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
893 StringRef Name = Module.getName();
895 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
896 Context->addChild(IMDie);
899 // Emit all Dwarf sections that should come prior to the content. Create
900 // global DIEs and emit initial debug info sections. This is invoked by
901 // the target AsmPrinter.
902 void DwarfDebug::beginModule() {
903 if (DisableDebugInfoPrinting)
906 const Module *M = MMI->getModule();
908 // If module has named metadata anchors then use them, otherwise scan the
909 // module using debug info finder to collect debug info.
910 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
913 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
915 // Emit initial sections so we can reference labels later.
918 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
919 DICompileUnit CUNode(CU_Nodes->getOperand(i));
920 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode);
921 DIArray ImportedEntities = CUNode.getImportedEntities();
922 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
923 ScopesWithImportedEntities.push_back(std::make_pair(
924 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
925 ImportedEntities.getElement(i)));
926 std::sort(ScopesWithImportedEntities.begin(),
927 ScopesWithImportedEntities.end(), less_first());
928 DIArray GVs = CUNode.getGlobalVariables();
929 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
930 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
931 DIArray SPs = CUNode.getSubprograms();
932 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
933 constructSubprogramDIE(CU, SPs.getElement(i));
934 DIArray EnumTypes = CUNode.getEnumTypes();
935 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
936 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
937 DIArray RetainedTypes = CUNode.getRetainedTypes();
938 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
939 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
940 // Emit imported_modules last so that the relevant context is already
942 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
943 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
946 // Tell MMI that we have debug info.
947 MMI->setDebugInfoAvailability(true);
949 // Prime section data.
950 SectionMap[Asm->getObjFileLowering().getTextSection()];
953 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
954 void DwarfDebug::computeInlinedDIEs() {
955 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
956 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
957 AE = InlinedSubprogramDIEs.end();
960 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
962 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
963 AE = AbstractSPDies.end();
965 DIE *ISP = AI->second;
966 if (InlinedSubprogramDIEs.count(ISP))
968 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
972 // Collect info for variables that were optimized out.
973 void DwarfDebug::collectDeadVariables() {
974 const Module *M = MMI->getModule();
976 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
977 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
978 DICompileUnit TheCU(CU_Nodes->getOperand(i));
979 DIArray Subprograms = TheCU.getSubprograms();
980 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
981 DISubprogram SP(Subprograms.getElement(i));
982 if (ProcessedSPNodes.count(SP) != 0)
984 if (!SP.isSubprogram())
986 if (!SP.isDefinition())
988 DIArray Variables = SP.getVariables();
989 if (Variables.getNumElements() == 0)
992 // Construct subprogram DIE and add variables DIEs.
993 DwarfCompileUnit *SPCU =
994 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
995 assert(SPCU && "Unable to find Compile Unit!");
996 // FIXME: See the comment in constructSubprogramDIE about duplicate
998 constructSubprogramDIE(SPCU, SP);
999 DIE *SPDIE = SPCU->getDIE(SP);
1000 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1001 DIVariable DV(Variables.getElement(vi));
1002 if (!DV.isVariable())
1004 DbgVariable NewVar(DV, NULL, this);
1005 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1006 SPDIE->addChild(VariableDIE);
1013 void DwarfDebug::finalizeModuleInfo() {
1014 // Collect info for variables that were optimized out.
1015 collectDeadVariables();
1017 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1018 computeInlinedDIEs();
1020 // Handle anything that needs to be done on a per-unit basis after
1021 // all other generation.
1022 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
1023 E = getUnits().end();
1025 DwarfUnit *TheU = *I;
1026 // Emit DW_AT_containing_type attribute to connect types with their
1027 // vtable holding type.
1028 TheU->constructContainingTypeDIEs();
1030 // Add CU specific attributes if we need to add any.
1031 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
1032 // If we're splitting the dwarf out now that we've got the entire
1033 // CU then add the dwo id to it.
1034 DwarfCompileUnit *SkCU =
1035 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
1036 if (useSplitDwarf()) {
1037 // This should be a unique identifier when we want to build .dwp files.
1039 if (GenerateCUHash) {
1041 ID = CUHash.computeCUSignature(*TheU->getUnitDie());
1043 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1044 dwarf::DW_FORM_data8, ID);
1045 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1046 dwarf::DW_FORM_data8, ID);
1049 // If we have code split among multiple sections or we've requested
1050 // it then emit a DW_AT_ranges attribute on the unit that will remain
1051 // in the .o file, otherwise add a DW_AT_low_pc.
1052 // FIXME: Also add a high pc if we can.
1053 // FIXME: We should use ranges if we have multiple compile units or
1054 // allow reordering of code ala .subsections_via_symbols in mach-o.
1055 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
1056 if (useCURanges() && TheU->getRanges().size())
1057 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
1058 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
1059 DwarfDebugRangeSectionSym);
1061 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
1066 // Compute DIE offsets and sizes.
1067 InfoHolder.computeSizeAndOffsets();
1068 if (useSplitDwarf())
1069 SkeletonHolder.computeSizeAndOffsets();
1072 void DwarfDebug::endSections() {
1073 // Filter labels by section.
1074 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1075 const SymbolCU &SCU = ArangeLabels[n];
1076 if (SCU.Sym->isInSection()) {
1077 // Make a note of this symbol and it's section.
1078 const MCSection *Section = &SCU.Sym->getSection();
1079 if (!Section->getKind().isMetadata())
1080 SectionMap[Section].push_back(SCU);
1082 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1083 // appear in the output. This sucks as we rely on sections to build
1084 // arange spans. We can do it without, but it's icky.
1085 SectionMap[NULL].push_back(SCU);
1089 // Build a list of sections used.
1090 std::vector<const MCSection *> Sections;
1091 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1093 const MCSection *Section = it->first;
1094 Sections.push_back(Section);
1097 // Sort the sections into order.
1098 // This is only done to ensure consistent output order across different runs.
1099 std::sort(Sections.begin(), Sections.end(), SectionSort);
1101 // Add terminating symbols for each section.
1102 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1103 const MCSection *Section = Sections[ID];
1104 MCSymbol *Sym = NULL;
1107 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1108 // if we know the section name up-front. For user-created sections, the
1110 // label may not be valid to use as a label. (section names can use a
1112 // set of characters on some systems)
1113 Sym = Asm->GetTempSymbol("debug_end", ID);
1114 Asm->OutStreamer.SwitchSection(Section);
1115 Asm->OutStreamer.EmitLabel(Sym);
1118 // Insert a final terminator.
1119 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1122 // For now only turn on CU ranges if we've explicitly asked for it,
1123 // we have -ffunction-sections enabled, or we've emitted a function
1124 // into a unique section. At this point all sections should be finalized
1125 // except for dwarf sections.
1126 HasCURanges = DwarfCURanges || Asm->TM.debugUseUniqueSections() ||
1127 TargetMachine::getFunctionSections();
1130 // Emit all Dwarf sections that should come after the content.
1131 void DwarfDebug::endModule() {
1138 // End any existing sections.
1139 // TODO: Does this need to happen?
1142 // Finalize the debug info for the module.
1143 finalizeModuleInfo();
1147 // Emit all the DIEs into a debug info section.
1150 // Corresponding abbreviations into a abbrev section.
1151 emitAbbreviations();
1153 // Emit info into a debug loc section.
1156 // Emit info into a debug aranges section.
1159 // Emit info into a debug ranges section.
1162 if (useSplitDwarf()) {
1165 emitDebugAbbrevDWO();
1166 // Emit DWO addresses.
1167 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1170 // Emit info into the dwarf accelerator table sections.
1171 if (useDwarfAccelTables()) {
1174 emitAccelNamespaces();
1178 // Emit the pubnames and pubtypes sections if requested.
1179 if (HasDwarfPubSections) {
1180 emitDebugPubNames(GenerateGnuPubSections);
1181 emitDebugPubTypes(GenerateGnuPubSections);
1187 // Reset these for the next Module if we have one.
1191 // Find abstract variable, if any, associated with Var.
1192 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1193 DebugLoc ScopeLoc) {
1194 LLVMContext &Ctx = DV->getContext();
1195 // More then one inlined variable corresponds to one abstract variable.
1196 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1197 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1199 return AbsDbgVariable;
1201 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1205 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1206 addScopeVariable(Scope, AbsDbgVariable);
1207 AbstractVariables[Var] = AbsDbgVariable;
1208 return AbsDbgVariable;
1211 // If Var is a current function argument then add it to CurrentFnArguments list.
1212 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1213 if (!LScopes.isCurrentFunctionScope(Scope))
1215 DIVariable DV = Var->getVariable();
1216 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1218 unsigned ArgNo = DV.getArgNumber();
1222 size_t Size = CurrentFnArguments.size();
1224 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1225 // llvm::Function argument size is not good indicator of how many
1226 // arguments does the function have at source level.
1228 CurrentFnArguments.resize(ArgNo * 2);
1229 CurrentFnArguments[ArgNo - 1] = Var;
1233 // Collect variable information from side table maintained by MMI.
1234 void DwarfDebug::collectVariableInfoFromMMITable(
1235 SmallPtrSet<const MDNode *, 16> &Processed) {
1236 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1237 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1240 const MDNode *Var = VI->first;
1243 Processed.insert(Var);
1245 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1247 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1249 // If variable scope is not found then skip this variable.
1253 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1254 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1255 RegVar->setFrameIndex(VP.first);
1256 if (!addCurrentFnArgument(RegVar, Scope))
1257 addScopeVariable(Scope, RegVar);
1259 AbsDbgVariable->setFrameIndex(VP.first);
1263 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1265 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1266 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1267 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1268 MI->getOperand(0).getReg() &&
1269 (MI->getOperand(1).isImm() ||
1270 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1273 // Get .debug_loc entry for the instruction range starting at MI.
1274 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1275 const MCSymbol *FLabel,
1276 const MCSymbol *SLabel,
1277 const MachineInstr *MI) {
1278 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1280 assert(MI->getNumOperands() == 3);
1281 if (MI->getOperand(0).isReg()) {
1282 MachineLocation MLoc;
1283 // If the second operand is an immediate, this is a
1284 // register-indirect address.
1285 if (!MI->getOperand(1).isImm())
1286 MLoc.set(MI->getOperand(0).getReg());
1288 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1289 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1291 if (MI->getOperand(0).isImm())
1292 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1293 if (MI->getOperand(0).isFPImm())
1294 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1295 if (MI->getOperand(0).isCImm())
1296 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1298 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1301 // Find variables for each lexical scope.
1303 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1305 // Grab the variable info that was squirreled away in the MMI side-table.
1306 collectVariableInfoFromMMITable(Processed);
1308 for (SmallVectorImpl<const MDNode *>::const_iterator
1309 UVI = UserVariables.begin(),
1310 UVE = UserVariables.end();
1311 UVI != UVE; ++UVI) {
1312 const MDNode *Var = *UVI;
1313 if (Processed.count(Var))
1316 // History contains relevant DBG_VALUE instructions for Var and instructions
1318 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1319 if (History.empty())
1321 const MachineInstr *MInsn = History.front();
1324 LexicalScope *Scope = NULL;
1325 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1326 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1327 Scope = LScopes.getCurrentFunctionScope();
1328 else if (MDNode *IA = DV.getInlinedAt())
1329 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1331 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1332 // If variable scope is not found then skip this variable.
1336 Processed.insert(DV);
1337 assert(MInsn->isDebugValue() && "History must begin with debug value");
1338 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1339 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1340 if (!addCurrentFnArgument(RegVar, Scope))
1341 addScopeVariable(Scope, RegVar);
1343 AbsVar->setMInsn(MInsn);
1345 // Simplify ranges that are fully coalesced.
1346 if (History.size() <= 1 ||
1347 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1348 RegVar->setMInsn(MInsn);
1352 // Handle multiple DBG_VALUE instructions describing one variable.
1353 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1355 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1356 HI = History.begin(),
1359 const MachineInstr *Begin = *HI;
1360 assert(Begin->isDebugValue() && "Invalid History entry");
1362 // Check if DBG_VALUE is truncating a range.
1363 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1364 !Begin->getOperand(0).getReg())
1367 // Compute the range for a register location.
1368 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1369 const MCSymbol *SLabel = 0;
1372 // If Begin is the last instruction in History then its value is valid
1373 // until the end of the function.
1374 SLabel = FunctionEndSym;
1376 const MachineInstr *End = HI[1];
1377 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1378 << "\t" << *Begin << "\t" << *End << "\n");
1379 if (End->isDebugValue())
1380 SLabel = getLabelBeforeInsn(End);
1382 // End is a normal instruction clobbering the range.
1383 SLabel = getLabelAfterInsn(End);
1384 assert(SLabel && "Forgot label after clobber instruction");
1389 // The value is valid until the next DBG_VALUE or clobber.
1390 DotDebugLocEntries.push_back(
1391 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1393 DotDebugLocEntries.push_back(DotDebugLocEntry());
1396 // Collect info for variables that were optimized out.
1397 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1398 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1399 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1400 DIVariable DV(Variables.getElement(i));
1401 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1403 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1404 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1408 // Return Label preceding the instruction.
1409 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1410 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1411 assert(Label && "Didn't insert label before instruction");
1415 // Return Label immediately following the instruction.
1416 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1417 return LabelsAfterInsn.lookup(MI);
1420 // Process beginning of an instruction.
1421 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1424 // Check if source location changes, but ignore DBG_VALUE locations.
1425 if (!MI->isDebugValue()) {
1426 DebugLoc DL = MI->getDebugLoc();
1427 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1430 if (DL == PrologEndLoc) {
1431 Flags |= DWARF2_FLAG_PROLOGUE_END;
1432 PrologEndLoc = DebugLoc();
1434 if (PrologEndLoc.isUnknown())
1435 Flags |= DWARF2_FLAG_IS_STMT;
1437 if (!DL.isUnknown()) {
1438 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1439 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1441 recordSourceLine(0, 0, 0, 0);
1445 // Insert labels where requested.
1446 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1447 LabelsBeforeInsn.find(MI);
1450 if (I == LabelsBeforeInsn.end())
1453 // Label already assigned.
1458 PrevLabel = MMI->getContext().CreateTempSymbol();
1459 Asm->OutStreamer.EmitLabel(PrevLabel);
1461 I->second = PrevLabel;
1464 // Process end of an instruction.
1465 void DwarfDebug::endInstruction() {
1467 // Don't create a new label after DBG_VALUE instructions.
1468 // They don't generate code.
1469 if (!CurMI->isDebugValue())
1472 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1473 LabelsAfterInsn.find(CurMI);
1477 if (I == LabelsAfterInsn.end())
1480 // Label already assigned.
1484 // We need a label after this instruction.
1486 PrevLabel = MMI->getContext().CreateTempSymbol();
1487 Asm->OutStreamer.EmitLabel(PrevLabel);
1489 I->second = PrevLabel;
1492 // Each LexicalScope has first instruction and last instruction to mark
1493 // beginning and end of a scope respectively. Create an inverse map that list
1494 // scopes starts (and ends) with an instruction. One instruction may start (or
1495 // end) multiple scopes. Ignore scopes that are not reachable.
1496 void DwarfDebug::identifyScopeMarkers() {
1497 SmallVector<LexicalScope *, 4> WorkList;
1498 WorkList.push_back(LScopes.getCurrentFunctionScope());
1499 while (!WorkList.empty()) {
1500 LexicalScope *S = WorkList.pop_back_val();
1502 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1503 if (!Children.empty())
1504 for (SmallVectorImpl<LexicalScope *>::const_iterator
1505 SI = Children.begin(),
1506 SE = Children.end();
1508 WorkList.push_back(*SI);
1510 if (S->isAbstractScope())
1513 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1516 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1519 assert(RI->first && "InsnRange does not have first instruction!");
1520 assert(RI->second && "InsnRange does not have second instruction!");
1521 requestLabelBeforeInsn(RI->first);
1522 requestLabelAfterInsn(RI->second);
1527 // Get MDNode for DebugLoc's scope.
1528 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1529 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1530 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1531 return DL.getScope(Ctx);
1534 // Walk up the scope chain of given debug loc and find line number info
1535 // for the function.
1536 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1537 const MDNode *Scope = getScopeNode(DL, Ctx);
1538 DISubprogram SP = getDISubprogram(Scope);
1539 if (SP.isSubprogram()) {
1540 // Check for number of operands since the compatibility is
1542 if (SP->getNumOperands() > 19)
1543 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1545 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1551 // Gather pre-function debug information. Assumes being called immediately
1552 // after the function entry point has been emitted.
1553 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1556 // If there's no debug info for the function we're not going to do anything.
1557 if (!MMI->hasDebugInfo())
1560 // Grab the lexical scopes for the function, if we don't have any of those
1561 // then we're not going to be able to do anything.
1562 LScopes.initialize(*MF);
1563 if (LScopes.empty())
1566 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1568 // Make sure that each lexical scope will have a begin/end label.
1569 identifyScopeMarkers();
1571 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1572 // belongs to so that we add to the correct per-cu line table in the
1574 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1575 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1576 assert(TheCU && "Unable to find compile unit!");
1577 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1578 // Use a single line table if we are using .loc and generating assembly.
1579 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1581 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1583 // Emit a label for the function so that we have a beginning address.
1584 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1585 // Assumes in correct section after the entry point.
1586 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1588 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1589 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1590 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1592 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1594 bool AtBlockEntry = true;
1595 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1597 const MachineInstr *MI = II;
1599 if (MI->isDebugValue()) {
1600 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1602 // Keep track of user variables.
1604 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1606 // Variable is in a register, we need to check for clobbers.
1607 if (isDbgValueInDefinedReg(MI))
1608 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1610 // Check the history of this variable.
1611 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1612 if (History.empty()) {
1613 UserVariables.push_back(Var);
1614 // The first mention of a function argument gets the FunctionBeginSym
1615 // label, so arguments are visible when breaking at function entry.
1617 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1618 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1619 LabelsBeforeInsn[MI] = FunctionBeginSym;
1621 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1622 const MachineInstr *Prev = History.back();
1623 if (Prev->isDebugValue()) {
1624 // Coalesce identical entries at the end of History.
1625 if (History.size() >= 2 &&
1626 Prev->isIdenticalTo(History[History.size() - 2])) {
1627 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1628 << "\t" << *Prev << "\t"
1629 << *History[History.size() - 2] << "\n");
1633 // Terminate old register assignments that don't reach MI;
1634 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1635 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1636 isDbgValueInDefinedReg(Prev)) {
1637 // Previous register assignment needs to terminate at the end of
1639 MachineBasicBlock::const_iterator LastMI =
1640 PrevMBB->getLastNonDebugInstr();
1641 if (LastMI == PrevMBB->end()) {
1642 // Drop DBG_VALUE for empty range.
1643 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1644 << "\t" << *Prev << "\n");
1646 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1647 // Terminate after LastMI.
1648 History.push_back(LastMI);
1652 History.push_back(MI);
1654 // Not a DBG_VALUE instruction.
1656 AtBlockEntry = false;
1658 // First known non-DBG_VALUE and non-frame setup location marks
1659 // the beginning of the function body.
1660 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1661 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1662 PrologEndLoc = MI->getDebugLoc();
1664 // Check if the instruction clobbers any registers with debug vars.
1665 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1666 MOE = MI->operands_end();
1667 MOI != MOE; ++MOI) {
1668 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1670 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1673 const MDNode *Var = LiveUserVar[Reg];
1676 // Reg is now clobbered.
1677 LiveUserVar[Reg] = 0;
1679 // Was MD last defined by a DBG_VALUE referring to Reg?
1680 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1681 if (HistI == DbgValues.end())
1683 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1684 if (History.empty())
1686 const MachineInstr *Prev = History.back();
1687 // Sanity-check: Register assignments are terminated at the end of
1689 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1691 // Is the variable still in Reg?
1692 if (!isDbgValueInDefinedReg(Prev) ||
1693 Prev->getOperand(0).getReg() != Reg)
1695 // Var is clobbered. Make sure the next instruction gets a label.
1696 History.push_back(MI);
1703 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1705 SmallVectorImpl<const MachineInstr *> &History = I->second;
1706 if (History.empty())
1709 // Make sure the final register assignments are terminated.
1710 const MachineInstr *Prev = History.back();
1711 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1712 const MachineBasicBlock *PrevMBB = Prev->getParent();
1713 MachineBasicBlock::const_iterator LastMI =
1714 PrevMBB->getLastNonDebugInstr();
1715 if (LastMI == PrevMBB->end())
1716 // Drop DBG_VALUE for empty range.
1718 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1719 // Terminate after LastMI.
1720 History.push_back(LastMI);
1723 // Request labels for the full history.
1724 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1725 const MachineInstr *MI = History[i];
1726 if (MI->isDebugValue())
1727 requestLabelBeforeInsn(MI);
1729 requestLabelAfterInsn(MI);
1733 PrevInstLoc = DebugLoc();
1734 PrevLabel = FunctionBeginSym;
1736 // Record beginning of function.
1737 if (!PrologEndLoc.isUnknown()) {
1738 DebugLoc FnStartDL =
1739 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1741 FnStartDL.getLine(), FnStartDL.getCol(),
1742 FnStartDL.getScope(MF->getFunction()->getContext()),
1743 // We'd like to list the prologue as "not statements" but GDB behaves
1744 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1745 DWARF2_FLAG_IS_STMT);
1749 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1750 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1751 DIVariable DV = Var->getVariable();
1752 // Variables with positive arg numbers are parameters.
1753 if (unsigned ArgNum = DV.getArgNumber()) {
1754 // Keep all parameters in order at the start of the variable list to ensure
1755 // function types are correct (no out-of-order parameters)
1757 // This could be improved by only doing it for optimized builds (unoptimized
1758 // builds have the right order to begin with), searching from the back (this
1759 // would catch the unoptimized case quickly), or doing a binary search
1760 // rather than linear search.
1761 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1762 while (I != Vars.end()) {
1763 unsigned CurNum = (*I)->getVariable().getArgNumber();
1764 // A local (non-parameter) variable has been found, insert immediately
1768 // A later indexed parameter has been found, insert immediately before it.
1769 if (CurNum > ArgNum)
1773 Vars.insert(I, Var);
1777 Vars.push_back(Var);
1780 // Gather and emit post-function debug information.
1781 void DwarfDebug::endFunction(const MachineFunction *MF) {
1782 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1783 // though the beginFunction may not be called at all.
1784 // We should handle both cases.
1788 assert(CurFn == MF);
1791 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1796 // Define end label for subprogram.
1797 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1798 // Assumes in correct section after the entry point.
1799 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1800 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1801 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1803 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1804 collectVariableInfo(ProcessedVars);
1806 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1807 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1808 assert(TheCU && "Unable to find compile unit!");
1810 // Construct abstract scopes.
1811 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1812 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1813 LexicalScope *AScope = AList[i];
1814 DISubprogram SP(AScope->getScopeNode());
1815 if (SP.isSubprogram()) {
1816 // Collect info for variables that were optimized out.
1817 DIArray Variables = SP.getVariables();
1818 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1819 DIVariable DV(Variables.getElement(i));
1820 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1822 // Check that DbgVariable for DV wasn't created earlier, when
1823 // findAbstractVariable() was called for inlined instance of DV.
1824 LLVMContext &Ctx = DV->getContext();
1825 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1826 if (AbstractVariables.lookup(CleanDV))
1828 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1829 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1832 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1833 constructScopeDIE(TheCU, AScope);
1836 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1838 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1839 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1842 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1843 E = ScopeVariables.end();
1845 DeleteContainerPointers(I->second);
1846 ScopeVariables.clear();
1847 DeleteContainerPointers(CurrentFnArguments);
1848 UserVariables.clear();
1850 AbstractVariables.clear();
1851 LabelsBeforeInsn.clear();
1852 LabelsAfterInsn.clear();
1857 // Register a source line with debug info. Returns the unique label that was
1858 // emitted and which provides correspondence to the source line list.
1859 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1865 DIDescriptor Scope(S);
1867 if (Scope.isCompileUnit()) {
1868 DICompileUnit CU(S);
1869 Fn = CU.getFilename();
1870 Dir = CU.getDirectory();
1871 } else if (Scope.isFile()) {
1873 Fn = F.getFilename();
1874 Dir = F.getDirectory();
1875 } else if (Scope.isSubprogram()) {
1877 Fn = SP.getFilename();
1878 Dir = SP.getDirectory();
1879 } else if (Scope.isLexicalBlockFile()) {
1880 DILexicalBlockFile DBF(S);
1881 Fn = DBF.getFilename();
1882 Dir = DBF.getDirectory();
1883 } else if (Scope.isLexicalBlock()) {
1884 DILexicalBlock DB(S);
1885 Fn = DB.getFilename();
1886 Dir = DB.getDirectory();
1888 llvm_unreachable("Unexpected scope info");
1890 Src = getOrCreateSourceID(
1891 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1893 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1896 //===----------------------------------------------------------------------===//
1898 //===----------------------------------------------------------------------===//
1900 // Compute the size and offset of a DIE. The offset is relative to start of the
1901 // CU. It returns the offset after laying out the DIE.
1902 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1903 // Get the children.
1904 const std::vector<DIE *> &Children = Die->getChildren();
1906 // Record the abbreviation.
1907 assignAbbrevNumber(Die->getAbbrev());
1909 // Get the abbreviation for this DIE.
1910 const DIEAbbrev &Abbrev = Die->getAbbrev();
1913 Die->setOffset(Offset);
1915 // Start the size with the size of abbreviation code.
1916 Offset += MCAsmInfo::getULEB128Size(Die->getAbbrevNumber());
1918 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1919 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1921 // Size the DIE attribute values.
1922 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1923 // Size attribute value.
1924 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1926 // Size the DIE children if any.
1927 if (!Children.empty()) {
1928 assert(Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1929 "Children flag not set");
1931 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1932 Offset = computeSizeAndOffset(Children[j], Offset);
1934 // End of children marker.
1935 Offset += sizeof(int8_t);
1938 Die->setSize(Offset - Die->getOffset());
1942 // Compute the size and offset for each DIE.
1943 void DwarfFile::computeSizeAndOffsets() {
1944 // Offset from the first CU in the debug info section is 0 initially.
1945 unsigned SecOffset = 0;
1947 // Iterate over each compile unit and set the size and offsets for each
1948 // DIE within each compile unit. All offsets are CU relative.
1949 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = CUs.begin(),
1952 (*I)->setDebugInfoOffset(SecOffset);
1954 // CU-relative offset is reset to 0 here.
1955 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1956 (*I)->getHeaderSize(); // Unit-specific headers
1958 // EndOffset here is CU-relative, after laying out
1959 // all of the CU DIE.
1960 unsigned EndOffset = computeSizeAndOffset((*I)->getUnitDie(), Offset);
1961 SecOffset += EndOffset;
1965 // Emit initial Dwarf sections with a label at the start of each one.
1966 void DwarfDebug::emitSectionLabels() {
1967 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1969 // Dwarf sections base addresses.
1970 DwarfInfoSectionSym =
1971 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1972 if (useSplitDwarf())
1973 DwarfInfoDWOSectionSym =
1974 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1975 DwarfAbbrevSectionSym =
1976 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1977 if (useSplitDwarf())
1978 DwarfAbbrevDWOSectionSym = emitSectionSym(
1979 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1980 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1982 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1983 emitSectionSym(Asm, MacroInfo);
1985 DwarfLineSectionSym =
1986 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1987 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1988 if (GenerateGnuPubSections) {
1989 DwarfGnuPubNamesSectionSym =
1990 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1991 DwarfGnuPubTypesSectionSym =
1992 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1993 } else if (HasDwarfPubSections) {
1994 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1995 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1998 DwarfStrSectionSym =
1999 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2000 if (useSplitDwarf()) {
2001 DwarfStrDWOSectionSym =
2002 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2003 DwarfAddrSectionSym =
2004 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2006 DwarfDebugRangeSectionSym =
2007 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2009 DwarfDebugLocSectionSym =
2010 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2013 // Recursively emits a debug information entry.
2014 void DwarfDebug::emitDIE(DIE *Die) {
2015 // Get the abbreviation for this DIE.
2016 const DIEAbbrev &Abbrev = Die->getAbbrev();
2018 // Emit the code (index) for the abbreviation.
2019 if (Asm->isVerbose())
2020 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
2021 "] 0x" + Twine::utohexstr(Die->getOffset()) +
2022 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
2023 dwarf::TagString(Abbrev.getTag()));
2024 Asm->EmitULEB128(Abbrev.getNumber());
2026 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2027 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
2029 // Emit the DIE attribute values.
2030 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2031 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2032 dwarf::Form Form = AbbrevData[i].getForm();
2033 assert(Form && "Too many attributes for DIE (check abbreviation)");
2035 if (Asm->isVerbose())
2036 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2039 case dwarf::DW_AT_abstract_origin:
2040 case dwarf::DW_AT_type:
2041 case dwarf::DW_AT_friend:
2042 case dwarf::DW_AT_specification:
2043 case dwarf::DW_AT_import:
2044 case dwarf::DW_AT_containing_type: {
2045 DIEEntry *E = cast<DIEEntry>(Values[i]);
2046 DIE *Origin = E->getEntry();
2047 unsigned Addr = Origin->getOffset();
2048 if (Form == dwarf::DW_FORM_ref_addr) {
2049 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2050 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2051 // section. Origin->getOffset() returns the offset from start of the
2053 DwarfCompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2054 assert(CU && "CUDie should belong to a CU.");
2055 Addr += CU->getDebugInfoOffset();
2056 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2057 Asm->EmitLabelPlusOffset(CU->getSectionSym(), Addr,
2058 DIEEntry::getRefAddrSize(Asm));
2060 Asm->EmitLabelOffsetDifference(CU->getSectionSym(), Addr,
2061 CU->getSectionSym(),
2062 DIEEntry::getRefAddrSize(Asm));
2064 // Make sure Origin belong to the same CU.
2065 assert(Die->getUnit() == Origin->getUnit() &&
2066 "The referenced DIE should belong to the same CU in ref4");
2067 Asm->EmitInt32(Addr);
2071 case dwarf::DW_AT_location: {
2072 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2073 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2074 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2076 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2078 Values[i]->EmitValue(Asm, Form);
2082 case dwarf::DW_AT_accessibility: {
2083 if (Asm->isVerbose()) {
2084 DIEInteger *V = cast<DIEInteger>(Values[i]);
2085 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2087 Values[i]->EmitValue(Asm, Form);
2091 // Emit an attribute using the defined form.
2092 Values[i]->EmitValue(Asm, Form);
2097 // Emit the DIE children if any.
2098 if (Abbrev.getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2099 const std::vector<DIE *> &Children = Die->getChildren();
2101 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2102 emitDIE(Children[j]);
2104 Asm->OutStreamer.AddComment("End Of Children Mark");
2109 // Emit the various dwarf units to the unit section USection with
2110 // the abbreviations going into ASection.
2111 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
2112 const MCSymbol *ASectionSym) {
2113 for (SmallVectorImpl<DwarfUnit *>::iterator I = CUs.begin(), E = CUs.end();
2115 DwarfUnit *TheU = *I;
2116 DIE *Die = TheU->getUnitDie();
2117 const MCSection *USection = TheU->getSection();
2118 Asm->OutStreamer.SwitchSection(USection);
2120 // Emit the compile units header.
2121 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
2123 // Emit size of content not including length itself
2124 Asm->OutStreamer.AddComment("Length of Unit");
2125 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
2127 TheU->emitHeader(ASection, ASectionSym);
2130 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
2134 // Emit the debug info section.
2135 void DwarfDebug::emitDebugInfo() {
2136 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2138 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
2139 DwarfAbbrevSectionSym);
2142 // Emit the abbreviation section.
2143 void DwarfDebug::emitAbbreviations() {
2144 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2146 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2149 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2150 // Check to see if it is worth the effort.
2151 if (!Abbreviations.empty()) {
2152 // Start the debug abbrev section.
2153 Asm->OutStreamer.SwitchSection(Section);
2155 // For each abbrevation.
2156 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
2157 // Get abbreviation data
2158 const DIEAbbrev *Abbrev = Abbreviations[i];
2160 // Emit the abbrevations code (base 1 index.)
2161 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2163 // Emit the abbreviations data.
2167 // Mark end of abbreviations.
2168 Asm->EmitULEB128(0, "EOM(3)");
2172 // Emit the last address of the section and the end of the line matrix.
2173 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2174 // Define last address of section.
2175 Asm->OutStreamer.AddComment("Extended Op");
2178 Asm->OutStreamer.AddComment("Op size");
2179 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2180 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2181 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2183 Asm->OutStreamer.AddComment("Section end label");
2185 Asm->OutStreamer.EmitSymbolValue(
2186 Asm->GetTempSymbol("section_end", SectionEnd),
2187 Asm->getDataLayout().getPointerSize());
2189 // Mark end of matrix.
2190 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2196 // Emit visible names into a hashed accelerator table section.
2197 void DwarfDebug::emitAccelNames() {
2199 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2200 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2201 E = getUnits().end();
2203 DwarfUnit *TheU = *I;
2204 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelNames();
2205 for (StringMap<std::vector<const DIE *> >::const_iterator
2209 StringRef Name = GI->getKey();
2210 const std::vector<const DIE *> &Entities = GI->second;
2211 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2212 DE = Entities.end();
2214 AT.AddName(Name, *DI);
2218 AT.FinalizeTable(Asm, "Names");
2219 Asm->OutStreamer.SwitchSection(
2220 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2221 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2222 Asm->OutStreamer.EmitLabel(SectionBegin);
2224 // Emit the full data.
2225 AT.Emit(Asm, SectionBegin, &InfoHolder);
2228 // Emit objective C classes and categories into a hashed accelerator table
2230 void DwarfDebug::emitAccelObjC() {
2232 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2233 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2234 E = getUnits().end();
2236 DwarfUnit *TheU = *I;
2237 const StringMap<std::vector<const DIE *> > &Names = TheU->getAccelObjC();
2238 for (StringMap<std::vector<const DIE *> >::const_iterator
2242 StringRef Name = GI->getKey();
2243 const std::vector<const DIE *> &Entities = GI->second;
2244 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2245 DE = Entities.end();
2247 AT.AddName(Name, *DI);
2251 AT.FinalizeTable(Asm, "ObjC");
2252 Asm->OutStreamer.SwitchSection(
2253 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2254 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2255 Asm->OutStreamer.EmitLabel(SectionBegin);
2257 // Emit the full data.
2258 AT.Emit(Asm, SectionBegin, &InfoHolder);
2261 // Emit namespace dies into a hashed accelerator table.
2262 void DwarfDebug::emitAccelNamespaces() {
2264 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2265 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2266 E = getUnits().end();
2268 DwarfUnit *TheU = *I;
2269 const StringMap<std::vector<const DIE *> > &Names =
2270 TheU->getAccelNamespace();
2271 for (StringMap<std::vector<const DIE *> >::const_iterator
2275 StringRef Name = GI->getKey();
2276 const std::vector<const DIE *> &Entities = GI->second;
2277 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2278 DE = Entities.end();
2280 AT.AddName(Name, *DI);
2284 AT.FinalizeTable(Asm, "namespac");
2285 Asm->OutStreamer.SwitchSection(
2286 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2287 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2288 Asm->OutStreamer.EmitLabel(SectionBegin);
2290 // Emit the full data.
2291 AT.Emit(Asm, SectionBegin, &InfoHolder);
2294 // Emit type dies into a hashed accelerator table.
2295 void DwarfDebug::emitAccelTypes() {
2296 std::vector<DwarfAccelTable::Atom> Atoms;
2298 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2300 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2302 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2303 DwarfAccelTable AT(Atoms);
2304 for (SmallVectorImpl<DwarfUnit *>::const_iterator I = getUnits().begin(),
2305 E = getUnits().end();
2307 DwarfUnit *TheU = *I;
2308 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2309 TheU->getAccelTypes();
2311 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2315 StringRef Name = GI->getKey();
2316 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2318 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2319 DI = Entities.begin(),
2320 DE = Entities.end();
2322 AT.AddName(Name, DI->first, DI->second);
2326 AT.FinalizeTable(Asm, "types");
2327 Asm->OutStreamer.SwitchSection(
2328 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2329 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2330 Asm->OutStreamer.EmitLabel(SectionBegin);
2332 // Emit the full data.
2333 AT.Emit(Asm, SectionBegin, &InfoHolder);
2336 // Public name handling.
2337 // The format for the various pubnames:
2339 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2340 // for the DIE that is named.
2342 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2343 // into the CU and the index value is computed according to the type of value
2344 // for the DIE that is named.
2346 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2347 // it's the offset within the debug_info/debug_types dwo section, however, the
2348 // reference in the pubname header doesn't change.
2350 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2351 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2353 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2355 // We could have a specification DIE that has our most of our knowledge,
2356 // look for that now.
2357 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2359 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2360 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2361 Linkage = dwarf::GIEL_EXTERNAL;
2362 } else if (Die->findAttribute(dwarf::DW_AT_external))
2363 Linkage = dwarf::GIEL_EXTERNAL;
2365 switch (Die->getTag()) {
2366 case dwarf::DW_TAG_class_type:
2367 case dwarf::DW_TAG_structure_type:
2368 case dwarf::DW_TAG_union_type:
2369 case dwarf::DW_TAG_enumeration_type:
2370 return dwarf::PubIndexEntryDescriptor(
2371 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2372 ? dwarf::GIEL_STATIC
2373 : dwarf::GIEL_EXTERNAL);
2374 case dwarf::DW_TAG_typedef:
2375 case dwarf::DW_TAG_base_type:
2376 case dwarf::DW_TAG_subrange_type:
2377 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2378 case dwarf::DW_TAG_namespace:
2379 return dwarf::GIEK_TYPE;
2380 case dwarf::DW_TAG_subprogram:
2381 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2382 case dwarf::DW_TAG_constant:
2383 case dwarf::DW_TAG_variable:
2384 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2385 case dwarf::DW_TAG_enumerator:
2386 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2387 dwarf::GIEL_STATIC);
2389 return dwarf::GIEK_NONE;
2393 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2395 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2396 const MCSection *PSec =
2397 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2398 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2400 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2401 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2402 for (unsigned i = 0; i != Units.size(); ++i) {
2403 DwarfUnit *TheU = Units[i];
2404 unsigned ID = TheU->getUniqueID();
2406 // Start the dwarf pubnames section.
2407 Asm->OutStreamer.SwitchSection(PSec);
2409 // Emit a label so we can reference the beginning of this pubname section.
2411 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames", ID));
2414 Asm->OutStreamer.AddComment("Length of Public Names Info");
2415 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubnames_begin", ID);
2416 MCSymbol *EndLabel = Asm->GetTempSymbol("pubnames_end", ID);
2417 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2419 Asm->OutStreamer.EmitLabel(BeginLabel);
2421 Asm->OutStreamer.AddComment("DWARF Version");
2422 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2424 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2425 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2427 Asm->OutStreamer.AddComment("Compilation Unit Length");
2428 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2430 // Emit the pubnames for this compilation unit.
2431 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalNames();
2432 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2435 const char *Name = GI->getKeyData();
2436 const DIE *Entity = GI->second;
2438 Asm->OutStreamer.AddComment("DIE offset");
2439 Asm->EmitInt32(Entity->getOffset());
2442 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2443 Asm->OutStreamer.AddComment(
2444 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2445 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2446 Asm->EmitInt8(Desc.toBits());
2449 Asm->OutStreamer.AddComment("External Name");
2450 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2453 Asm->OutStreamer.AddComment("End Mark");
2455 Asm->OutStreamer.EmitLabel(EndLabel);
2459 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2460 const MCSection *PSec =
2461 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2462 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2464 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2465 const SmallVectorImpl<DwarfUnit *> &Units = Holder.getUnits();
2466 for (unsigned i = 0; i != Units.size(); ++i) {
2467 DwarfUnit *TheU = Units[i];
2468 unsigned ID = TheU->getUniqueID();
2470 // Start the dwarf pubtypes section.
2471 Asm->OutStreamer.SwitchSection(PSec);
2473 // Emit a label so we can reference the beginning of this pubtype section.
2475 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes", ID));
2478 Asm->OutStreamer.AddComment("Length of Public Types Info");
2479 MCSymbol *BeginLabel = Asm->GetTempSymbol("pubtypes_begin", ID);
2480 MCSymbol *EndLabel = Asm->GetTempSymbol("pubtypes_end", ID);
2481 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2483 Asm->OutStreamer.EmitLabel(BeginLabel);
2485 Asm->OutStreamer.AddComment("DWARF Version");
2486 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2488 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2489 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2491 Asm->OutStreamer.AddComment("Compilation Unit Length");
2492 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2494 // Emit the pubtypes.
2495 const StringMap<const DIE *> &Globals = getUnits()[ID]->getGlobalTypes();
2496 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2499 const char *Name = GI->getKeyData();
2500 const DIE *Entity = GI->second;
2502 Asm->OutStreamer.AddComment("DIE offset");
2503 Asm->EmitInt32(Entity->getOffset());
2506 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2507 Asm->OutStreamer.AddComment(
2508 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2509 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2510 Asm->EmitInt8(Desc.toBits());
2513 Asm->OutStreamer.AddComment("External Name");
2515 // Emit the name with a terminating null byte.
2516 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2519 Asm->OutStreamer.AddComment("End Mark");
2521 Asm->OutStreamer.EmitLabel(EndLabel);
2525 // Emit strings into a string section.
2526 void DwarfFile::emitStrings(const MCSection *StrSection,
2527 const MCSection *OffsetSection = NULL,
2528 const MCSymbol *StrSecSym = NULL) {
2530 if (StringPool.empty())
2533 // Start the dwarf str section.
2534 Asm->OutStreamer.SwitchSection(StrSection);
2536 // Get all of the string pool entries and put them in an array by their ID so
2537 // we can sort them.
2539 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2542 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2543 I = StringPool.begin(),
2544 E = StringPool.end();
2546 Entries.push_back(std::make_pair(I->second.second, &*I));
2548 array_pod_sort(Entries.begin(), Entries.end());
2550 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2551 // Emit a label for reference from debug information entries.
2552 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2554 // Emit the string itself with a terminating null byte.
2555 Asm->OutStreamer.EmitBytes(
2556 StringRef(Entries[i].second->getKeyData(),
2557 Entries[i].second->getKeyLength() + 1));
2560 // If we've got an offset section go ahead and emit that now as well.
2561 if (OffsetSection) {
2562 Asm->OutStreamer.SwitchSection(OffsetSection);
2563 unsigned offset = 0;
2564 unsigned size = 4; // FIXME: DWARF64 is 8.
2565 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2566 Asm->OutStreamer.EmitIntValue(offset, size);
2567 offset += Entries[i].second->getKeyLength() + 1;
2572 // Emit addresses into the section given.
2573 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2575 if (AddressPool.empty())
2578 // Start the dwarf addr section.
2579 Asm->OutStreamer.SwitchSection(AddrSection);
2581 // Order the address pool entries by ID
2582 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2584 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2585 E = AddressPool.end();
2587 Entries[I->second] = I->first;
2589 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2590 // Emit an expression for reference from debug information entries.
2591 if (const MCExpr *Expr = Entries[i])
2592 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2594 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2598 // Emit visible names into a debug str section.
2599 void DwarfDebug::emitDebugStr() {
2600 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2601 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2604 // Emit locations into the debug loc section.
2605 void DwarfDebug::emitDebugLoc() {
2606 if (DotDebugLocEntries.empty())
2609 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2610 I = DotDebugLocEntries.begin(),
2611 E = DotDebugLocEntries.end();
2613 DotDebugLocEntry &Entry = *I;
2614 if (I + 1 != DotDebugLocEntries.end())
2618 // Start the dwarf loc section.
2619 Asm->OutStreamer.SwitchSection(
2620 Asm->getObjFileLowering().getDwarfLocSection());
2621 unsigned char Size = Asm->getDataLayout().getPointerSize();
2622 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2624 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2625 I = DotDebugLocEntries.begin(),
2626 E = DotDebugLocEntries.end();
2627 I != E; ++I, ++index) {
2628 DotDebugLocEntry &Entry = *I;
2629 if (Entry.isMerged())
2631 if (Entry.isEmpty()) {
2632 Asm->OutStreamer.EmitIntValue(0, Size);
2633 Asm->OutStreamer.EmitIntValue(0, Size);
2634 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2636 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2637 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2638 DIVariable DV(Entry.getVariable());
2639 Asm->OutStreamer.AddComment("Loc expr size");
2640 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2641 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2642 Asm->EmitLabelDifference(end, begin, 2);
2643 Asm->OutStreamer.EmitLabel(begin);
2644 if (Entry.isInt()) {
2645 DIBasicType BTy(DV.getType());
2646 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2647 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2648 Asm->OutStreamer.AddComment("DW_OP_consts");
2649 Asm->EmitInt8(dwarf::DW_OP_consts);
2650 Asm->EmitSLEB128(Entry.getInt());
2652 Asm->OutStreamer.AddComment("DW_OP_constu");
2653 Asm->EmitInt8(dwarf::DW_OP_constu);
2654 Asm->EmitULEB128(Entry.getInt());
2656 } else if (Entry.isLocation()) {
2657 MachineLocation Loc = Entry.getLoc();
2658 if (!DV.hasComplexAddress())
2660 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2662 // Complex address entry.
2663 unsigned N = DV.getNumAddrElements();
2665 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2666 if (Loc.getOffset()) {
2668 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2669 Asm->OutStreamer.AddComment("DW_OP_deref");
2670 Asm->EmitInt8(dwarf::DW_OP_deref);
2671 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2672 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2673 Asm->EmitSLEB128(DV.getAddrElement(1));
2675 // If first address element is OpPlus then emit
2676 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2677 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2678 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2682 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2685 // Emit remaining complex address elements.
2686 for (; i < N; ++i) {
2687 uint64_t Element = DV.getAddrElement(i);
2688 if (Element == DIBuilder::OpPlus) {
2689 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2690 Asm->EmitULEB128(DV.getAddrElement(++i));
2691 } else if (Element == DIBuilder::OpDeref) {
2693 Asm->EmitInt8(dwarf::DW_OP_deref);
2695 llvm_unreachable("unknown Opcode found in complex address");
2699 // else ... ignore constant fp. There is not any good way to
2700 // to represent them here in dwarf.
2701 Asm->OutStreamer.EmitLabel(end);
2706 struct SymbolCUSorter {
2707 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2708 const MCStreamer &Streamer;
2710 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2711 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2712 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2714 // Symbols with no order assigned should be placed at the end.
2715 // (e.g. section end labels)
2717 IA = (unsigned)(-1);
2719 IB = (unsigned)(-1);
2724 static bool CUSort(const DwarfUnit *A, const DwarfUnit *B) {
2725 return (A->getUniqueID() < B->getUniqueID());
2729 const MCSymbol *Start, *End;
2732 // Emit a debug aranges section, containing a CU lookup for any
2733 // address we can tie back to a CU.
2734 void DwarfDebug::emitDebugARanges() {
2735 // Start the dwarf aranges section.
2736 Asm->OutStreamer.SwitchSection(
2737 Asm->getObjFileLowering().getDwarfARangesSection());
2739 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2743 // Build a list of sections used.
2744 std::vector<const MCSection *> Sections;
2745 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2747 const MCSection *Section = it->first;
2748 Sections.push_back(Section);
2751 // Sort the sections into order.
2752 // This is only done to ensure consistent output order across different runs.
2753 std::sort(Sections.begin(), Sections.end(), SectionSort);
2755 // Build a set of address spans, sorted by CU.
2756 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2757 const MCSection *Section = Sections[SecIdx];
2758 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2759 if (List.size() < 2)
2762 // Sort the symbols by offset within the section.
2763 SymbolCUSorter sorter(Asm->OutStreamer);
2764 std::sort(List.begin(), List.end(), sorter);
2766 // If we have no section (e.g. common), just write out
2767 // individual spans for each symbol.
2768 if (Section == NULL) {
2769 for (size_t n = 0; n < List.size(); n++) {
2770 const SymbolCU &Cur = List[n];
2773 Span.Start = Cur.Sym;
2776 Spans[Cur.CU].push_back(Span);
2779 // Build spans between each label.
2780 const MCSymbol *StartSym = List[0].Sym;
2781 for (size_t n = 1; n < List.size(); n++) {
2782 const SymbolCU &Prev = List[n - 1];
2783 const SymbolCU &Cur = List[n];
2785 // Try and build the longest span we can within the same CU.
2786 if (Cur.CU != Prev.CU) {
2788 Span.Start = StartSym;
2790 Spans[Prev.CU].push_back(Span);
2797 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2799 // Build a list of CUs used.
2800 std::vector<DwarfCompileUnit *> CUs;
2801 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2802 DwarfCompileUnit *CU = it->first;
2806 // Sort the CU list (again, to ensure consistent output order).
2807 std::sort(CUs.begin(), CUs.end(), CUSort);
2809 // Emit an arange table for each CU we used.
2810 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2811 DwarfCompileUnit *CU = CUs[CUIdx];
2812 std::vector<ArangeSpan> &List = Spans[CU];
2814 // Emit size of content not including length itself.
2815 unsigned ContentSize =
2816 sizeof(int16_t) + // DWARF ARange version number
2817 sizeof(int32_t) + // Offset of CU in the .debug_info section
2818 sizeof(int8_t) + // Pointer Size (in bytes)
2819 sizeof(int8_t); // Segment Size (in bytes)
2821 unsigned TupleSize = PtrSize * 2;
2823 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2825 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2827 ContentSize += Padding;
2828 ContentSize += (List.size() + 1) * TupleSize;
2830 // For each compile unit, write the list of spans it covers.
2831 Asm->OutStreamer.AddComment("Length of ARange Set");
2832 Asm->EmitInt32(ContentSize);
2833 Asm->OutStreamer.AddComment("DWARF Arange version number");
2834 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2835 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2836 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2837 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2838 Asm->EmitInt8(PtrSize);
2839 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2842 Asm->OutStreamer.EmitFill(Padding, 0xff);
2844 for (unsigned n = 0; n < List.size(); n++) {
2845 const ArangeSpan &Span = List[n];
2846 Asm->EmitLabelReference(Span.Start, PtrSize);
2848 // Calculate the size as being from the span start to it's end.
2850 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2852 // For symbols without an end marker (e.g. common), we
2853 // write a single arange entry containing just that one symbol.
2854 uint64_t Size = SymSize[Span.Start];
2858 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2862 Asm->OutStreamer.AddComment("ARange terminator");
2863 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2864 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2868 // Emit visible names into a debug ranges section.
2869 void DwarfDebug::emitDebugRanges() {
2870 // Start the dwarf ranges section.
2871 Asm->OutStreamer.SwitchSection(
2872 Asm->getObjFileLowering().getDwarfRangesSection());
2874 // Size for our labels.
2875 unsigned char Size = Asm->getDataLayout().getPointerSize();
2877 // Grab the specific ranges for the compile units in the module.
2878 for (DenseMap<const MDNode *, DwarfCompileUnit *>::iterator I = CUMap.begin(),
2881 DwarfCompileUnit *TheCU = I->second;
2883 // Emit a symbol so we can find the beginning of our ranges.
2884 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2886 // Iterate over the misc ranges for the compile units in the module.
2887 const SmallVectorImpl<RangeSpanList> &RangeLists = TheCU->getRangeLists();
2888 for (SmallVectorImpl<RangeSpanList>::const_iterator I = RangeLists.begin(),
2889 E = RangeLists.end();
2891 const RangeSpanList &List = *I;
2893 // Emit our symbol so we can find the beginning of the range.
2894 Asm->OutStreamer.EmitLabel(List.getSym());
2896 for (SmallVectorImpl<RangeSpan>::const_iterator
2897 RI = List.getRanges().begin(),
2898 RE = List.getRanges().end();
2900 const RangeSpan &Range = *RI;
2901 const MCSymbol *Begin = Range.getStart();
2902 const MCSymbol *End = Range.getEnd();
2903 assert(Begin && "Range without a begin symbol?");
2904 assert(End && "Range without an end symbol?");
2905 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2906 Asm->OutStreamer.EmitSymbolValue(End, Size);
2909 // And terminate the list with two 0 values.
2910 Asm->OutStreamer.EmitIntValue(0, Size);
2911 Asm->OutStreamer.EmitIntValue(0, Size);
2914 // Now emit a range for the CU itself.
2915 if (useCURanges()) {
2916 Asm->OutStreamer.EmitLabel(
2917 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2918 const SmallVectorImpl<RangeSpan> &Ranges = TheCU->getRanges();
2919 for (uint32_t i = 0, e = Ranges.size(); i != e; ++i) {
2920 RangeSpan Range = Ranges[i];
2921 const MCSymbol *Begin = Range.getStart();
2922 const MCSymbol *End = Range.getEnd();
2923 assert(Begin && "Range without a begin symbol?");
2924 assert(End && "Range without an end symbol?");
2925 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2926 Asm->OutStreamer.EmitSymbolValue(End, Size);
2928 // And terminate the list with two 0 values.
2929 Asm->OutStreamer.EmitIntValue(0, Size);
2930 Asm->OutStreamer.EmitIntValue(0, Size);
2935 // DWARF5 Experimental Separate Dwarf emitters.
2937 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2939 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2940 U->getCUNode().getSplitDebugFilename());
2942 // Relocate to the beginning of the addr_base section, else 0 for the
2943 // beginning of the one for this compile unit.
2944 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2945 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2947 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2949 if (!CompilationDir.empty())
2950 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2952 addGnuPubAttributes(NewU, Die);
2954 SkeletonHolder.addUnit(NewU);
2957 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2958 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2959 // DW_AT_ranges_base, DW_AT_addr_base.
2960 // TODO: Implement DW_AT_ranges_base.
2961 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2963 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2964 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2965 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2966 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2967 DwarfInfoSectionSym);
2969 // DW_AT_stmt_list is a offset of line number information for this
2970 // compile unit in debug_line section.
2971 // FIXME: Should handle multiple compile units.
2972 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2973 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list, DwarfLineSectionSym);
2975 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2977 initSkeletonUnit(CU, Die, NewCU);
2982 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2984 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(const DwarfTypeUnit *TU) {
2986 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2987 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
2988 TU->getUniqueID(), Die, TU->getCUNode(), Asm, this, &SkeletonHolder);
2989 NewTU->setTypeSignature(TU->getTypeSignature());
2990 NewTU->setType(NULL);
2992 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2994 initSkeletonUnit(TU, Die, NewTU);
2998 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2999 // compile units that would normally be in debug_info.
3000 void DwarfDebug::emitDebugInfoDWO() {
3001 assert(useSplitDwarf() && "No split dwarf debug info?");
3002 InfoHolder.emitUnits(this,
3003 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3004 DwarfAbbrevDWOSectionSym);
3007 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3008 // abbreviations for the .debug_info.dwo section.
3009 void DwarfDebug::emitDebugAbbrevDWO() {
3010 assert(useSplitDwarf() && "No split dwarf?");
3011 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3014 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3015 // string section and is identical in format to traditional .debug_str
3017 void DwarfDebug::emitDebugStrDWO() {
3018 assert(useSplitDwarf() && "No split dwarf?");
3019 const MCSection *OffSec =
3020 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3021 const MCSymbol *StrSym = DwarfStrSectionSym;
3022 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3026 void DwarfDebug::addDwarfTypeUnitType(DICompileUnit CUNode,
3027 StringRef Identifier, DIE *RefDie,
3028 DICompositeType CTy) {
3030 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
3032 CUMap.begin()->second->addDIETypeSignature(RefDie, *TU);
3036 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3037 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
3038 InfoHolder.getUnits().size(), UnitDie, CUNode, Asm, this, &InfoHolder);
3040 InfoHolder.addUnit(NewTU);
3042 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3043 CUNode.getLanguage());
3046 Hash.update(Identifier);
3047 // ... take the least significant 8 bytes and return those. Our MD5
3048 // implementation always returns its results in little endian, swap bytes
3050 MD5::MD5Result Result;
3052 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
3053 NewTU->setTypeSignature(Signature);
3054 if (useSplitDwarf())
3055 NewTU->setSkeleton(constructSkeletonTU(NewTU));
3057 NewTU->setType(NewTU->createTypeDIE(CTy));
3061 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
3062 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
3064 CUMap.begin()->second->addDIETypeSignature(RefDie, *NewTU);