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 "DwarfCompileUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
66 static cl::opt<bool> GenerateCUHash("generate-cu-hash", cl::Hidden,
67 cl::desc("Add the CU hash as the dwo_id."),
71 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
72 cl::desc("Generate GNU-style pubnames and pubtypes"),
83 static cl::opt<DefaultOnOff>
84 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
85 cl::desc("Output prototype dwarf accelerator tables."),
86 cl::values(clEnumVal(Default, "Default for platform"),
87 clEnumVal(Enable, "Enabled"),
88 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 static cl::opt<DefaultOnOff>
92 SplitDwarf("split-dwarf", cl::Hidden,
93 cl::desc("Output prototype dwarf split debug info."),
94 cl::values(clEnumVal(Default, "Default for platform"),
95 clEnumVal(Enable, "Enabled"),
96 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 static cl::opt<DefaultOnOff>
100 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
101 cl::desc("Generate DWARF pubnames and pubtypes sections"),
102 cl::values(clEnumVal(Default, "Default for platform"),
103 clEnumVal(Enable, "Enabled"),
104 clEnumVal(Disable, "Disabled"), clEnumValEnd),
107 static cl::opt<unsigned>
108 DwarfVersionNumber("dwarf-version", cl::Hidden,
109 cl::desc("Generate DWARF for dwarf version."),
112 static const char *const DWARFGroupName = "DWARF Emission";
113 static const char *const DbgTimerName = "DWARF Debug Writer";
115 //===----------------------------------------------------------------------===//
117 // Configuration values for initial hash set sizes (log2).
119 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
123 /// resolve - Look in the DwarfDebug map for the MDNode that
124 /// corresponds to the reference.
125 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
126 return DD->resolve(Ref);
129 DIType DbgVariable::getType() const {
130 DIType Ty = Var.getType();
131 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
132 // addresses instead.
133 if (Var.isBlockByrefVariable()) {
134 /* Byref variables, in Blocks, are declared by the programmer as
135 "SomeType VarName;", but the compiler creates a
136 __Block_byref_x_VarName struct, and gives the variable VarName
137 either the struct, or a pointer to the struct, as its type. This
138 is necessary for various behind-the-scenes things the compiler
139 needs to do with by-reference variables in blocks.
141 However, as far as the original *programmer* is concerned, the
142 variable should still have type 'SomeType', as originally declared.
144 The following function dives into the __Block_byref_x_VarName
145 struct to find the original type of the variable. This will be
146 passed back to the code generating the type for the Debug
147 Information Entry for the variable 'VarName'. 'VarName' will then
148 have the original type 'SomeType' in its debug information.
150 The original type 'SomeType' will be the type of the field named
151 'VarName' inside the __Block_byref_x_VarName struct.
153 NOTE: In order for this to not completely fail on the debugger
154 side, the Debug Information Entry for the variable VarName needs to
155 have a DW_AT_location that tells the debugger how to unwind through
156 the pointers and __Block_byref_x_VarName struct to find the actual
157 value of the variable. The function addBlockByrefType does this. */
159 uint16_t tag = Ty.getTag();
161 if (tag == dwarf::DW_TAG_pointer_type)
162 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
164 DIArray Elements = DICompositeType(subType).getTypeArray();
165 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
166 DIDerivedType DT(Elements.getElement(i));
167 if (getName() == DT.getName())
168 return (resolve(DT.getTypeDerivedFrom()));
174 } // end llvm namespace
176 /// Return Dwarf Version by checking module flags.
177 static unsigned getDwarfVersionFromModule(const Module *M) {
178 Value *Val = M->getModuleFlag("Dwarf Version");
180 return dwarf::DWARF_VERSION;
181 return cast<ConstantInt>(Val)->getZExtValue();
184 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
185 : Asm(A), MMI(Asm->MMI), FirstCU(0),
186 AbbreviationsSet(InitAbbreviationsSetSize),
187 SourceIdMap(DIEValueAllocator), PrevLabel(NULL), GlobalCUIndexCount(0),
188 InfoHolder(A, &AbbreviationsSet, Abbreviations, "info_string",
190 SkeletonAbbrevSet(InitAbbreviationsSetSize),
191 SkeletonHolder(A, &SkeletonAbbrevSet, SkeletonAbbrevs, "skel_string",
194 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
195 DwarfStrSectionSym = TextSectionSym = 0;
196 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
197 DwarfAddrSectionSym = 0;
198 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
199 FunctionBeginSym = FunctionEndSym = 0;
201 // Turn on accelerator tables for Darwin by default, pubnames by
202 // default for non-Darwin, and handle split dwarf.
203 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
205 if (DwarfAccelTables == Default)
206 HasDwarfAccelTables = IsDarwin;
208 HasDwarfAccelTables = DwarfAccelTables == Enable;
210 if (SplitDwarf == Default)
211 HasSplitDwarf = false;
213 HasSplitDwarf = SplitDwarf == Enable;
215 if (DwarfPubSections == Default)
216 HasDwarfPubSections = !IsDarwin;
218 HasDwarfPubSections = DwarfPubSections == Enable;
220 DwarfVersion = DwarfVersionNumber
222 : getDwarfVersionFromModule(MMI->getModule());
225 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
230 // Switch to the specified MCSection and emit an assembler
231 // temporary label to it if SymbolStem is specified.
232 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
233 const char *SymbolStem = 0) {
234 Asm->OutStreamer.SwitchSection(Section);
238 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
239 Asm->OutStreamer.EmitLabel(TmpSym);
243 MCSymbol *DwarfUnits::getStringPoolSym() {
244 return Asm->GetTempSymbol(StringPref);
247 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
248 std::pair<MCSymbol *, unsigned> &Entry =
249 StringPool.GetOrCreateValue(Str).getValue();
253 Entry.second = NextStringPoolNumber++;
254 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
257 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
258 std::pair<MCSymbol *, unsigned> &Entry =
259 StringPool.GetOrCreateValue(Str).getValue();
263 Entry.second = NextStringPoolNumber++;
264 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
268 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
269 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
272 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
273 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
274 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
276 ++NextAddrPoolNumber;
277 return P.first->second;
280 // Define a unique number for the abbreviation.
282 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
283 // Check the set for priors.
284 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
286 // If it's newly added.
287 if (InSet == &Abbrev) {
288 // Add to abbreviation list.
289 Abbreviations.push_back(&Abbrev);
291 // Assign the vector position + 1 as its number.
292 Abbrev.setNumber(Abbreviations.size());
294 // Assign existing abbreviation number.
295 Abbrev.setNumber(InSet->getNumber());
299 static bool isObjCClass(StringRef Name) {
300 return Name.startswith("+") || Name.startswith("-");
303 static bool hasObjCCategory(StringRef Name) {
304 if (!isObjCClass(Name))
307 return Name.find(") ") != StringRef::npos;
310 static void getObjCClassCategory(StringRef In, StringRef &Class,
311 StringRef &Category) {
312 if (!hasObjCCategory(In)) {
313 Class = In.slice(In.find('[') + 1, In.find(' '));
318 Class = In.slice(In.find('[') + 1, In.find('('));
319 Category = In.slice(In.find('[') + 1, In.find(' '));
323 static StringRef getObjCMethodName(StringRef In) {
324 return In.slice(In.find(' ') + 1, In.find(']'));
327 // Helper for sorting sections into a stable output order.
328 static bool SectionSort(const MCSection *A, const MCSection *B) {
329 std::string LA = (A ? A->getLabelBeginName() : "");
330 std::string LB = (B ? B->getLabelBeginName() : "");
334 // Add the various names to the Dwarf accelerator table names.
335 // TODO: Determine whether or not we should add names for programs
336 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
337 // is only slightly different than the lookup of non-standard ObjC names.
338 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP, DIE *Die) {
339 if (!SP.isDefinition())
341 TheCU->addAccelName(SP.getName(), Die);
343 // If the linkage name is different than the name, go ahead and output
344 // that as well into the name table.
345 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
346 TheCU->addAccelName(SP.getLinkageName(), Die);
348 // If this is an Objective-C selector name add it to the ObjC accelerator
350 if (isObjCClass(SP.getName())) {
351 StringRef Class, Category;
352 getObjCClassCategory(SP.getName(), Class, Category);
353 TheCU->addAccelObjC(Class, Die);
355 TheCU->addAccelObjC(Category, Die);
356 // Also add the base method name to the name table.
357 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
361 /// isSubprogramContext - Return true if Context is either a subprogram
362 /// or another context nested inside a subprogram.
363 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
366 DIDescriptor D(Context);
367 if (D.isSubprogram())
370 return isSubprogramContext(resolve(DIType(Context).getContext()));
374 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
375 // and DW_AT_high_pc attributes. If there are global variables in this
376 // scope then create and insert DIEs for these variables.
377 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, DISubprogram SP) {
378 DIE *SPDie = SPCU->getDIE(SP);
380 assert(SPDie && "Unable to find subprogram DIE!");
382 // If we're updating an abstract DIE, then we will be adding the children and
383 // object pointer later on. But what we don't want to do is process the
384 // concrete DIE twice.
385 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
386 // Pick up abstract subprogram DIE.
387 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getCUDie());
388 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
390 DISubprogram SPDecl = SP.getFunctionDeclaration();
391 if (!SPDecl.isSubprogram()) {
392 // There is not any need to generate specification DIE for a function
393 // defined at compile unit level. If a function is defined inside another
394 // function then gdb prefers the definition at top level and but does not
395 // expect specification DIE in parent function. So avoid creating
396 // specification DIE for a function defined inside a function.
397 DIScope SPContext = resolve(SP.getContext());
398 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
399 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
400 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
403 DICompositeType SPTy = SP.getType();
404 DIArray Args = SPTy.getTypeArray();
405 uint16_t SPTag = SPTy.getTag();
406 if (SPTag == dwarf::DW_TAG_subroutine_type)
407 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
409 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
410 DIType ATy(Args.getElement(i));
411 SPCU->addType(Arg, ATy);
412 if (ATy.isArtificial())
413 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
414 if (ATy.isObjectPointer())
415 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
417 DIE *SPDeclDie = SPDie;
419 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getCUDie());
420 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
425 SPCU->addLabelAddress(
426 SPDie, dwarf::DW_AT_low_pc,
427 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
428 SPCU->addLabelAddress(
429 SPDie, dwarf::DW_AT_high_pc,
430 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
431 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
432 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
433 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
435 // Add name to the name table, we do this here because we're guaranteed
436 // to have concrete versions of our DW_TAG_subprogram nodes.
437 addSubprogramNames(SPCU, SP, SPDie);
442 /// Check whether we should create a DIE for the given Scope, return true
443 /// if we don't create a DIE (the corresponding DIE is null).
444 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
445 if (Scope->isAbstractScope())
448 // We don't create a DIE if there is no Range.
449 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
453 if (Ranges.size() > 1)
456 // We don't create a DIE if we have a single Range and the end label
458 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
459 MCSymbol *End = getLabelAfterInsn(RI->second);
463 // Construct new DW_TAG_lexical_block for this scope and attach
464 // DW_AT_low_pc/DW_AT_high_pc labels.
465 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
466 LexicalScope *Scope) {
467 if (isLexicalScopeDIENull(Scope))
470 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
471 if (Scope->isAbstractScope())
474 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
475 // If we have multiple ranges, emit them into the range section.
476 if (Ranges.size() > 1) {
477 // .debug_range section has not been laid out yet. Emit offset in
478 // .debug_range as a relocatable label. emitDIE will handle
479 // emitting it appropriately.
480 unsigned Offset = DebugRangeSymbols.size();
481 TheCU->addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges,
482 Asm->GetTempSymbol("debug_ranges", Offset));
483 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
486 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
487 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
490 // Terminate the range list.
491 DebugRangeSymbols.push_back(NULL);
492 DebugRangeSymbols.push_back(NULL);
496 // Construct the address range for this DIE.
497 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
498 MCSymbol *Start = getLabelBeforeInsn(RI->first);
499 MCSymbol *End = getLabelAfterInsn(RI->second);
500 assert(End && "End label should not be null!");
502 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
503 assert(End->isDefined() && "Invalid end label for an inlined scope!");
505 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
506 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
511 // This scope represents inlined body of a function. Construct DIE to
512 // represent this concrete inlined copy of the function.
513 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
514 LexicalScope *Scope) {
515 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
516 assert(Ranges.empty() == false &&
517 "LexicalScope does not have instruction markers!");
519 if (!Scope->getScopeNode())
521 DIScope DS(Scope->getScopeNode());
522 DISubprogram InlinedSP = getDISubprogram(DS);
523 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
525 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
529 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
530 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
532 if (Ranges.size() > 1) {
533 // .debug_range section has not been laid out yet. Emit offset in
534 // .debug_range as a relocatable label. emitDIE will handle
535 // emitting it appropriately.
536 unsigned Offset = DebugRangeSymbols.size();
537 TheCU->addSectionLabel(ScopeDIE, dwarf::DW_AT_ranges,
538 Asm->GetTempSymbol("debug_ranges", Offset));
539 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
542 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
543 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
545 DebugRangeSymbols.push_back(NULL);
546 DebugRangeSymbols.push_back(NULL);
548 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
549 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
550 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
552 if (StartLabel == 0 || EndLabel == 0)
553 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
555 assert(StartLabel->isDefined() &&
556 "Invalid starting label for an inlined scope!");
557 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
559 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
560 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
563 InlinedSubprogramDIEs.insert(OriginDIE);
565 // Add the call site information to the DIE.
566 DILocation DL(Scope->getInlinedAt());
567 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
568 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
569 TheCU->getUniqueID()));
570 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
572 // Add name to the name table, we do this here because we're guaranteed
573 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
574 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
579 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
580 SmallVectorImpl<DIE *> &Children) {
581 DIE *ObjectPointer = NULL;
583 // Collect arguments for current function.
584 if (LScopes.isCurrentFunctionScope(Scope))
585 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
586 if (DbgVariable *ArgDV = CurrentFnArguments[i])
588 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
589 Children.push_back(Arg);
590 if (ArgDV->isObjectPointer())
594 // Collect lexical scope children first.
595 const SmallVectorImpl<DbgVariable *> &Variables =
596 ScopeVariables.lookup(Scope);
597 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
598 if (DIE *Variable = TheCU->constructVariableDIE(*Variables[i],
599 Scope->isAbstractScope())) {
600 Children.push_back(Variable);
601 if (Variables[i]->isObjectPointer())
602 ObjectPointer = Variable;
604 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
605 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
606 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
607 Children.push_back(Nested);
608 return ObjectPointer;
611 // Construct a DIE for this scope.
612 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
613 if (!Scope || !Scope->getScopeNode())
616 DIScope DS(Scope->getScopeNode());
618 SmallVector<DIE *, 8> Children;
619 DIE *ObjectPointer = NULL;
620 bool ChildrenCreated = false;
622 // We try to create the scope DIE first, then the children DIEs. This will
623 // avoid creating un-used children then removing them later when we find out
624 // the scope DIE is null.
625 DIE *ScopeDIE = NULL;
626 if (Scope->getInlinedAt())
627 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
628 else if (DS.isSubprogram()) {
629 ProcessedSPNodes.insert(DS);
630 if (Scope->isAbstractScope()) {
631 ScopeDIE = TheCU->getDIE(DS);
632 // Note down abstract DIE.
634 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
636 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
638 // Early exit when we know the scope DIE is going to be null.
639 if (isLexicalScopeDIENull(Scope))
642 // We create children here when we know the scope DIE is not going to be
643 // null and the children will be added to the scope DIE.
644 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
645 ChildrenCreated = true;
647 // There is no need to emit empty lexical block DIE.
648 std::pair<ImportedEntityMap::const_iterator,
649 ImportedEntityMap::const_iterator> Range =
651 ScopesWithImportedEntities.begin(),
652 ScopesWithImportedEntities.end(),
653 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
655 if (Children.empty() && Range.first == Range.second)
657 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
658 assert(ScopeDIE && "Scope DIE should not be null.");
659 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
661 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
665 assert(Children.empty() &&
666 "We create children only when the scope DIE is not null.");
669 if (!ChildrenCreated)
670 // We create children when the scope DIE is not null.
671 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
674 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
677 ScopeDIE->addChild(*I);
679 if (DS.isSubprogram() && ObjectPointer != NULL)
680 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
682 if (DS.isSubprogram())
683 TheCU->addPubTypes(DISubprogram(DS));
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 // Create new CompileUnit for the given metadata node with tag
733 // DW_TAG_compile_unit.
734 CompileUnit *DwarfDebug::constructCompileUnit(DICompileUnit DIUnit) {
735 StringRef FN = DIUnit.getFilename();
736 CompilationDir = DIUnit.getDirectory();
738 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
739 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++, Die, DIUnit, Asm,
742 FileIDCUMap[NewCU->getUniqueID()] = 0;
743 // Call this to emit a .file directive if it wasn't emitted for the source
744 // file this CU comes from yet.
745 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
747 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
748 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
749 DIUnit.getLanguage());
750 NewCU->addString(Die, dwarf::DW_AT_name, FN);
752 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
753 // into an entity. We're using 0 (or a NULL label) for this. For
754 // split dwarf it's in the skeleton CU so omit it here.
755 if (!useSplitDwarf())
756 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
758 // Define start line table label for each Compile Unit.
759 MCSymbol *LineTableStartSym =
760 Asm->GetTempSymbol("line_table_start", NewCU->getUniqueID());
761 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
762 NewCU->getUniqueID());
764 // Use a single line table if we are using .loc and generating assembly.
766 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
767 (NewCU->getUniqueID() == 0);
769 if (!useSplitDwarf()) {
770 // DW_AT_stmt_list is a offset of line number information for this
771 // compile unit in debug_line section. For split dwarf this is
772 // left in the skeleton CU and so not included.
773 // The line table entries are not always emitted in assembly, so it
774 // is not okay to use line_table_start here.
775 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
776 NewCU->addSectionLabel(
777 Die, dwarf::DW_AT_stmt_list,
778 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
779 : LineTableStartSym);
780 else if (UseTheFirstCU)
781 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
783 NewCU->addSectionDelta(Die, dwarf::DW_AT_stmt_list,
784 LineTableStartSym, DwarfLineSectionSym);
786 // If we're using split dwarf the compilation dir is going to be in the
787 // skeleton CU and so we don't need to duplicate it here.
788 if (!CompilationDir.empty())
789 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
791 // Flags to let the linker know we have emitted new style pubnames. Only
792 // emit it here if we don't have a skeleton CU for split dwarf.
793 if (GenerateGnuPubSections) {
794 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
795 NewCU->addSectionLabel(
796 Die, dwarf::DW_AT_GNU_pubnames,
797 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
799 NewCU->addSectionDelta(
800 Die, dwarf::DW_AT_GNU_pubnames,
801 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
802 DwarfGnuPubNamesSectionSym);
804 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
805 NewCU->addSectionLabel(
806 Die, dwarf::DW_AT_GNU_pubtypes,
807 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
809 NewCU->addSectionDelta(
810 Die, dwarf::DW_AT_GNU_pubtypes,
811 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
812 DwarfGnuPubTypesSectionSym);
816 if (DIUnit.isOptimized())
817 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
819 StringRef Flags = DIUnit.getFlags();
821 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
823 if (unsigned RVer = DIUnit.getRunTimeVersion())
824 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
825 dwarf::DW_FORM_data1, RVer);
830 InfoHolder.addUnit(NewCU);
832 CUMap.insert(std::make_pair(DIUnit, NewCU));
833 CUDieMap.insert(std::make_pair(Die, NewCU));
837 // Construct subprogram DIE.
838 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
839 // FIXME: We should only call this routine once, however, during LTO if a
840 // program is defined in multiple CUs we could end up calling it out of
841 // beginModule as we walk the CUs.
843 CompileUnit *&CURef = SPMap[N];
849 if (!SP.isDefinition())
850 // This is a method declaration which will be handled while constructing
854 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
856 // Expose as a global name.
857 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
860 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
862 DIImportedEntity Module(N);
863 if (!Module.Verify())
865 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
866 constructImportedEntityDIE(TheCU, Module, D);
869 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
871 DIImportedEntity Module(N);
872 if (!Module.Verify())
874 return constructImportedEntityDIE(TheCU, Module, Context);
877 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
878 const DIImportedEntity &Module,
880 assert(Module.Verify() &&
881 "Use one of the MDNode * overloads to handle invalid metadata");
882 assert(Context && "Should always have a context for an imported_module");
883 DIE *IMDie = new DIE(Module.getTag());
884 TheCU->insertDIE(Module, IMDie);
886 DIDescriptor Entity = Module.getEntity();
887 if (Entity.isNameSpace())
888 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
889 else if (Entity.isSubprogram())
890 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
891 else if (Entity.isType())
892 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
894 EntityDie = TheCU->getDIE(Entity);
895 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
896 Module.getContext().getDirectory(),
897 TheCU->getUniqueID());
898 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
899 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
900 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
901 StringRef Name = Module.getName();
903 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
904 Context->addChild(IMDie);
907 // Emit all Dwarf sections that should come prior to the content. Create
908 // global DIEs and emit initial debug info sections. This is invoked by
909 // the target AsmPrinter.
910 void DwarfDebug::beginModule() {
911 if (DisableDebugInfoPrinting)
914 const Module *M = MMI->getModule();
916 // If module has named metadata anchors then use them, otherwise scan the
917 // module using debug info finder to collect debug info.
918 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
921 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
923 // Emit initial sections so we can reference labels later.
926 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
927 DICompileUnit CUNode(CU_Nodes->getOperand(i));
928 CompileUnit *CU = constructCompileUnit(CUNode);
929 DIArray ImportedEntities = CUNode.getImportedEntities();
930 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
931 ScopesWithImportedEntities.push_back(std::make_pair(
932 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
933 ImportedEntities.getElement(i)));
934 std::sort(ScopesWithImportedEntities.begin(),
935 ScopesWithImportedEntities.end(), less_first());
936 DIArray GVs = CUNode.getGlobalVariables();
937 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
938 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
939 DIArray SPs = CUNode.getSubprograms();
940 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
941 constructSubprogramDIE(CU, SPs.getElement(i));
942 DIArray EnumTypes = CUNode.getEnumTypes();
943 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
944 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
945 DIArray RetainedTypes = CUNode.getRetainedTypes();
946 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
947 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
948 // Emit imported_modules last so that the relevant context is already
950 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
951 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
954 // Tell MMI that we have debug info.
955 MMI->setDebugInfoAvailability(true);
957 // Prime section data.
958 SectionMap[Asm->getObjFileLowering().getTextSection()];
961 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
962 void DwarfDebug::computeInlinedDIEs() {
963 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
964 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
965 AE = InlinedSubprogramDIEs.end();
968 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
970 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
971 AE = AbstractSPDies.end();
973 DIE *ISP = AI->second;
974 if (InlinedSubprogramDIEs.count(ISP))
976 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
980 // Collect info for variables that were optimized out.
981 void DwarfDebug::collectDeadVariables() {
982 const Module *M = MMI->getModule();
984 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
985 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
986 DICompileUnit TheCU(CU_Nodes->getOperand(i));
987 DIArray Subprograms = TheCU.getSubprograms();
988 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
989 DISubprogram SP(Subprograms.getElement(i));
990 if (ProcessedSPNodes.count(SP) != 0)
992 if (!SP.isSubprogram())
994 if (!SP.isDefinition())
996 DIArray Variables = SP.getVariables();
997 if (Variables.getNumElements() == 0)
1000 // Construct subprogram DIE and add variables DIEs.
1001 CompileUnit *SPCU = CUMap.lookup(TheCU);
1002 assert(SPCU && "Unable to find Compile Unit!");
1003 // FIXME: See the comment in constructSubprogramDIE about duplicate
1005 constructSubprogramDIE(SPCU, SP);
1006 DIE *SPDIE = SPCU->getDIE(SP);
1007 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
1008 DIVariable DV(Variables.getElement(vi));
1009 if (!DV.isVariable())
1011 DbgVariable NewVar(DV, NULL, this);
1012 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
1013 SPDIE->addChild(VariableDIE);
1020 // Type Signature [7.27] and ODR Hash code.
1022 /// \brief Grabs the string in whichever attribute is passed in and returns
1023 /// a reference to it. Returns "" if the attribute doesn't exist.
1024 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1025 DIEValue *V = Die->findAttribute(Attr);
1027 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1028 return S->getString();
1030 return StringRef("");
1033 /// Return true if the current DIE is contained within an anonymous namespace.
1034 static bool isContainedInAnonNamespace(DIE *Die) {
1035 DIE *Parent = Die->getParent();
1038 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1039 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1041 Parent = Parent->getParent();
1047 /// Test if the current CU language is C++ and that we have
1048 /// a named type that is not contained in an anonymous namespace.
1049 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
1050 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1051 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1052 !isContainedInAnonNamespace(Die);
1055 void DwarfDebug::finalizeModuleInfo() {
1056 // Collect info for variables that were optimized out.
1057 collectDeadVariables();
1059 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1060 computeInlinedDIEs();
1062 // Handle anything that needs to be done on a per-cu basis.
1063 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1065 CUI != CUE; ++CUI) {
1066 CompileUnit *TheCU = CUI->second;
1067 // Emit DW_AT_containing_type attribute to connect types with their
1068 // vtable holding type.
1069 TheCU->constructContainingTypeDIEs();
1071 // If we're splitting the dwarf out now that we've got the entire
1072 // CU then construct a skeleton CU based upon it.
1073 if (useSplitDwarf()) {
1075 if (GenerateCUHash) {
1077 ID = CUHash.computeCUSignature(*TheCU->getCUDie());
1079 // This should be a unique identifier when we want to build .dwp files.
1080 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1081 dwarf::DW_FORM_data8, ID);
1082 // Now construct the skeleton CU associated.
1083 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1084 // This should be a unique identifier when we want to build .dwp files.
1085 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1086 dwarf::DW_FORM_data8, ID);
1090 // Compute DIE offsets and sizes.
1091 InfoHolder.computeSizeAndOffsets();
1092 if (useSplitDwarf())
1093 SkeletonHolder.computeSizeAndOffsets();
1096 void DwarfDebug::endSections() {
1097 // Filter labels by section.
1098 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1099 const SymbolCU &SCU = ArangeLabels[n];
1100 if (SCU.Sym->isInSection()) {
1101 // Make a note of this symbol and it's section.
1102 const MCSection *Section = &SCU.Sym->getSection();
1103 if (!Section->getKind().isMetadata())
1104 SectionMap[Section].push_back(SCU);
1106 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1107 // appear in the output. This sucks as we rely on sections to build
1108 // arange spans. We can do it without, but it's icky.
1109 SectionMap[NULL].push_back(SCU);
1113 // Build a list of sections used.
1114 std::vector<const MCSection *> Sections;
1115 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1117 const MCSection *Section = it->first;
1118 Sections.push_back(Section);
1121 // Sort the sections into order.
1122 // This is only done to ensure consistent output order across different runs.
1123 std::sort(Sections.begin(), Sections.end(), SectionSort);
1125 // Add terminating symbols for each section.
1126 for (unsigned ID = 0; ID < Sections.size(); ID++) {
1127 const MCSection *Section = Sections[ID];
1128 MCSymbol *Sym = NULL;
1131 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1132 // if we know the section name up-front. For user-created sections, the
1134 // label may not be valid to use as a label. (section names can use a
1136 // set of characters on some systems)
1137 Sym = Asm->GetTempSymbol("debug_end", ID);
1138 Asm->OutStreamer.SwitchSection(Section);
1139 Asm->OutStreamer.EmitLabel(Sym);
1142 // Insert a final terminator.
1143 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1147 // Emit all Dwarf sections that should come after the content.
1148 void DwarfDebug::endModule() {
1153 // End any existing sections.
1154 // TODO: Does this need to happen?
1157 // Finalize the debug info for the module.
1158 finalizeModuleInfo();
1162 // Emit all the DIEs into a debug info section.
1165 // Corresponding abbreviations into a abbrev section.
1166 emitAbbreviations();
1168 // Emit info into a debug loc section.
1171 // Emit info into a debug aranges section.
1174 // Emit info into a debug ranges section.
1177 // Emit info into a debug macinfo section.
1180 if (useSplitDwarf()) {
1183 emitDebugAbbrevDWO();
1184 // Emit DWO addresses.
1185 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1188 // Emit info into the dwarf accelerator table sections.
1189 if (useDwarfAccelTables()) {
1192 emitAccelNamespaces();
1196 // Emit the pubnames and pubtypes sections if requested.
1197 if (HasDwarfPubSections) {
1198 emitDebugPubNames(GenerateGnuPubSections);
1199 emitDebugPubTypes(GenerateGnuPubSections);
1204 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1209 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1210 E = SkeletonCUs.end();
1214 // Reset these for the next Module if we have one.
1218 // Find abstract variable, if any, associated with Var.
1219 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1220 DebugLoc ScopeLoc) {
1221 LLVMContext &Ctx = DV->getContext();
1222 // More then one inlined variable corresponds to one abstract variable.
1223 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1224 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1226 return AbsDbgVariable;
1228 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1232 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1233 addScopeVariable(Scope, AbsDbgVariable);
1234 AbstractVariables[Var] = AbsDbgVariable;
1235 return AbsDbgVariable;
1238 // If Var is a current function argument then add it to CurrentFnArguments list.
1239 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1240 DbgVariable *Var, LexicalScope *Scope) {
1241 if (!LScopes.isCurrentFunctionScope(Scope))
1243 DIVariable DV = Var->getVariable();
1244 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1246 unsigned ArgNo = DV.getArgNumber();
1250 size_t Size = CurrentFnArguments.size();
1252 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1253 // llvm::Function argument size is not good indicator of how many
1254 // arguments does the function have at source level.
1256 CurrentFnArguments.resize(ArgNo * 2);
1257 CurrentFnArguments[ArgNo - 1] = Var;
1261 // Collect variable information from side table maintained by MMI.
1262 void DwarfDebug::collectVariableInfoFromMMITable(
1263 const MachineFunction *MF, SmallPtrSet<const MDNode *, 16> &Processed) {
1264 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1265 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1268 const MDNode *Var = VI->first;
1271 Processed.insert(Var);
1273 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1275 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1277 // If variable scope is not found then skip this variable.
1281 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1282 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1283 RegVar->setFrameIndex(VP.first);
1284 if (!addCurrentFnArgument(MF, RegVar, Scope))
1285 addScopeVariable(Scope, RegVar);
1287 AbsDbgVariable->setFrameIndex(VP.first);
1291 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1293 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1294 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1295 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1296 MI->getOperand(0).getReg() &&
1297 (MI->getOperand(1).isImm() ||
1298 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1301 // Get .debug_loc entry for the instruction range starting at MI.
1302 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1303 const MCSymbol *FLabel,
1304 const MCSymbol *SLabel,
1305 const MachineInstr *MI) {
1306 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1308 assert(MI->getNumOperands() == 3);
1309 if (MI->getOperand(0).isReg()) {
1310 MachineLocation MLoc;
1311 // If the second operand is an immediate, this is a
1312 // register-indirect address.
1313 if (!MI->getOperand(1).isImm())
1314 MLoc.set(MI->getOperand(0).getReg());
1316 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1317 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1319 if (MI->getOperand(0).isImm())
1320 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1321 if (MI->getOperand(0).isFPImm())
1322 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1323 if (MI->getOperand(0).isCImm())
1324 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1326 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1329 // Find variables for each lexical scope.
1331 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1332 SmallPtrSet<const MDNode *, 16> &Processed) {
1334 // Grab the variable info that was squirreled away in the MMI side-table.
1335 collectVariableInfoFromMMITable(MF, Processed);
1337 for (SmallVectorImpl<const MDNode *>::const_iterator
1338 UVI = UserVariables.begin(),
1339 UVE = UserVariables.end();
1340 UVI != UVE; ++UVI) {
1341 const MDNode *Var = *UVI;
1342 if (Processed.count(Var))
1345 // History contains relevant DBG_VALUE instructions for Var and instructions
1347 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1348 if (History.empty())
1350 const MachineInstr *MInsn = History.front();
1353 LexicalScope *Scope = NULL;
1354 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1355 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1356 Scope = LScopes.getCurrentFunctionScope();
1357 else if (MDNode *IA = DV.getInlinedAt())
1358 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1360 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1361 // If variable scope is not found then skip this variable.
1365 Processed.insert(DV);
1366 assert(MInsn->isDebugValue() && "History must begin with debug value");
1367 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1368 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1369 if (!addCurrentFnArgument(MF, RegVar, Scope))
1370 addScopeVariable(Scope, RegVar);
1372 AbsVar->setMInsn(MInsn);
1374 // Simplify ranges that are fully coalesced.
1375 if (History.size() <= 1 ||
1376 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1377 RegVar->setMInsn(MInsn);
1381 // Handle multiple DBG_VALUE instructions describing one variable.
1382 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1384 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1385 HI = History.begin(),
1388 const MachineInstr *Begin = *HI;
1389 assert(Begin->isDebugValue() && "Invalid History entry");
1391 // Check if DBG_VALUE is truncating a range.
1392 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1393 !Begin->getOperand(0).getReg())
1396 // Compute the range for a register location.
1397 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1398 const MCSymbol *SLabel = 0;
1401 // If Begin is the last instruction in History then its value is valid
1402 // until the end of the function.
1403 SLabel = FunctionEndSym;
1405 const MachineInstr *End = HI[1];
1406 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1407 << "\t" << *Begin << "\t" << *End << "\n");
1408 if (End->isDebugValue())
1409 SLabel = getLabelBeforeInsn(End);
1411 // End is a normal instruction clobbering the range.
1412 SLabel = getLabelAfterInsn(End);
1413 assert(SLabel && "Forgot label after clobber instruction");
1418 // The value is valid until the next DBG_VALUE or clobber.
1419 DotDebugLocEntries.push_back(
1420 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1422 DotDebugLocEntries.push_back(DotDebugLocEntry());
1425 // Collect info for variables that were optimized out.
1426 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1427 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1428 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1429 DIVariable DV(Variables.getElement(i));
1430 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1432 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1433 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1437 // Return Label preceding the instruction.
1438 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1439 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1440 assert(Label && "Didn't insert label before instruction");
1444 // Return Label immediately following the instruction.
1445 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1446 return LabelsAfterInsn.lookup(MI);
1449 // Process beginning of an instruction.
1450 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1451 // Check if source location changes, but ignore DBG_VALUE locations.
1452 if (!MI->isDebugValue()) {
1453 DebugLoc DL = MI->getDebugLoc();
1454 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1457 if (DL == PrologEndLoc) {
1458 Flags |= DWARF2_FLAG_PROLOGUE_END;
1459 PrologEndLoc = DebugLoc();
1461 if (PrologEndLoc.isUnknown())
1462 Flags |= DWARF2_FLAG_IS_STMT;
1464 if (!DL.isUnknown()) {
1465 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1466 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1468 recordSourceLine(0, 0, 0, 0);
1472 // Insert labels where requested.
1473 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1474 LabelsBeforeInsn.find(MI);
1477 if (I == LabelsBeforeInsn.end())
1480 // Label already assigned.
1485 PrevLabel = MMI->getContext().CreateTempSymbol();
1486 Asm->OutStreamer.EmitLabel(PrevLabel);
1488 I->second = PrevLabel;
1491 // Process end of an instruction.
1492 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1493 // Don't create a new label after DBG_VALUE instructions.
1494 // They don't generate code.
1495 if (!MI->isDebugValue())
1498 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1499 LabelsAfterInsn.find(MI);
1502 if (I == LabelsAfterInsn.end())
1505 // Label already assigned.
1509 // We need a label after this instruction.
1511 PrevLabel = MMI->getContext().CreateTempSymbol();
1512 Asm->OutStreamer.EmitLabel(PrevLabel);
1514 I->second = PrevLabel;
1517 // Each LexicalScope has first instruction and last instruction to mark
1518 // beginning and end of a scope respectively. Create an inverse map that list
1519 // scopes starts (and ends) with an instruction. One instruction may start (or
1520 // end) multiple scopes. Ignore scopes that are not reachable.
1521 void DwarfDebug::identifyScopeMarkers() {
1522 SmallVector<LexicalScope *, 4> WorkList;
1523 WorkList.push_back(LScopes.getCurrentFunctionScope());
1524 while (!WorkList.empty()) {
1525 LexicalScope *S = WorkList.pop_back_val();
1527 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1528 if (!Children.empty())
1529 for (SmallVectorImpl<LexicalScope *>::const_iterator
1530 SI = Children.begin(),
1531 SE = Children.end();
1533 WorkList.push_back(*SI);
1535 if (S->isAbstractScope())
1538 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1541 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1544 assert(RI->first && "InsnRange does not have first instruction!");
1545 assert(RI->second && "InsnRange does not have second instruction!");
1546 requestLabelBeforeInsn(RI->first);
1547 requestLabelAfterInsn(RI->second);
1552 // Get MDNode for DebugLoc's scope.
1553 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1554 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1555 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1556 return DL.getScope(Ctx);
1559 // Walk up the scope chain of given debug loc and find line number info
1560 // for the function.
1561 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1562 const MDNode *Scope = getScopeNode(DL, Ctx);
1563 DISubprogram SP = getDISubprogram(Scope);
1564 if (SP.isSubprogram()) {
1565 // Check for number of operands since the compatibility is
1567 if (SP->getNumOperands() > 19)
1568 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1570 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1576 // Gather pre-function debug information. Assumes being called immediately
1577 // after the function entry point has been emitted.
1578 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1580 // If there's no debug info for the function we're not going to do anything.
1581 if (!MMI->hasDebugInfo())
1584 // Grab the lexical scopes for the function, if we don't have any of those
1585 // then we're not going to be able to do anything.
1586 LScopes.initialize(*MF);
1587 if (LScopes.empty())
1590 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1592 // Make sure that each lexical scope will have a begin/end label.
1593 identifyScopeMarkers();
1595 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1596 // belongs to so that we add to the correct per-cu line table in the
1598 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1599 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1600 assert(TheCU && "Unable to find compile unit!");
1601 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1602 // Use a single line table if we are using .loc and generating assembly.
1603 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1605 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1607 // Emit a label for the function so that we have a beginning address.
1608 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1609 // Assumes in correct section after the entry point.
1610 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1612 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1613 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1614 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1616 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1618 bool AtBlockEntry = true;
1619 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1621 const MachineInstr *MI = II;
1623 if (MI->isDebugValue()) {
1624 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1626 // Keep track of user variables.
1628 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1630 // Variable is in a register, we need to check for clobbers.
1631 if (isDbgValueInDefinedReg(MI))
1632 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1634 // Check the history of this variable.
1635 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1636 if (History.empty()) {
1637 UserVariables.push_back(Var);
1638 // The first mention of a function argument gets the FunctionBeginSym
1639 // label, so arguments are visible when breaking at function entry.
1641 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1642 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1643 LabelsBeforeInsn[MI] = FunctionBeginSym;
1645 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1646 const MachineInstr *Prev = History.back();
1647 if (Prev->isDebugValue()) {
1648 // Coalesce identical entries at the end of History.
1649 if (History.size() >= 2 &&
1650 Prev->isIdenticalTo(History[History.size() - 2])) {
1651 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1652 << "\t" << *Prev << "\t"
1653 << *History[History.size() - 2] << "\n");
1657 // Terminate old register assignments that don't reach MI;
1658 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1659 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1660 isDbgValueInDefinedReg(Prev)) {
1661 // Previous register assignment needs to terminate at the end of
1663 MachineBasicBlock::const_iterator LastMI =
1664 PrevMBB->getLastNonDebugInstr();
1665 if (LastMI == PrevMBB->end()) {
1666 // Drop DBG_VALUE for empty range.
1667 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1668 << "\t" << *Prev << "\n");
1670 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1671 // Terminate after LastMI.
1672 History.push_back(LastMI);
1676 History.push_back(MI);
1678 // Not a DBG_VALUE instruction.
1680 AtBlockEntry = false;
1682 // First known non-DBG_VALUE and non-frame setup location marks
1683 // the beginning of the function body.
1684 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1685 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1686 PrologEndLoc = MI->getDebugLoc();
1688 // Check if the instruction clobbers any registers with debug vars.
1689 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1690 MOE = MI->operands_end();
1691 MOI != MOE; ++MOI) {
1692 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1694 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1697 const MDNode *Var = LiveUserVar[Reg];
1700 // Reg is now clobbered.
1701 LiveUserVar[Reg] = 0;
1703 // Was MD last defined by a DBG_VALUE referring to Reg?
1704 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1705 if (HistI == DbgValues.end())
1707 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1708 if (History.empty())
1710 const MachineInstr *Prev = History.back();
1711 // Sanity-check: Register assignments are terminated at the end of
1713 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1715 // Is the variable still in Reg?
1716 if (!isDbgValueInDefinedReg(Prev) ||
1717 Prev->getOperand(0).getReg() != Reg)
1719 // Var is clobbered. Make sure the next instruction gets a label.
1720 History.push_back(MI);
1727 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1729 SmallVectorImpl<const MachineInstr *> &History = I->second;
1730 if (History.empty())
1733 // Make sure the final register assignments are terminated.
1734 const MachineInstr *Prev = History.back();
1735 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1736 const MachineBasicBlock *PrevMBB = Prev->getParent();
1737 MachineBasicBlock::const_iterator LastMI =
1738 PrevMBB->getLastNonDebugInstr();
1739 if (LastMI == PrevMBB->end())
1740 // Drop DBG_VALUE for empty range.
1742 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1743 // Terminate after LastMI.
1744 History.push_back(LastMI);
1747 // Request labels for the full history.
1748 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1749 const MachineInstr *MI = History[i];
1750 if (MI->isDebugValue())
1751 requestLabelBeforeInsn(MI);
1753 requestLabelAfterInsn(MI);
1757 PrevInstLoc = DebugLoc();
1758 PrevLabel = FunctionBeginSym;
1760 // Record beginning of function.
1761 if (!PrologEndLoc.isUnknown()) {
1762 DebugLoc FnStartDL =
1763 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1765 FnStartDL.getLine(), FnStartDL.getCol(),
1766 FnStartDL.getScope(MF->getFunction()->getContext()),
1767 // We'd like to list the prologue as "not statements" but GDB behaves
1768 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1769 DWARF2_FLAG_IS_STMT);
1773 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1774 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1775 DIVariable DV = Var->getVariable();
1776 // Variables with positive arg numbers are parameters.
1777 if (unsigned ArgNum = DV.getArgNumber()) {
1778 // Keep all parameters in order at the start of the variable list to ensure
1779 // function types are correct (no out-of-order parameters)
1781 // This could be improved by only doing it for optimized builds (unoptimized
1782 // builds have the right order to begin with), searching from the back (this
1783 // would catch the unoptimized case quickly), or doing a binary search
1784 // rather than linear search.
1785 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1786 while (I != Vars.end()) {
1787 unsigned CurNum = (*I)->getVariable().getArgNumber();
1788 // A local (non-parameter) variable has been found, insert immediately
1792 // A later indexed parameter has been found, insert immediately before it.
1793 if (CurNum > ArgNum)
1797 Vars.insert(I, Var);
1801 Vars.push_back(Var);
1804 // Gather and emit post-function debug information.
1805 void DwarfDebug::endFunction(const MachineFunction *MF) {
1806 if (!MMI->hasDebugInfo() || LScopes.empty())
1809 // Define end label for subprogram.
1810 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1811 // Assumes in correct section after the entry point.
1812 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1813 // Set DwarfCompileUnitID in MCContext to default value.
1814 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1816 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1817 collectVariableInfo(MF, ProcessedVars);
1819 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1820 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1821 assert(TheCU && "Unable to find compile unit!");
1823 // Construct abstract scopes.
1824 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1825 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1826 LexicalScope *AScope = AList[i];
1827 DISubprogram SP(AScope->getScopeNode());
1828 if (SP.isSubprogram()) {
1829 // Collect info for variables that were optimized out.
1830 DIArray Variables = SP.getVariables();
1831 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1832 DIVariable DV(Variables.getElement(i));
1833 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1835 // Check that DbgVariable for DV wasn't created earlier, when
1836 // findAbstractVariable() was called for inlined instance of DV.
1837 LLVMContext &Ctx = DV->getContext();
1838 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1839 if (AbstractVariables.lookup(CleanDV))
1841 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1842 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1845 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1846 constructScopeDIE(TheCU, AScope);
1849 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1851 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1852 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1855 for (ScopeVariablesMap::iterator I = ScopeVariables.begin(),
1856 E = ScopeVariables.end();
1858 DeleteContainerPointers(I->second);
1859 ScopeVariables.clear();
1860 DeleteContainerPointers(CurrentFnArguments);
1861 UserVariables.clear();
1863 AbstractVariables.clear();
1864 LabelsBeforeInsn.clear();
1865 LabelsAfterInsn.clear();
1869 // Register a source line with debug info. Returns the unique label that was
1870 // emitted and which provides correspondence to the source line list.
1871 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1877 DIDescriptor Scope(S);
1879 if (Scope.isCompileUnit()) {
1880 DICompileUnit CU(S);
1881 Fn = CU.getFilename();
1882 Dir = CU.getDirectory();
1883 } else if (Scope.isFile()) {
1885 Fn = F.getFilename();
1886 Dir = F.getDirectory();
1887 } else if (Scope.isSubprogram()) {
1889 Fn = SP.getFilename();
1890 Dir = SP.getDirectory();
1891 } else if (Scope.isLexicalBlockFile()) {
1892 DILexicalBlockFile DBF(S);
1893 Fn = DBF.getFilename();
1894 Dir = DBF.getDirectory();
1895 } else if (Scope.isLexicalBlock()) {
1896 DILexicalBlock DB(S);
1897 Fn = DB.getFilename();
1898 Dir = DB.getDirectory();
1900 llvm_unreachable("Unexpected scope info");
1902 Src = getOrCreateSourceID(
1903 Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1905 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1908 //===----------------------------------------------------------------------===//
1910 //===----------------------------------------------------------------------===//
1912 // Compute the size and offset of a DIE. The offset is relative to start of the
1913 // CU. It returns the offset after laying out the DIE.
1914 unsigned DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1915 // Get the children.
1916 const std::vector<DIE *> &Children = Die->getChildren();
1918 // Record the abbreviation.
1919 assignAbbrevNumber(Die->getAbbrev());
1921 // Get the abbreviation for this DIE.
1922 unsigned AbbrevNumber = Die->getAbbrevNumber();
1923 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1926 Die->setOffset(Offset);
1928 // Start the size with the size of abbreviation code.
1929 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1931 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1932 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1934 // Size the DIE attribute values.
1935 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1936 // Size attribute value.
1937 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1939 // Size the DIE children if any.
1940 if (!Children.empty()) {
1941 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1942 "Children flag not set");
1944 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1945 Offset = computeSizeAndOffset(Children[j], Offset);
1947 // End of children marker.
1948 Offset += sizeof(int8_t);
1951 Die->setSize(Offset - Die->getOffset());
1955 // Compute the size and offset for each DIE.
1956 void DwarfUnits::computeSizeAndOffsets() {
1957 // Offset from the first CU in the debug info section is 0 initially.
1958 unsigned SecOffset = 0;
1960 // Iterate over each compile unit and set the size and offsets for each
1961 // DIE within each compile unit. All offsets are CU relative.
1962 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
1964 (*I)->setDebugInfoOffset(SecOffset);
1966 // CU-relative offset is reset to 0 here.
1967 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1968 (*I)->getHeaderSize(); // Unit-specific headers
1970 // EndOffset here is CU-relative, after laying out
1971 // all of the CU DIE.
1972 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1973 SecOffset += EndOffset;
1977 // Emit initial Dwarf sections with a label at the start of each one.
1978 void DwarfDebug::emitSectionLabels() {
1979 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1981 // Dwarf sections base addresses.
1982 DwarfInfoSectionSym =
1983 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1984 DwarfAbbrevSectionSym =
1985 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1986 if (useSplitDwarf())
1987 DwarfAbbrevDWOSectionSym = emitSectionSym(
1988 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1989 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1991 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1992 emitSectionSym(Asm, MacroInfo);
1994 DwarfLineSectionSym =
1995 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1996 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1997 if (GenerateGnuPubSections) {
1998 DwarfGnuPubNamesSectionSym =
1999 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2000 DwarfGnuPubTypesSectionSym =
2001 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2002 } else if (HasDwarfPubSections) {
2003 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2004 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2007 DwarfStrSectionSym =
2008 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2009 if (useSplitDwarf()) {
2010 DwarfStrDWOSectionSym =
2011 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2012 DwarfAddrSectionSym =
2013 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2015 DwarfDebugRangeSectionSym =
2016 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
2018 DwarfDebugLocSectionSym =
2019 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
2021 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2022 emitSectionSym(Asm, TLOF.getDataSection());
2025 // Recursively emits a debug information entry.
2026 void DwarfDebug::emitDIE(DIE *Die, ArrayRef<DIEAbbrev *> Abbrevs) {
2027 // Get the abbreviation for this DIE.
2028 unsigned AbbrevNumber = Die->getAbbrevNumber();
2029 const DIEAbbrev *Abbrev = Abbrevs[AbbrevNumber - 1];
2031 // Emit the code (index) for the abbreviation.
2032 if (Asm->isVerbose())
2033 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2034 Twine::utohexstr(Die->getOffset()) + ":0x" +
2035 Twine::utohexstr(Die->getSize()) + " " +
2036 dwarf::TagString(Abbrev->getTag()));
2037 Asm->EmitULEB128(AbbrevNumber);
2039 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
2040 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2042 // Emit the DIE attribute values.
2043 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2044 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2045 dwarf::Form Form = AbbrevData[i].getForm();
2046 assert(Form && "Too many attributes for DIE (check abbreviation)");
2048 if (Asm->isVerbose())
2049 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2052 case dwarf::DW_AT_abstract_origin:
2053 case dwarf::DW_AT_type:
2054 case dwarf::DW_AT_friend:
2055 case dwarf::DW_AT_specification:
2056 case dwarf::DW_AT_import:
2057 case dwarf::DW_AT_containing_type: {
2058 DIEEntry *E = cast<DIEEntry>(Values[i]);
2059 DIE *Origin = E->getEntry();
2060 unsigned Addr = Origin->getOffset();
2061 if (Form == dwarf::DW_FORM_ref_addr) {
2062 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2063 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2064 // section. Origin->getOffset() returns the offset from start of the
2066 CompileUnit *CU = CUDieMap.lookup(Origin->getUnit());
2067 assert(CU && "CUDie should belong to a CU.");
2068 Addr += CU->getDebugInfoOffset();
2069 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2070 Asm->EmitLabelPlusOffset(DwarfInfoSectionSym, Addr,
2071 DIEEntry::getRefAddrSize(Asm));
2073 Asm->EmitLabelOffsetDifference(DwarfInfoSectionSym, Addr,
2074 DwarfInfoSectionSym,
2075 DIEEntry::getRefAddrSize(Asm));
2077 // Make sure Origin belong to the same CU.
2078 assert(Die->getUnit() == Origin->getUnit() &&
2079 "The referenced DIE should belong to the same CU in ref4");
2080 Asm->EmitInt32(Addr);
2084 case dwarf::DW_AT_ranges: {
2085 // DW_AT_range Value encodes offset in debug_range section.
2086 DIELabel *V = cast<DIELabel>(Values[i]);
2088 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2089 Asm->EmitSectionOffset(V->getValue(), DwarfDebugRangeSectionSym);
2091 Asm->EmitLabelDifference(V->getValue(), DwarfDebugRangeSectionSym, 4);
2094 case dwarf::DW_AT_location: {
2095 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2096 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2097 Asm->EmitSectionOffset(L->getValue(), DwarfDebugLocSectionSym);
2099 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2101 Values[i]->EmitValue(Asm, Form);
2105 case dwarf::DW_AT_accessibility: {
2106 if (Asm->isVerbose()) {
2107 DIEInteger *V = cast<DIEInteger>(Values[i]);
2108 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2110 Values[i]->EmitValue(Asm, Form);
2114 // Emit an attribute using the defined form.
2115 Values[i]->EmitValue(Asm, Form);
2120 // Emit the DIE children if any.
2121 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2122 const std::vector<DIE *> &Children = Die->getChildren();
2124 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2125 emitDIE(Children[j], Abbrevs);
2127 if (Asm->isVerbose())
2128 Asm->OutStreamer.AddComment("End Of Children Mark");
2133 // Emit the various dwarf units to the unit section USection with
2134 // the abbreviations going into ASection.
2135 void DwarfUnits::emitUnits(DwarfDebug *DD, const MCSection *USection,
2136 const MCSection *ASection,
2137 const MCSymbol *ASectionSym) {
2138 Asm->OutStreamer.SwitchSection(USection);
2139 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2141 CompileUnit *TheCU = *I;
2142 DIE *Die = TheCU->getCUDie();
2144 // Emit the compile units header.
2145 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2146 TheCU->getUniqueID()));
2148 // Emit size of content not including length itself
2149 Asm->OutStreamer.AddComment("Length of Unit");
2150 Asm->EmitInt32(TheCU->getHeaderSize() + Die->getSize());
2152 TheCU->emitHeader(ASection, ASectionSym);
2154 DD->emitDIE(Die, Abbreviations);
2155 Asm->OutStreamer.EmitLabel(
2156 Asm->GetTempSymbol(USection->getLabelEndName(), TheCU->getUniqueID()));
2160 // Emit the debug info section.
2161 void DwarfDebug::emitDebugInfo() {
2162 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2164 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2165 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2166 DwarfAbbrevSectionSym);
2169 // Emit the abbreviation section.
2170 void DwarfDebug::emitAbbreviations() {
2171 if (!useSplitDwarf())
2172 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2175 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2178 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2179 std::vector<DIEAbbrev *> *Abbrevs) {
2180 // Check to see if it is worth the effort.
2181 if (!Abbrevs->empty()) {
2182 // Start the debug abbrev section.
2183 Asm->OutStreamer.SwitchSection(Section);
2185 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2186 Asm->OutStreamer.EmitLabel(Begin);
2188 // For each abbrevation.
2189 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2190 // Get abbreviation data
2191 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2193 // Emit the abbrevations code (base 1 index.)
2194 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2196 // Emit the abbreviations data.
2200 // Mark end of abbreviations.
2201 Asm->EmitULEB128(0, "EOM(3)");
2203 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2204 Asm->OutStreamer.EmitLabel(End);
2208 // Emit the last address of the section and the end of the line matrix.
2209 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2210 // Define last address of section.
2211 Asm->OutStreamer.AddComment("Extended Op");
2214 Asm->OutStreamer.AddComment("Op size");
2215 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2216 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2217 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2219 Asm->OutStreamer.AddComment("Section end label");
2221 Asm->OutStreamer.EmitSymbolValue(
2222 Asm->GetTempSymbol("section_end", SectionEnd),
2223 Asm->getDataLayout().getPointerSize());
2225 // Mark end of matrix.
2226 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2232 // Emit visible names into a hashed accelerator table section.
2233 void DwarfDebug::emitAccelNames() {
2235 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2236 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2239 CompileUnit *TheCU = I->second;
2240 const StringMap<std::vector<const DIE *> > &Names = TheCU->getAccelNames();
2241 for (StringMap<std::vector<const DIE *> >::const_iterator
2245 StringRef Name = GI->getKey();
2246 const std::vector<const DIE *> &Entities = GI->second;
2247 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2248 DE = Entities.end();
2250 AT.AddName(Name, *DI);
2254 AT.FinalizeTable(Asm, "Names");
2255 Asm->OutStreamer.SwitchSection(
2256 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2257 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2258 Asm->OutStreamer.EmitLabel(SectionBegin);
2260 // Emit the full data.
2261 AT.Emit(Asm, SectionBegin, &InfoHolder);
2264 // Emit objective C classes and categories into a hashed accelerator table
2266 void DwarfDebug::emitAccelObjC() {
2268 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2269 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2272 CompileUnit *TheCU = I->second;
2273 const StringMap<std::vector<const DIE *> > &Names = TheCU->getAccelObjC();
2274 for (StringMap<std::vector<const DIE *> >::const_iterator
2278 StringRef Name = GI->getKey();
2279 const std::vector<const DIE *> &Entities = GI->second;
2280 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2281 DE = Entities.end();
2283 AT.AddName(Name, *DI);
2287 AT.FinalizeTable(Asm, "ObjC");
2288 Asm->OutStreamer.SwitchSection(
2289 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2290 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2291 Asm->OutStreamer.EmitLabel(SectionBegin);
2293 // Emit the full data.
2294 AT.Emit(Asm, SectionBegin, &InfoHolder);
2297 // Emit namespace dies into a hashed accelerator table.
2298 void DwarfDebug::emitAccelNamespaces() {
2300 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2301 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2304 CompileUnit *TheCU = I->second;
2305 const StringMap<std::vector<const DIE *> > &Names =
2306 TheCU->getAccelNamespace();
2307 for (StringMap<std::vector<const DIE *> >::const_iterator
2311 StringRef Name = GI->getKey();
2312 const std::vector<const DIE *> &Entities = GI->second;
2313 for (std::vector<const DIE *>::const_iterator DI = Entities.begin(),
2314 DE = Entities.end();
2316 AT.AddName(Name, *DI);
2320 AT.FinalizeTable(Asm, "namespac");
2321 Asm->OutStreamer.SwitchSection(
2322 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2323 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2324 Asm->OutStreamer.EmitLabel(SectionBegin);
2326 // Emit the full data.
2327 AT.Emit(Asm, SectionBegin, &InfoHolder);
2330 // Emit type dies into a hashed accelerator table.
2331 void DwarfDebug::emitAccelTypes() {
2332 std::vector<DwarfAccelTable::Atom> Atoms;
2334 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2336 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2338 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2339 DwarfAccelTable AT(Atoms);
2340 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2343 CompileUnit *TheCU = I->second;
2344 const StringMap<std::vector<std::pair<const DIE *, unsigned> > > &Names =
2345 TheCU->getAccelTypes();
2347 std::vector<std::pair<const DIE *, unsigned> > >::const_iterator
2351 StringRef Name = GI->getKey();
2352 const std::vector<std::pair<const DIE *, unsigned> > &Entities =
2354 for (std::vector<std::pair<const DIE *, unsigned> >::const_iterator
2355 DI = Entities.begin(),
2356 DE = Entities.end();
2358 AT.AddName(Name, DI->first, DI->second);
2362 AT.FinalizeTable(Asm, "types");
2363 Asm->OutStreamer.SwitchSection(
2364 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2365 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2366 Asm->OutStreamer.EmitLabel(SectionBegin);
2368 // Emit the full data.
2369 AT.Emit(Asm, SectionBegin, &InfoHolder);
2372 // Public name handling.
2373 // The format for the various pubnames:
2375 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2376 // for the DIE that is named.
2378 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2379 // into the CU and the index value is computed according to the type of value
2380 // for the DIE that is named.
2382 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2383 // it's the offset within the debug_info/debug_types dwo section, however, the
2384 // reference in the pubname header doesn't change.
2386 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2387 static dwarf::PubIndexEntryDescriptor computeIndexValue(CompileUnit *CU,
2389 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2391 // We could have a specification DIE that has our most of our knowledge,
2392 // look for that now.
2393 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2395 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2396 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2397 Linkage = dwarf::GIEL_EXTERNAL;
2398 } else if (Die->findAttribute(dwarf::DW_AT_external))
2399 Linkage = dwarf::GIEL_EXTERNAL;
2401 switch (Die->getTag()) {
2402 case dwarf::DW_TAG_class_type:
2403 case dwarf::DW_TAG_structure_type:
2404 case dwarf::DW_TAG_union_type:
2405 case dwarf::DW_TAG_enumeration_type:
2406 return dwarf::PubIndexEntryDescriptor(
2407 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2408 ? dwarf::GIEL_STATIC
2409 : dwarf::GIEL_EXTERNAL);
2410 case dwarf::DW_TAG_typedef:
2411 case dwarf::DW_TAG_base_type:
2412 case dwarf::DW_TAG_subrange_type:
2413 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2414 case dwarf::DW_TAG_namespace:
2415 return dwarf::GIEK_TYPE;
2416 case dwarf::DW_TAG_subprogram:
2417 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2418 case dwarf::DW_TAG_constant:
2419 case dwarf::DW_TAG_variable:
2420 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2421 case dwarf::DW_TAG_enumerator:
2422 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2423 dwarf::GIEL_STATIC);
2425 return dwarf::GIEK_NONE;
2429 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2431 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2432 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2433 const MCSection *PSec =
2434 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2435 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2437 typedef DenseMap<const MDNode *, CompileUnit *> CUMapType;
2438 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2439 CompileUnit *TheCU = I->second;
2440 unsigned ID = TheCU->getUniqueID();
2442 // Start the dwarf pubnames section.
2443 Asm->OutStreamer.SwitchSection(PSec);
2445 // Emit a label so we can reference the beginning of this pubname section.
2447 Asm->OutStreamer.EmitLabel(
2448 Asm->GetTempSymbol("gnu_pubnames", TheCU->getUniqueID()));
2451 Asm->OutStreamer.AddComment("Length of Public Names Info");
2452 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2453 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2455 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2457 Asm->OutStreamer.AddComment("DWARF Version");
2458 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2460 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2461 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2462 DwarfInfoSectionSym);
2464 Asm->OutStreamer.AddComment("Compilation Unit Length");
2465 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2466 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2469 // Emit the pubnames for this compilation unit.
2470 const StringMap<const DIE *> &Globals = TheCU->getGlobalNames();
2471 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2474 const char *Name = GI->getKeyData();
2475 const DIE *Entity = GI->second;
2477 Asm->OutStreamer.AddComment("DIE offset");
2478 Asm->EmitInt32(Entity->getOffset());
2481 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2482 Asm->OutStreamer.AddComment(
2483 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2484 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2485 Asm->EmitInt8(Desc.toBits());
2488 if (Asm->isVerbose())
2489 Asm->OutStreamer.AddComment("External Name");
2490 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2493 Asm->OutStreamer.AddComment("End Mark");
2495 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2499 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2500 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2501 const MCSection *PSec =
2502 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2503 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2505 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2508 CompileUnit *TheCU = I->second;
2509 // Start the dwarf pubtypes section.
2510 Asm->OutStreamer.SwitchSection(PSec);
2512 // Emit a label so we can reference the beginning of this pubtype section.
2514 Asm->OutStreamer.EmitLabel(
2515 Asm->GetTempSymbol("gnu_pubtypes", TheCU->getUniqueID()));
2518 Asm->OutStreamer.AddComment("Length of Public Types Info");
2519 Asm->EmitLabelDifference(
2520 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2521 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2523 Asm->OutStreamer.EmitLabel(
2524 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()));
2526 if (Asm->isVerbose())
2527 Asm->OutStreamer.AddComment("DWARF Version");
2528 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2530 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2531 Asm->EmitSectionOffset(
2532 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()),
2533 DwarfInfoSectionSym);
2535 Asm->OutStreamer.AddComment("Compilation Unit Length");
2536 Asm->EmitLabelDifference(
2537 Asm->GetTempSymbol(ISec->getLabelEndName(), TheCU->getUniqueID()),
2538 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()), 4);
2540 // Emit the pubtypes.
2541 const StringMap<const DIE *> &Globals = TheCU->getGlobalTypes();
2542 for (StringMap<const DIE *>::const_iterator GI = Globals.begin(),
2545 const char *Name = GI->getKeyData();
2546 const DIE *Entity = GI->second;
2548 if (Asm->isVerbose())
2549 Asm->OutStreamer.AddComment("DIE offset");
2550 Asm->EmitInt32(Entity->getOffset());
2553 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2554 Asm->OutStreamer.AddComment(
2555 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2556 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2557 Asm->EmitInt8(Desc.toBits());
2560 if (Asm->isVerbose())
2561 Asm->OutStreamer.AddComment("External Name");
2563 // Emit the name with a terminating null byte.
2564 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2567 Asm->OutStreamer.AddComment("End Mark");
2569 Asm->OutStreamer.EmitLabel(
2570 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()));
2574 // Emit strings into a string section.
2575 void DwarfUnits::emitStrings(const MCSection *StrSection,
2576 const MCSection *OffsetSection = NULL,
2577 const MCSymbol *StrSecSym = NULL) {
2579 if (StringPool.empty())
2582 // Start the dwarf str section.
2583 Asm->OutStreamer.SwitchSection(StrSection);
2585 // Get all of the string pool entries and put them in an array by their ID so
2586 // we can sort them.
2588 std::pair<unsigned, StringMapEntry<std::pair<MCSymbol *, unsigned> > *>,
2591 for (StringMap<std::pair<MCSymbol *, unsigned> >::iterator
2592 I = StringPool.begin(),
2593 E = StringPool.end();
2595 Entries.push_back(std::make_pair(I->second.second, &*I));
2597 array_pod_sort(Entries.begin(), Entries.end());
2599 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2600 // Emit a label for reference from debug information entries.
2601 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2603 // Emit the string itself with a terminating null byte.
2604 Asm->OutStreamer.EmitBytes(
2605 StringRef(Entries[i].second->getKeyData(),
2606 Entries[i].second->getKeyLength() + 1));
2609 // If we've got an offset section go ahead and emit that now as well.
2610 if (OffsetSection) {
2611 Asm->OutStreamer.SwitchSection(OffsetSection);
2612 unsigned offset = 0;
2613 unsigned size = 4; // FIXME: DWARF64 is 8.
2614 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2615 Asm->OutStreamer.EmitIntValue(offset, size);
2616 offset += Entries[i].second->getKeyLength() + 1;
2622 // Emit addresses into the section given.
2623 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2625 if (AddressPool.empty())
2628 // Start the dwarf addr section.
2629 Asm->OutStreamer.SwitchSection(AddrSection);
2631 // Order the address pool entries by ID
2632 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2634 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2635 E = AddressPool.end();
2637 Entries[I->second] = I->first;
2639 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2640 // Emit an expression for reference from debug information entries.
2641 if (const MCExpr *Expr = Entries[i])
2642 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2644 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2648 // Emit visible names into a debug str section.
2649 void DwarfDebug::emitDebugStr() {
2650 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2651 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2654 // Emit locations into the debug loc section.
2655 void DwarfDebug::emitDebugLoc() {
2656 if (DotDebugLocEntries.empty())
2659 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2660 I = DotDebugLocEntries.begin(),
2661 E = DotDebugLocEntries.end();
2663 DotDebugLocEntry &Entry = *I;
2664 if (I + 1 != DotDebugLocEntries.end())
2668 // Start the dwarf loc section.
2669 Asm->OutStreamer.SwitchSection(
2670 Asm->getObjFileLowering().getDwarfLocSection());
2671 unsigned char Size = Asm->getDataLayout().getPointerSize();
2672 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2674 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2675 I = DotDebugLocEntries.begin(),
2676 E = DotDebugLocEntries.end();
2677 I != E; ++I, ++index) {
2678 DotDebugLocEntry &Entry = *I;
2679 if (Entry.isMerged())
2681 if (Entry.isEmpty()) {
2682 Asm->OutStreamer.EmitIntValue(0, Size);
2683 Asm->OutStreamer.EmitIntValue(0, Size);
2684 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2686 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2687 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2688 DIVariable DV(Entry.getVariable());
2689 Asm->OutStreamer.AddComment("Loc expr size");
2690 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2691 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2692 Asm->EmitLabelDifference(end, begin, 2);
2693 Asm->OutStreamer.EmitLabel(begin);
2694 if (Entry.isInt()) {
2695 DIBasicType BTy(DV.getType());
2696 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2697 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2698 Asm->OutStreamer.AddComment("DW_OP_consts");
2699 Asm->EmitInt8(dwarf::DW_OP_consts);
2700 Asm->EmitSLEB128(Entry.getInt());
2702 Asm->OutStreamer.AddComment("DW_OP_constu");
2703 Asm->EmitInt8(dwarf::DW_OP_constu);
2704 Asm->EmitULEB128(Entry.getInt());
2706 } else if (Entry.isLocation()) {
2707 MachineLocation Loc = Entry.getLoc();
2708 if (!DV.hasComplexAddress())
2710 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2712 // Complex address entry.
2713 unsigned N = DV.getNumAddrElements();
2715 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2716 if (Loc.getOffset()) {
2718 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2719 Asm->OutStreamer.AddComment("DW_OP_deref");
2720 Asm->EmitInt8(dwarf::DW_OP_deref);
2721 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2722 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2723 Asm->EmitSLEB128(DV.getAddrElement(1));
2725 // If first address element is OpPlus then emit
2726 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2727 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2728 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2732 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2735 // Emit remaining complex address elements.
2736 for (; i < N; ++i) {
2737 uint64_t Element = DV.getAddrElement(i);
2738 if (Element == DIBuilder::OpPlus) {
2739 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2740 Asm->EmitULEB128(DV.getAddrElement(++i));
2741 } else if (Element == DIBuilder::OpDeref) {
2743 Asm->EmitInt8(dwarf::DW_OP_deref);
2745 llvm_unreachable("unknown Opcode found in complex address");
2749 // else ... ignore constant fp. There is not any good way to
2750 // to represent them here in dwarf.
2751 Asm->OutStreamer.EmitLabel(end);
2756 struct SymbolCUSorter {
2757 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2758 const MCStreamer &Streamer;
2760 bool operator()(const SymbolCU &A, const SymbolCU &B) {
2761 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2762 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2764 // Symbols with no order assigned should be placed at the end.
2765 // (e.g. section end labels)
2767 IA = (unsigned)(-1);
2769 IB = (unsigned)(-1);
2774 static bool CUSort(const CompileUnit *A, const CompileUnit *B) {
2775 return (A->getUniqueID() < B->getUniqueID());
2779 const MCSymbol *Start, *End;
2782 // Emit a debug aranges section, containing a CU lookup for any
2783 // address we can tie back to a CU.
2784 void DwarfDebug::emitDebugARanges() {
2785 // Start the dwarf aranges section.
2786 Asm->OutStreamer.SwitchSection(
2787 Asm->getObjFileLowering().getDwarfARangesSection());
2789 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2793 // Build a list of sections used.
2794 std::vector<const MCSection *> Sections;
2795 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2797 const MCSection *Section = it->first;
2798 Sections.push_back(Section);
2801 // Sort the sections into order.
2802 // This is only done to ensure consistent output order across different runs.
2803 std::sort(Sections.begin(), Sections.end(), SectionSort);
2805 // Build a set of address spans, sorted by CU.
2806 for (size_t SecIdx = 0; SecIdx < Sections.size(); SecIdx++) {
2807 const MCSection *Section = Sections[SecIdx];
2808 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2809 if (List.size() < 2)
2812 // Sort the symbols by offset within the section.
2813 SymbolCUSorter sorter(Asm->OutStreamer);
2814 std::sort(List.begin(), List.end(), sorter);
2816 // If we have no section (e.g. common), just write out
2817 // individual spans for each symbol.
2818 if (Section == NULL) {
2819 for (size_t n = 0; n < List.size(); n++) {
2820 const SymbolCU &Cur = List[n];
2823 Span.Start = Cur.Sym;
2826 Spans[Cur.CU].push_back(Span);
2829 // Build spans between each label.
2830 const MCSymbol *StartSym = List[0].Sym;
2831 for (size_t n = 1; n < List.size(); n++) {
2832 const SymbolCU &Prev = List[n - 1];
2833 const SymbolCU &Cur = List[n];
2835 // Try and build the longest span we can within the same CU.
2836 if (Cur.CU != Prev.CU) {
2838 Span.Start = StartSym;
2840 Spans[Prev.CU].push_back(Span);
2847 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2848 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2850 // Build a list of CUs used.
2851 std::vector<CompileUnit *> CUs;
2852 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2853 CompileUnit *CU = it->first;
2857 // Sort the CU list (again, to ensure consistent output order).
2858 std::sort(CUs.begin(), CUs.end(), CUSort);
2860 // Emit an arange table for each CU we used.
2861 for (size_t CUIdx = 0; CUIdx < CUs.size(); CUIdx++) {
2862 CompileUnit *CU = CUs[CUIdx];
2863 std::vector<ArangeSpan> &List = Spans[CU];
2865 // Emit size of content not including length itself.
2866 unsigned ContentSize =
2867 sizeof(int16_t) + // DWARF ARange version number
2868 sizeof(int32_t) + // Offset of CU in the .debug_info section
2869 sizeof(int8_t) + // Pointer Size (in bytes)
2870 sizeof(int8_t); // Segment Size (in bytes)
2872 unsigned TupleSize = PtrSize * 2;
2874 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2875 unsigned Padding = 0;
2876 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2879 ContentSize += Padding;
2880 ContentSize += (List.size() + 1) * TupleSize;
2882 // For each compile unit, write the list of spans it covers.
2883 Asm->OutStreamer.AddComment("Length of ARange Set");
2884 Asm->EmitInt32(ContentSize);
2885 Asm->OutStreamer.AddComment("DWARF Arange version number");
2886 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2887 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2888 Asm->EmitSectionOffset(
2889 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2890 DwarfInfoSectionSym);
2891 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2892 Asm->EmitInt8(PtrSize);
2893 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2896 for (unsigned n = 0; n < Padding; n++)
2897 Asm->EmitInt8(0xff);
2899 for (unsigned n = 0; n < List.size(); n++) {
2900 const ArangeSpan &Span = List[n];
2901 Asm->EmitLabelReference(Span.Start, PtrSize);
2903 // Calculate the size as being from the span start to it's end.
2905 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2907 // For symbols without an end marker (e.g. common), we
2908 // write a single arange entry containing just that one symbol.
2909 uint64_t Size = SymSize[Span.Start];
2913 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2917 Asm->OutStreamer.AddComment("ARange terminator");
2918 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2919 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2923 // Emit visible names into a debug ranges section.
2924 void DwarfDebug::emitDebugRanges() {
2925 // Start the dwarf ranges section.
2926 Asm->OutStreamer.SwitchSection(
2927 Asm->getObjFileLowering().getDwarfRangesSection());
2928 unsigned char Size = Asm->getDataLayout().getPointerSize();
2929 for (uint32_t i = 0, e = DebugRangeSymbols.size(); i < e; ++i) {
2930 // Only emit a symbol for every range pair for now.
2931 // FIXME: Make this per range list.
2933 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_ranges", i));
2935 const MCSymbol *I = DebugRangeSymbols[i];
2937 Asm->OutStreamer.EmitSymbolValue(I, Size);
2939 Asm->OutStreamer.EmitIntValue(0, Size);
2943 // Emit visible names into a debug macinfo section.
2944 void DwarfDebug::emitDebugMacInfo() {
2945 if (const MCSection *LineInfo =
2946 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2947 // Start the dwarf macinfo section.
2948 Asm->OutStreamer.SwitchSection(LineInfo);
2952 // DWARF5 Experimental Separate Dwarf emitters.
2954 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2955 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2956 // DW_AT_ranges_base, DW_AT_addr_base.
2957 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2959 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2960 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2961 Asm, this, &SkeletonHolder);
2963 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2964 CU->getNode().getSplitDebugFilename());
2966 // Relocate to the beginning of the addr_base section, else 0 for the
2967 // beginning of the one for this compile unit.
2968 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2969 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base,
2970 DwarfAddrSectionSym);
2972 NewCU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2974 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2975 // into an entity. We're using 0, or a NULL label for this.
2976 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2978 // DW_AT_stmt_list is a offset of line number information for this
2979 // compile unit in debug_line section.
2980 // FIXME: Should handle multiple compile units.
2981 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2982 NewCU->addSectionLabel(Die, dwarf::DW_AT_stmt_list,
2983 DwarfLineSectionSym);
2985 NewCU->addSectionOffset(Die, dwarf::DW_AT_stmt_list, 0);
2987 if (!CompilationDir.empty())
2988 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2990 // Flags to let the linker know we have emitted new style pubnames.
2991 if (GenerateGnuPubSections) {
2992 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2993 NewCU->addSectionLabel(
2994 Die, dwarf::DW_AT_GNU_pubnames,
2995 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
2997 NewCU->addSectionDelta(
2998 Die, dwarf::DW_AT_GNU_pubnames,
2999 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
3000 DwarfGnuPubNamesSectionSym);
3002 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3003 NewCU->addSectionLabel(
3004 Die, dwarf::DW_AT_GNU_pubtypes,
3005 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
3007 NewCU->addSectionDelta(
3008 Die, dwarf::DW_AT_GNU_pubtypes,
3009 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
3010 DwarfGnuPubTypesSectionSym);
3013 // Flag if we've emitted any ranges and their location for the compile unit.
3014 if (DebugRangeSymbols.size()) {
3015 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3016 NewCU->addSectionLabel(Die, dwarf::DW_AT_GNU_ranges_base,
3017 DwarfDebugRangeSectionSym);
3019 NewCU->addUInt(Die, dwarf::DW_AT_GNU_ranges_base, dwarf::DW_FORM_data4,
3023 SkeletonHolder.addUnit(NewCU);
3024 SkeletonCUs.push_back(NewCU);
3029 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
3030 assert(useSplitDwarf() && "No split dwarf debug info?");
3031 emitAbbrevs(Section, &SkeletonAbbrevs);
3034 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3035 // compile units that would normally be in debug_info.
3036 void DwarfDebug::emitDebugInfoDWO() {
3037 assert(useSplitDwarf() && "No split dwarf debug info?");
3038 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
3039 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3040 DwarfAbbrevDWOSectionSym);
3043 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3044 // abbreviations for the .debug_info.dwo section.
3045 void DwarfDebug::emitDebugAbbrevDWO() {
3046 assert(useSplitDwarf() && "No split dwarf?");
3047 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3051 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3052 // string section and is identical in format to traditional .debug_str
3054 void DwarfDebug::emitDebugStrDWO() {
3055 assert(useSplitDwarf() && "No split dwarf?");
3056 const MCSection *OffSec =
3057 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3058 const MCSymbol *StrSym = DwarfStrSectionSym;
3059 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3063 void DwarfDebug::addTypeUnitType(DIE *RefDie, DICompositeType CTy) {
3064 DenseMap<const MDNode*, std::pair<uint64_t, SmallVectorImpl<DIE*>* > >::iterator I = TypeUnits.find(CTy);
3065 SmallVector<DIE *, 8> References;
3066 References.push_back(RefDie);
3067 if (I != TypeUnits.end()) {
3068 if (I->second.second) {
3069 I->second.second->push_back(RefDie);
3073 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
3074 CompileUnit *NewCU =
3075 new CompileUnit(GlobalCUIndexCount++, UnitDie,
3076 dwarf::DW_LANG_C_plus_plus, Asm, this, &InfoHolder);
3077 CUDieMap.insert(std::make_pair(UnitDie, NewCU));
3078 NewCU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3079 dwarf::DW_LANG_C_plus_plus);
3081 // Register the type in the TypeUnits map with a vector of references to be
3082 // populated whenever a reference is required.
3083 I = TypeUnits.insert(std::make_pair(CTy, std::make_pair(0, &References)))
3086 // Construct the type, this may, recursively, require more type units that
3087 // may in turn require this type again - in which case they will add DIEs to
3088 // the References vector.
3089 DIE *Die = NewCU->createTypeDIE(CTy);
3091 if (GenerateODRHash && shouldAddODRHash(NewCU, Die))
3092 NewCU->addUInt(UnitDie, dwarf::DW_AT_GNU_odr_signature,
3093 dwarf::DW_FORM_data8,
3094 DIEHash().computeDIEODRSignature(*Die));
3095 // FIXME: This won't handle circularly referential structures, as the DIE
3096 // may have references to other DIEs still under construction and missing
3097 // their signature. Hashing should walk through the signatures to their
3098 // referenced type, or possibly walk the precomputed hashes of related types
3100 uint64_t Signature = DIEHash().computeTypeSignature(*Die);
3102 // Remove the References vector and add the type hash.
3103 I->second.first = Signature;
3104 I->second.second = NULL;
3107 InfoHolder.addUnit(NewCU);
3110 // Populate all the signatures.
3111 for (unsigned i = 0, e = References.size(); i != e; ++i) {
3112 CUMap.begin()->second->addUInt(References[i], dwarf::DW_AT_signature,
3113 dwarf::DW_FORM_ref_sig8, I->second.first);