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."),
67 GenerateCUHash("generate-cu-hash", cl::Hidden,
68 cl::desc("Add the CU hash as the dwo_id."),
72 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
73 cl::desc("Generate GNU-style pubnames and pubtypes"),
84 static cl::opt<DefaultOnOff>
85 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
86 cl::desc("Output prototype dwarf accelerator tables."),
87 cl::values(clEnumVal(Default, "Default for platform"),
88 clEnumVal(Enable, "Enabled"),
89 clEnumVal(Disable, "Disabled"), clEnumValEnd),
92 static cl::opt<DefaultOnOff>
93 SplitDwarf("split-dwarf", cl::Hidden,
94 cl::desc("Output prototype dwarf split debug info."),
95 cl::values(clEnumVal(Default, "Default for platform"),
96 clEnumVal(Enable, "Enabled"),
97 clEnumVal(Disable, "Disabled"), clEnumValEnd),
100 static cl::opt<DefaultOnOff>
101 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
102 cl::desc("Generate DWARF pubnames and pubtypes sections"),
103 cl::values(clEnumVal(Default, "Default for platform"),
104 clEnumVal(Enable, "Enabled"),
105 clEnumVal(Disable, "Disabled"), clEnumValEnd),
108 static const char *const DWARFGroupName = "DWARF Emission";
109 static const char *const DbgTimerName = "DWARF Debug Writer";
111 //===----------------------------------------------------------------------===//
113 // Configuration values for initial hash set sizes (log2).
115 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
119 /// resolve - Look in the DwarfDebug map for the MDNode that
120 /// corresponds to the reference.
121 template <typename T>
122 T DbgVariable::resolve(DIRef<T> Ref) const {
123 return DD->resolve(Ref);
126 DIType DbgVariable::getType() const {
127 DIType Ty = Var.getType();
128 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
129 // addresses instead.
130 if (Var.isBlockByrefVariable()) {
131 /* Byref variables, in Blocks, are declared by the programmer as
132 "SomeType VarName;", but the compiler creates a
133 __Block_byref_x_VarName struct, and gives the variable VarName
134 either the struct, or a pointer to the struct, as its type. This
135 is necessary for various behind-the-scenes things the compiler
136 needs to do with by-reference variables in blocks.
138 However, as far as the original *programmer* is concerned, the
139 variable should still have type 'SomeType', as originally declared.
141 The following function dives into the __Block_byref_x_VarName
142 struct to find the original type of the variable. This will be
143 passed back to the code generating the type for the Debug
144 Information Entry for the variable 'VarName'. 'VarName' will then
145 have the original type 'SomeType' in its debug information.
147 The original type 'SomeType' will be the type of the field named
148 'VarName' inside the __Block_byref_x_VarName struct.
150 NOTE: In order for this to not completely fail on the debugger
151 side, the Debug Information Entry for the variable VarName needs to
152 have a DW_AT_location that tells the debugger how to unwind through
153 the pointers and __Block_byref_x_VarName struct to find the actual
154 value of the variable. The function addBlockByrefType does this. */
156 uint16_t tag = Ty.getTag();
158 if (tag == dwarf::DW_TAG_pointer_type)
159 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
161 DIArray Elements = DICompositeType(subType).getTypeArray();
162 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
163 DIDerivedType DT = DIDerivedType(Elements.getElement(i));
164 if (getName() == DT.getName())
165 return (resolve(DT.getTypeDerivedFrom()));
171 } // end llvm namespace
173 /// Return Dwarf Version by checking module flags.
174 static unsigned getDwarfVersionFromModule(const Module *M) {
175 Value *Val = M->getModuleFlag("Dwarf Version");
177 return dwarf::DWARF_VERSION;
178 return cast<ConstantInt>(Val)->getZExtValue();
181 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
182 : Asm(A), MMI(Asm->MMI), FirstCU(0),
183 AbbreviationsSet(InitAbbreviationsSetSize),
184 SourceIdMap(DIEValueAllocator),
185 PrevLabel(NULL), GlobalCUIndexCount(0),
186 InfoHolder(A, &AbbreviationsSet, Abbreviations, "info_string",
188 SkeletonAbbrevSet(InitAbbreviationsSetSize),
189 SkeletonHolder(A, &SkeletonAbbrevSet, SkeletonAbbrevs, "skel_string",
192 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
193 DwarfStrSectionSym = TextSectionSym = 0;
194 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
195 DwarfAddrSectionSym = 0;
196 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
197 FunctionBeginSym = FunctionEndSym = 0;
199 // Turn on accelerator tables for Darwin by default, pubnames by
200 // default for non-Darwin, and handle split dwarf.
201 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
203 if (DwarfAccelTables == Default)
204 HasDwarfAccelTables = IsDarwin;
206 HasDwarfAccelTables = DwarfAccelTables == Enable;
208 if (SplitDwarf == Default)
209 HasSplitDwarf = false;
211 HasSplitDwarf = SplitDwarf == Enable;
213 if (DwarfPubSections == Default)
214 HasDwarfPubSections = !IsDarwin;
216 HasDwarfPubSections = DwarfPubSections == Enable;
218 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
221 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
226 // Switch to the specified MCSection and emit an assembler
227 // temporary label to it if SymbolStem is specified.
228 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
229 const char *SymbolStem = 0) {
230 Asm->OutStreamer.SwitchSection(Section);
231 if (!SymbolStem) return 0;
233 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
234 Asm->OutStreamer.EmitLabel(TmpSym);
238 MCSymbol *DwarfUnits::getStringPoolSym() {
239 return Asm->GetTempSymbol(StringPref);
242 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
243 std::pair<MCSymbol*, unsigned> &Entry =
244 StringPool.GetOrCreateValue(Str).getValue();
245 if (Entry.first) return Entry.first;
247 Entry.second = NextStringPoolNumber++;
248 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
251 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
252 std::pair<MCSymbol*, unsigned> &Entry =
253 StringPool.GetOrCreateValue(Str).getValue();
254 if (Entry.first) return Entry.second;
256 Entry.second = NextStringPoolNumber++;
257 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
261 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
262 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
265 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
266 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
267 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
269 ++NextAddrPoolNumber;
270 return P.first->second;
273 // Define a unique number for the abbreviation.
275 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
276 // Check the set for priors.
277 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
279 // If it's newly added.
280 if (InSet == &Abbrev) {
281 // Add to abbreviation list.
282 Abbreviations.push_back(&Abbrev);
284 // Assign the vector position + 1 as its number.
285 Abbrev.setNumber(Abbreviations.size());
287 // Assign existing abbreviation number.
288 Abbrev.setNumber(InSet->getNumber());
292 static bool isObjCClass(StringRef Name) {
293 return Name.startswith("+") || Name.startswith("-");
296 static bool hasObjCCategory(StringRef Name) {
297 if (!isObjCClass(Name)) return false;
299 return Name.find(") ") != StringRef::npos;
302 static void getObjCClassCategory(StringRef In, StringRef &Class,
303 StringRef &Category) {
304 if (!hasObjCCategory(In)) {
305 Class = In.slice(In.find('[') + 1, In.find(' '));
310 Class = In.slice(In.find('[') + 1, In.find('('));
311 Category = In.slice(In.find('[') + 1, In.find(' '));
315 static StringRef getObjCMethodName(StringRef In) {
316 return In.slice(In.find(' ') + 1, In.find(']'));
319 // Helper for sorting sections into a stable output order.
320 static bool SectionSort(const MCSection *A, const MCSection *B) {
321 std::string LA = (A ? A->getLabelBeginName() : "");
322 std::string LB = (B ? B->getLabelBeginName() : "");
326 // Add the various names to the Dwarf accelerator table names.
327 // TODO: Determine whether or not we should add names for programs
328 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
329 // is only slightly different than the lookup of non-standard ObjC names.
330 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
332 if (!SP.isDefinition()) return;
333 TheCU->addAccelName(SP.getName(), Die);
335 // If the linkage name is different than the name, go ahead and output
336 // that as well into the name table.
337 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
338 TheCU->addAccelName(SP.getLinkageName(), Die);
340 // If this is an Objective-C selector name add it to the ObjC accelerator
342 if (isObjCClass(SP.getName())) {
343 StringRef Class, Category;
344 getObjCClassCategory(SP.getName(), Class, Category);
345 TheCU->addAccelObjC(Class, Die);
347 TheCU->addAccelObjC(Category, Die);
348 // Also add the base method name to the name table.
349 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
353 /// isSubprogramContext - Return true if Context is either a subprogram
354 /// or another context nested inside a subprogram.
355 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
358 DIDescriptor D(Context);
359 if (D.isSubprogram())
362 return isSubprogramContext(resolve(DIType(Context).getContext()));
366 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
367 // and DW_AT_high_pc attributes. If there are global variables in this
368 // scope then create and insert DIEs for these variables.
369 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU, DISubprogram SP) {
370 DIE *SPDie = SPCU->getDIE(SP);
372 assert(SPDie && "Unable to find subprogram DIE!");
374 // If we're updating an abstract DIE, then we will be adding the children and
375 // object pointer later on. But what we don't want to do is process the
376 // concrete DIE twice.
377 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
378 // Pick up abstract subprogram DIE.
379 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getCUDie());
380 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
382 DISubprogram SPDecl = SP.getFunctionDeclaration();
383 if (!SPDecl.isSubprogram()) {
384 // There is not any need to generate specification DIE for a function
385 // defined at compile unit level. If a function is defined inside another
386 // function then gdb prefers the definition at top level and but does not
387 // expect specification DIE in parent function. So avoid creating
388 // specification DIE for a function defined inside a function.
389 DIScope SPContext = resolve(SP.getContext());
390 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
391 !SPContext.isFile() &&
392 !isSubprogramContext(SPContext)) {
393 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
396 DICompositeType SPTy = SP.getType();
397 DIArray Args = SPTy.getTypeArray();
398 uint16_t SPTag = SPTy.getTag();
399 if (SPTag == dwarf::DW_TAG_subroutine_type)
400 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
402 SPCU->createAndAddDIE(dwarf::DW_TAG_formal_parameter, *SPDie);
403 DIType ATy = DIType(Args.getElement(i));
404 SPCU->addType(Arg, ATy);
405 if (ATy.isArtificial())
406 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
407 if (ATy.isObjectPointer())
408 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
410 DIE *SPDeclDie = SPDie;
412 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getCUDie());
413 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
418 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
419 Asm->GetTempSymbol("func_begin",
420 Asm->getFunctionNumber()));
421 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
422 Asm->GetTempSymbol("func_end",
423 Asm->getFunctionNumber()));
424 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
425 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
426 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
428 // Add name to the name table, we do this here because we're guaranteed
429 // to have concrete versions of our DW_TAG_subprogram nodes.
430 addSubprogramNames(SPCU, SP, SPDie);
435 /// Check whether we should create a DIE for the given Scope, return true
436 /// if we don't create a DIE (the corresponding DIE is null).
437 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
438 if (Scope->isAbstractScope())
441 // We don't create a DIE if there is no Range.
442 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
446 if (Ranges.size() > 1)
449 // We don't create a DIE if we have a single Range and the end label
451 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
452 MCSymbol *End = getLabelAfterInsn(RI->second);
456 // Construct new DW_TAG_lexical_block for this scope and attach
457 // DW_AT_low_pc/DW_AT_high_pc labels.
458 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
459 LexicalScope *Scope) {
460 if (isLexicalScopeDIENull(Scope))
463 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
464 if (Scope->isAbstractScope())
467 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
468 // If we have multiple ranges, emit them into the range section.
469 if (Ranges.size() > 1) {
470 // .debug_range section has not been laid out yet. Emit offset in
471 // .debug_range as a uint, size 4, for now. emitDIE will handle
472 // DW_AT_ranges appropriately.
473 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
474 DebugRangeSymbols.size()
475 * Asm->getDataLayout().getPointerSize());
476 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
477 RE = Ranges.end(); RI != RE; ++RI) {
478 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
479 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
482 // Terminate the range list.
483 DebugRangeSymbols.push_back(NULL);
484 DebugRangeSymbols.push_back(NULL);
488 // Construct the address range for this DIE.
489 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
490 MCSymbol *Start = getLabelBeforeInsn(RI->first);
491 MCSymbol *End = getLabelAfterInsn(RI->second);
492 assert(End && "End label should not be null!");
494 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
495 assert(End->isDefined() && "Invalid end label for an inlined scope!");
497 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
498 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
503 // This scope represents inlined body of a function. Construct DIE to
504 // represent this concrete inlined copy of the function.
505 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
506 LexicalScope *Scope) {
507 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
508 assert(Ranges.empty() == false &&
509 "LexicalScope does not have instruction markers!");
511 if (!Scope->getScopeNode())
513 DIScope DS(Scope->getScopeNode());
514 DISubprogram InlinedSP = getDISubprogram(DS);
515 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
517 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
521 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
522 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
524 if (Ranges.size() > 1) {
525 // .debug_range section has not been laid out yet. Emit offset in
526 // .debug_range as a uint, size 4, for now. emitDIE will handle
527 // DW_AT_ranges appropriately.
528 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
529 DebugRangeSymbols.size()
530 * Asm->getDataLayout().getPointerSize());
531 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
532 RE = Ranges.end(); RI != RE; ++RI) {
533 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
534 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
536 DebugRangeSymbols.push_back(NULL);
537 DebugRangeSymbols.push_back(NULL);
539 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
540 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
541 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
543 if (StartLabel == 0 || EndLabel == 0)
544 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
546 assert(StartLabel->isDefined() &&
547 "Invalid starting label for an inlined scope!");
548 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
550 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
551 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
554 InlinedSubprogramDIEs.insert(OriginDIE);
556 // Add the call site information to the DIE.
557 DILocation DL(Scope->getInlinedAt());
558 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, None,
559 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
560 TheCU->getUniqueID()));
561 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
563 // Add name to the name table, we do this here because we're guaranteed
564 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
565 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
570 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
571 SmallVectorImpl<DIE*> &Children) {
572 DIE *ObjectPointer = NULL;
574 // Collect arguments for current function.
575 if (LScopes.isCurrentFunctionScope(Scope))
576 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
577 if (DbgVariable *ArgDV = CurrentFnArguments[i])
579 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
580 Children.push_back(Arg);
581 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
584 // Collect lexical scope children first.
585 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
586 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
588 TheCU->constructVariableDIE(*Variables[i], Scope->isAbstractScope())) {
589 Children.push_back(Variable);
590 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
592 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
593 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
594 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
595 Children.push_back(Nested);
596 return ObjectPointer;
599 // Construct a DIE for this scope.
600 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
601 if (!Scope || !Scope->getScopeNode())
604 DIScope DS(Scope->getScopeNode());
606 SmallVector<DIE *, 8> Children;
607 DIE *ObjectPointer = NULL;
608 bool ChildrenCreated = false;
610 // We try to create the scope DIE first, then the children DIEs. This will
611 // avoid creating un-used children then removing them later when we find out
612 // the scope DIE is null.
613 DIE *ScopeDIE = NULL;
614 if (Scope->getInlinedAt())
615 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
616 else if (DS.isSubprogram()) {
617 ProcessedSPNodes.insert(DS);
618 if (Scope->isAbstractScope()) {
619 ScopeDIE = TheCU->getDIE(DS);
620 // Note down abstract DIE.
622 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
625 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
628 // Early exit when we know the scope DIE is going to be null.
629 if (isLexicalScopeDIENull(Scope))
632 // We create children here when we know the scope DIE is not going to be
633 // null and the children will be added to the scope DIE.
634 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
635 ChildrenCreated = true;
637 // There is no need to emit empty lexical block DIE.
638 std::pair<ImportedEntityMap::const_iterator,
639 ImportedEntityMap::const_iterator> Range = std::equal_range(
640 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
641 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
643 if (Children.empty() && Range.first == Range.second)
645 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
646 assert(ScopeDIE && "Scope DIE should not be null.");
647 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
649 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
653 assert(Children.empty() &&
654 "We create children only when the scope DIE is not null.");
657 if (!ChildrenCreated)
658 // We create children when the scope DIE is not null.
659 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
662 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
663 E = Children.end(); I != E; ++I)
664 ScopeDIE->addChild(*I);
666 if (DS.isSubprogram() && ObjectPointer != NULL)
667 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
669 if (DS.isSubprogram())
670 TheCU->addPubTypes(DISubprogram(DS));
675 // Look up the source id with the given directory and source file names.
676 // If none currently exists, create a new id and insert it in the
677 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
679 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
680 StringRef DirName, unsigned CUID) {
681 // If we use .loc in assembly, we can't separate .file entries according to
682 // compile units. Thus all files will belong to the default compile unit.
684 // FIXME: add a better feature test than hasRawTextSupport. Even better,
685 // extend .file to support this.
686 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
689 // If FE did not provide a file name, then assume stdin.
690 if (FileName.empty())
691 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
693 // TODO: this might not belong here. See if we can factor this better.
694 if (DirName == CompilationDir)
697 // FileIDCUMap stores the current ID for the given compile unit.
698 unsigned SrcId = FileIDCUMap[CUID] + 1;
700 // We look up the CUID/file/dir by concatenating them with a zero byte.
701 SmallString<128> NamePair;
702 NamePair += utostr(CUID);
705 NamePair += '\0'; // Zero bytes are not allowed in paths.
706 NamePair += FileName;
708 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
709 if (Ent.getValue() != SrcId)
710 return Ent.getValue();
712 FileIDCUMap[CUID] = SrcId;
713 // Print out a .file directive to specify files for .loc directives.
714 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
719 // Create new CompileUnit for the given metadata node with tag
720 // DW_TAG_compile_unit.
721 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
722 DICompileUnit DIUnit(N);
723 StringRef FN = DIUnit.getFilename();
724 CompilationDir = DIUnit.getDirectory();
726 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
728 new CompileUnit(GlobalCUIndexCount++, Die, N, Asm, this, &InfoHolder);
730 FileIDCUMap[NewCU->getUniqueID()] = 0;
731 // Call this to emit a .file directive if it wasn't emitted for the source
732 // file this CU comes from yet.
733 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
735 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
736 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
737 DIUnit.getLanguage());
738 NewCU->addString(Die, dwarf::DW_AT_name, FN);
740 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
741 // into an entity. We're using 0 (or a NULL label) for this. For
742 // split dwarf it's in the skeleton CU so omit it here.
743 if (!useSplitDwarf())
744 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
746 // Define start line table label for each Compile Unit.
747 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
748 NewCU->getUniqueID());
749 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
750 NewCU->getUniqueID());
752 // Use a single line table if we are using .loc and generating assembly.
754 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
755 (NewCU->getUniqueID() == 0);
757 if (!useSplitDwarf()) {
758 // DW_AT_stmt_list is a offset of line number information for this
759 // compile unit in debug_line section. For split dwarf this is
760 // left in the skeleton CU and so not included.
761 // The line table entries are not always emitted in assembly, so it
762 // is not okay to use line_table_start here.
763 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
764 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
765 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
766 : LineTableStartSym);
767 else if (UseTheFirstCU)
768 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
770 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
771 LineTableStartSym, DwarfLineSectionSym);
773 // If we're using split dwarf the compilation dir is going to be in the
774 // skeleton CU and so we don't need to duplicate it here.
775 if (!CompilationDir.empty())
776 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
778 // Flags to let the linker know we have emitted new style pubnames. Only
779 // emit it here if we don't have a skeleton CU for split dwarf.
780 if (GenerateGnuPubSections) {
781 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
782 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubnames,
783 dwarf::DW_FORM_sec_offset,
784 Asm->GetTempSymbol("gnu_pubnames",
785 NewCU->getUniqueID()));
787 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubnames, dwarf::DW_FORM_data4,
788 Asm->GetTempSymbol("gnu_pubnames",
789 NewCU->getUniqueID()),
790 DwarfGnuPubNamesSectionSym);
792 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
793 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubtypes,
794 dwarf::DW_FORM_sec_offset,
795 Asm->GetTempSymbol("gnu_pubtypes",
796 NewCU->getUniqueID()));
798 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubtypes, dwarf::DW_FORM_data4,
799 Asm->GetTempSymbol("gnu_pubtypes",
800 NewCU->getUniqueID()),
801 DwarfGnuPubTypesSectionSym);
805 if (DIUnit.isOptimized())
806 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
808 StringRef Flags = DIUnit.getFlags();
810 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
812 if (unsigned RVer = DIUnit.getRunTimeVersion())
813 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
814 dwarf::DW_FORM_data1, RVer);
819 InfoHolder.addUnit(NewCU);
821 CUMap.insert(std::make_pair(N, NewCU));
822 CUDieMap.insert(std::make_pair(Die, NewCU));
826 // Construct subprogram DIE.
827 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU, const MDNode *N) {
828 // FIXME: We should only call this routine once, however, during LTO if a
829 // program is defined in multiple CUs we could end up calling it out of
830 // beginModule as we walk the CUs.
832 CompileUnit *&CURef = SPMap[N];
838 if (!SP.isDefinition())
839 // This is a method declaration which will be handled while constructing
843 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
845 // Expose as a global name.
846 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
849 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
851 DIImportedEntity Module(N);
852 if (!Module.Verify())
854 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
855 constructImportedEntityDIE(TheCU, Module, D);
858 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
860 DIImportedEntity Module(N);
861 if (!Module.Verify())
863 return constructImportedEntityDIE(TheCU, Module, Context);
866 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
867 const DIImportedEntity &Module,
869 assert(Module.Verify() &&
870 "Use one of the MDNode * overloads to handle invalid metadata");
871 assert(Context && "Should always have a context for an imported_module");
872 DIE *IMDie = new DIE(Module.getTag());
873 TheCU->insertDIE(Module, IMDie);
875 DIDescriptor Entity = Module.getEntity();
876 if (Entity.isNameSpace())
877 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
878 else if (Entity.isSubprogram())
879 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
880 else if (Entity.isType())
881 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
883 EntityDie = TheCU->getDIE(Entity);
884 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
885 Module.getContext().getDirectory(),
886 TheCU->getUniqueID());
887 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, None, FileID);
888 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, None, Module.getLineNumber());
889 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
890 StringRef Name = Module.getName();
892 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
893 Context->addChild(IMDie);
896 // Emit all Dwarf sections that should come prior to the content. Create
897 // global DIEs and emit initial debug info sections. This is invoked by
898 // the target AsmPrinter.
899 void DwarfDebug::beginModule() {
900 if (DisableDebugInfoPrinting)
903 const Module *M = MMI->getModule();
905 // If module has named metadata anchors then use them, otherwise scan the
906 // module using debug info finder to collect debug info.
907 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
910 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
912 // Emit initial sections so we can reference labels later.
915 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
916 DICompileUnit CUNode(CU_Nodes->getOperand(i));
917 CompileUnit *CU = constructCompileUnit(CUNode);
918 DIArray ImportedEntities = CUNode.getImportedEntities();
919 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
920 ScopesWithImportedEntities.push_back(std::make_pair(
921 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
922 ImportedEntities.getElement(i)));
923 std::sort(ScopesWithImportedEntities.begin(),
924 ScopesWithImportedEntities.end(), less_first());
925 DIArray GVs = CUNode.getGlobalVariables();
926 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
927 CU->createGlobalVariableDIE(GVs.getElement(i));
928 DIArray SPs = CUNode.getSubprograms();
929 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
930 constructSubprogramDIE(CU, SPs.getElement(i));
931 DIArray EnumTypes = CUNode.getEnumTypes();
932 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
933 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
934 DIArray RetainedTypes = CUNode.getRetainedTypes();
935 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
936 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
937 // Emit imported_modules last so that the relevant context is already
939 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
940 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
943 // Tell MMI that we have debug info.
944 MMI->setDebugInfoAvailability(true);
946 // Prime section data.
947 SectionMap[Asm->getObjFileLowering().getTextSection()];
950 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
951 void DwarfDebug::computeInlinedDIEs() {
952 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
953 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
954 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
956 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
958 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
959 AE = AbstractSPDies.end(); AI != AE; ++AI) {
960 DIE *ISP = AI->second;
961 if (InlinedSubprogramDIEs.count(ISP))
963 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
967 // Collect info for variables that were optimized out.
968 void DwarfDebug::collectDeadVariables() {
969 const Module *M = MMI->getModule();
971 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
972 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
973 DICompileUnit TheCU(CU_Nodes->getOperand(i));
974 DIArray Subprograms = TheCU.getSubprograms();
975 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
976 DISubprogram SP(Subprograms.getElement(i));
977 if (ProcessedSPNodes.count(SP) != 0)
979 if (!SP.isSubprogram())
981 if (!SP.isDefinition())
983 DIArray Variables = SP.getVariables();
984 if (Variables.getNumElements() == 0)
987 // Construct subprogram DIE and add variables DIEs.
988 CompileUnit *SPCU = CUMap.lookup(TheCU);
989 assert(SPCU && "Unable to find Compile Unit!");
990 // FIXME: See the comment in constructSubprogramDIE about duplicate
992 constructSubprogramDIE(SPCU, SP);
993 DIE *SPDIE = SPCU->getDIE(SP);
994 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
995 DIVariable DV(Variables.getElement(vi));
996 if (!DV.isVariable())
998 DbgVariable NewVar(DV, NULL, this);
999 if (DIE *VariableDIE =
1000 SPCU->constructVariableDIE(NewVar, false))
1001 SPDIE->addChild(VariableDIE);
1008 // Type Signature [7.27] and ODR Hash code.
1010 /// \brief Grabs the string in whichever attribute is passed in and returns
1011 /// a reference to it. Returns "" if the attribute doesn't exist.
1012 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1013 DIEValue *V = Die->findAttribute(Attr);
1015 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1016 return S->getString();
1018 return StringRef("");
1021 /// Return true if the current DIE is contained within an anonymous namespace.
1022 static bool isContainedInAnonNamespace(DIE *Die) {
1023 DIE *Parent = Die->getParent();
1026 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1027 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1029 Parent = Parent->getParent();
1035 /// Test if the current CU language is C++ and that we have
1036 /// a named type that is not contained in an anonymous namespace.
1037 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
1038 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1039 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1040 !isContainedInAnonNamespace(Die);
1043 void DwarfDebug::finalizeModuleInfo() {
1044 // Collect info for variables that were optimized out.
1045 collectDeadVariables();
1047 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1048 computeInlinedDIEs();
1050 // Split out type units and conditionally add an ODR tag to the split
1052 // FIXME: Do type splitting.
1053 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
1054 DIE *Die = TypeUnits[i];
1056 // If we've requested ODR hashes and it's applicable for an ODR hash then
1057 // add the ODR signature now.
1058 // FIXME: This should be added onto the type unit, not the type, but this
1059 // works as an intermediate stage.
1060 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
1061 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
1062 dwarf::DW_FORM_data8,
1063 Hash.computeDIEODRSignature(*Die));
1066 // Handle anything that needs to be done on a per-cu basis.
1067 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1069 CUI != CUE; ++CUI) {
1070 CompileUnit *TheCU = CUI->second;
1071 // Emit DW_AT_containing_type attribute to connect types with their
1072 // vtable holding type.
1073 TheCU->constructContainingTypeDIEs();
1075 // If we're splitting the dwarf out now that we've got the entire
1076 // CU then construct a skeleton CU based upon it.
1077 if (useSplitDwarf()) {
1079 if (GenerateCUHash) {
1081 ID = CUHash.computeCUSignature(*TheCU->getCUDie());
1083 // This should be a unique identifier when we want to build .dwp files.
1084 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1085 dwarf::DW_FORM_data8, ID);
1086 // Now construct the skeleton CU associated.
1087 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1088 // This should be a unique identifier when we want to build .dwp files.
1089 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1090 dwarf::DW_FORM_data8, ID);
1094 // Compute DIE offsets and sizes.
1095 InfoHolder.computeSizeAndOffsets();
1096 if (useSplitDwarf())
1097 SkeletonHolder.computeSizeAndOffsets();
1100 void DwarfDebug::endSections() {
1101 // Filter labels by section.
1102 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1103 const SymbolCU &SCU = ArangeLabels[n];
1104 if (SCU.Sym->isInSection()) {
1105 // Make a note of this symbol and it's section.
1106 const MCSection *Section = &SCU.Sym->getSection();
1107 if (!Section->getKind().isMetadata())
1108 SectionMap[Section].push_back(SCU);
1110 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1111 // appear in the output. This sucks as we rely on sections to build
1112 // arange spans. We can do it without, but it's icky.
1113 SectionMap[NULL].push_back(SCU);
1117 // Build a list of sections used.
1118 std::vector<const MCSection *> Sections;
1119 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1121 const MCSection *Section = it->first;
1122 Sections.push_back(Section);
1125 // Sort the sections into order.
1126 // This is only done to ensure consistent output order across different runs.
1127 std::sort(Sections.begin(), Sections.end(), SectionSort);
1129 // Add terminating symbols for each section.
1130 for (unsigned ID=0;ID<Sections.size();ID++) {
1131 const MCSection *Section = Sections[ID];
1132 MCSymbol *Sym = NULL;
1135 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1136 // if we know the section name up-front. For user-created sections, the resulting
1137 // label may not be valid to use as a label. (section names can use a greater
1138 // set of characters on some systems)
1139 Sym = Asm->GetTempSymbol("debug_end", ID);
1140 Asm->OutStreamer.SwitchSection(Section);
1141 Asm->OutStreamer.EmitLabel(Sym);
1144 // Insert a final terminator.
1145 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1149 // Emit all Dwarf sections that should come after the content.
1150 void DwarfDebug::endModule() {
1152 if (!FirstCU) return;
1154 // End any existing sections.
1155 // TODO: Does this need to happen?
1158 // Finalize the debug info for the module.
1159 finalizeModuleInfo();
1161 if (!useSplitDwarf()) {
1164 // Emit all the DIEs into a debug info section.
1167 // Corresponding abbreviations into a abbrev section.
1168 emitAbbreviations();
1170 // Emit info into a debug loc section.
1173 // Emit info into a debug aranges section.
1176 // Emit info into a debug ranges section.
1179 // Emit info into a debug macinfo section.
1183 // TODO: Fill this in for separated debug sections and separate
1184 // out information into new sections.
1186 if (useSplitDwarf())
1189 // Emit the debug info section and compile units.
1193 // Corresponding abbreviations into a abbrev section.
1194 emitAbbreviations();
1195 emitDebugAbbrevDWO();
1197 // Emit info into a debug loc section.
1200 // Emit info into a debug aranges section.
1203 // Emit info into a debug ranges section.
1206 // Emit info into a debug macinfo section.
1209 // Emit DWO addresses.
1210 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1214 // Emit info into the dwarf accelerator table sections.
1215 if (useDwarfAccelTables()) {
1218 emitAccelNamespaces();
1222 // Emit the pubnames and pubtypes sections if requested.
1223 if (HasDwarfPubSections) {
1224 emitDebugPubNames(GenerateGnuPubSections);
1225 emitDebugPubTypes(GenerateGnuPubSections);
1230 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1231 E = CUMap.end(); I != E; ++I)
1234 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1235 E = SkeletonCUs.end(); I != E; ++I)
1238 // Reset these for the next Module if we have one.
1242 // Find abstract variable, if any, associated with Var.
1243 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1244 DebugLoc ScopeLoc) {
1245 LLVMContext &Ctx = DV->getContext();
1246 // More then one inlined variable corresponds to one abstract variable.
1247 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1248 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1250 return AbsDbgVariable;
1252 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1256 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1257 addScopeVariable(Scope, AbsDbgVariable);
1258 AbstractVariables[Var] = AbsDbgVariable;
1259 return AbsDbgVariable;
1262 // If Var is a current function argument then add it to CurrentFnArguments list.
1263 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1264 DbgVariable *Var, LexicalScope *Scope) {
1265 if (!LScopes.isCurrentFunctionScope(Scope))
1267 DIVariable DV = Var->getVariable();
1268 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1270 unsigned ArgNo = DV.getArgNumber();
1274 size_t Size = CurrentFnArguments.size();
1276 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1277 // llvm::Function argument size is not good indicator of how many
1278 // arguments does the function have at source level.
1280 CurrentFnArguments.resize(ArgNo * 2);
1281 CurrentFnArguments[ArgNo - 1] = Var;
1285 // Collect variable information from side table maintained by MMI.
1287 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1288 SmallPtrSet<const MDNode *, 16> &Processed) {
1289 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1290 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1291 VE = VMap.end(); VI != VE; ++VI) {
1292 const MDNode *Var = VI->first;
1294 Processed.insert(Var);
1296 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1298 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1300 // If variable scope is not found then skip this variable.
1304 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1305 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1306 RegVar->setFrameIndex(VP.first);
1307 if (!addCurrentFnArgument(MF, RegVar, Scope))
1308 addScopeVariable(Scope, RegVar);
1310 AbsDbgVariable->setFrameIndex(VP.first);
1314 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1316 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1317 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1318 return MI->getNumOperands() == 3 &&
1319 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1320 (MI->getOperand(1).isImm() ||
1321 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1324 // Get .debug_loc entry for the instruction range starting at MI.
1325 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1326 const MCSymbol *FLabel,
1327 const MCSymbol *SLabel,
1328 const MachineInstr *MI) {
1329 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1331 assert(MI->getNumOperands() == 3);
1332 if (MI->getOperand(0).isReg()) {
1333 MachineLocation MLoc;
1334 // If the second operand is an immediate, this is a
1335 // register-indirect address.
1336 if (!MI->getOperand(1).isImm())
1337 MLoc.set(MI->getOperand(0).getReg());
1339 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1340 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1342 if (MI->getOperand(0).isImm())
1343 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1344 if (MI->getOperand(0).isFPImm())
1345 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1346 if (MI->getOperand(0).isCImm())
1347 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1349 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1352 // Find variables for each lexical scope.
1354 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1355 SmallPtrSet<const MDNode *, 16> &Processed) {
1357 // Grab the variable info that was squirreled away in the MMI side-table.
1358 collectVariableInfoFromMMITable(MF, Processed);
1360 for (SmallVectorImpl<const MDNode*>::const_iterator
1361 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1363 const MDNode *Var = *UVI;
1364 if (Processed.count(Var))
1367 // History contains relevant DBG_VALUE instructions for Var and instructions
1369 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1370 if (History.empty())
1372 const MachineInstr *MInsn = History.front();
1375 LexicalScope *Scope = NULL;
1376 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1377 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1378 Scope = LScopes.getCurrentFunctionScope();
1379 else if (MDNode *IA = DV.getInlinedAt())
1380 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1382 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1383 // If variable scope is not found then skip this variable.
1387 Processed.insert(DV);
1388 assert(MInsn->isDebugValue() && "History must begin with debug value");
1389 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1390 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1391 if (!addCurrentFnArgument(MF, RegVar, Scope))
1392 addScopeVariable(Scope, RegVar);
1394 AbsVar->setMInsn(MInsn);
1396 // Simplify ranges that are fully coalesced.
1397 if (History.size() <= 1 || (History.size() == 2 &&
1398 MInsn->isIdenticalTo(History.back()))) {
1399 RegVar->setMInsn(MInsn);
1403 // Handle multiple DBG_VALUE instructions describing one variable.
1404 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1406 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1407 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1408 const MachineInstr *Begin = *HI;
1409 assert(Begin->isDebugValue() && "Invalid History entry");
1411 // Check if DBG_VALUE is truncating a range.
1412 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1413 && !Begin->getOperand(0).getReg())
1416 // Compute the range for a register location.
1417 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1418 const MCSymbol *SLabel = 0;
1421 // If Begin is the last instruction in History then its value is valid
1422 // until the end of the function.
1423 SLabel = FunctionEndSym;
1425 const MachineInstr *End = HI[1];
1426 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1427 << "\t" << *Begin << "\t" << *End << "\n");
1428 if (End->isDebugValue())
1429 SLabel = getLabelBeforeInsn(End);
1431 // End is a normal instruction clobbering the range.
1432 SLabel = getLabelAfterInsn(End);
1433 assert(SLabel && "Forgot label after clobber instruction");
1438 // The value is valid until the next DBG_VALUE or clobber.
1439 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1442 DotDebugLocEntries.push_back(DotDebugLocEntry());
1445 // Collect info for variables that were optimized out.
1446 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1447 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1448 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1449 DIVariable DV(Variables.getElement(i));
1450 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1452 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1453 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1457 // Return Label preceding the instruction.
1458 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1459 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1460 assert(Label && "Didn't insert label before instruction");
1464 // Return Label immediately following the instruction.
1465 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1466 return LabelsAfterInsn.lookup(MI);
1469 // Process beginning of an instruction.
1470 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1471 // Check if source location changes, but ignore DBG_VALUE locations.
1472 if (!MI->isDebugValue()) {
1473 DebugLoc DL = MI->getDebugLoc();
1474 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1477 if (DL == PrologEndLoc) {
1478 Flags |= DWARF2_FLAG_PROLOGUE_END;
1479 PrologEndLoc = DebugLoc();
1481 if (PrologEndLoc.isUnknown())
1482 Flags |= DWARF2_FLAG_IS_STMT;
1484 if (!DL.isUnknown()) {
1485 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1486 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1488 recordSourceLine(0, 0, 0, 0);
1492 // Insert labels where requested.
1493 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1494 LabelsBeforeInsn.find(MI);
1497 if (I == LabelsBeforeInsn.end())
1500 // Label already assigned.
1505 PrevLabel = MMI->getContext().CreateTempSymbol();
1506 Asm->OutStreamer.EmitLabel(PrevLabel);
1508 I->second = PrevLabel;
1511 // Process end of an instruction.
1512 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1513 // Don't create a new label after DBG_VALUE instructions.
1514 // They don't generate code.
1515 if (!MI->isDebugValue())
1518 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1519 LabelsAfterInsn.find(MI);
1522 if (I == LabelsAfterInsn.end())
1525 // Label already assigned.
1529 // We need a label after this instruction.
1531 PrevLabel = MMI->getContext().CreateTempSymbol();
1532 Asm->OutStreamer.EmitLabel(PrevLabel);
1534 I->second = PrevLabel;
1537 // Each LexicalScope has first instruction and last instruction to mark
1538 // beginning and end of a scope respectively. Create an inverse map that list
1539 // scopes starts (and ends) with an instruction. One instruction may start (or
1540 // end) multiple scopes. Ignore scopes that are not reachable.
1541 void DwarfDebug::identifyScopeMarkers() {
1542 SmallVector<LexicalScope *, 4> WorkList;
1543 WorkList.push_back(LScopes.getCurrentFunctionScope());
1544 while (!WorkList.empty()) {
1545 LexicalScope *S = WorkList.pop_back_val();
1547 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1548 if (!Children.empty())
1549 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1550 SE = Children.end(); SI != SE; ++SI)
1551 WorkList.push_back(*SI);
1553 if (S->isAbstractScope())
1556 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1559 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1560 RE = Ranges.end(); RI != RE; ++RI) {
1561 assert(RI->first && "InsnRange does not have first instruction!");
1562 assert(RI->second && "InsnRange does not have second instruction!");
1563 requestLabelBeforeInsn(RI->first);
1564 requestLabelAfterInsn(RI->second);
1569 // Get MDNode for DebugLoc's scope.
1570 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1571 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1572 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1573 return DL.getScope(Ctx);
1576 // Walk up the scope chain of given debug loc and find line number info
1577 // for the function.
1578 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1579 const MDNode *Scope = getScopeNode(DL, Ctx);
1580 DISubprogram SP = getDISubprogram(Scope);
1581 if (SP.isSubprogram()) {
1582 // Check for number of operands since the compatibility is
1584 if (SP->getNumOperands() > 19)
1585 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1587 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1593 // Gather pre-function debug information. Assumes being called immediately
1594 // after the function entry point has been emitted.
1595 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1597 // If there's no debug info for the function we're not going to do anything.
1598 if (!MMI->hasDebugInfo())
1601 // Grab the lexical scopes for the function, if we don't have any of those
1602 // then we're not going to be able to do anything.
1603 LScopes.initialize(*MF);
1604 if (LScopes.empty())
1607 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1609 // Make sure that each lexical scope will have a begin/end label.
1610 identifyScopeMarkers();
1612 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1613 // belongs to so that we add to the correct per-cu line table in the
1615 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1616 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1617 assert(TheCU && "Unable to find compile unit!");
1618 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1619 // Use a single line table if we are using .loc and generating assembly.
1620 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1622 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1624 // Emit a label for the function so that we have a beginning address.
1625 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1626 // Assumes in correct section after the entry point.
1627 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1629 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1630 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1631 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1633 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1635 bool AtBlockEntry = true;
1636 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1638 const MachineInstr *MI = II;
1640 if (MI->isDebugValue()) {
1641 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1643 // Keep track of user variables.
1645 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1647 // Variable is in a register, we need to check for clobbers.
1648 if (isDbgValueInDefinedReg(MI))
1649 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1651 // Check the history of this variable.
1652 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1653 if (History.empty()) {
1654 UserVariables.push_back(Var);
1655 // The first mention of a function argument gets the FunctionBeginSym
1656 // label, so arguments are visible when breaking at function entry.
1658 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1659 DISubprogram(getDISubprogram(DV.getContext()))
1660 .describes(MF->getFunction()))
1661 LabelsBeforeInsn[MI] = FunctionBeginSym;
1663 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1664 const MachineInstr *Prev = History.back();
1665 if (Prev->isDebugValue()) {
1666 // Coalesce identical entries at the end of History.
1667 if (History.size() >= 2 &&
1668 Prev->isIdenticalTo(History[History.size() - 2])) {
1669 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1670 << "\t" << *Prev << "\t"
1671 << *History[History.size() - 2] << "\n");
1675 // Terminate old register assignments that don't reach MI;
1676 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1677 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1678 isDbgValueInDefinedReg(Prev)) {
1679 // Previous register assignment needs to terminate at the end of
1681 MachineBasicBlock::const_iterator LastMI =
1682 PrevMBB->getLastNonDebugInstr();
1683 if (LastMI == PrevMBB->end()) {
1684 // Drop DBG_VALUE for empty range.
1685 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1686 << "\t" << *Prev << "\n");
1688 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1689 // Terminate after LastMI.
1690 History.push_back(LastMI);
1694 History.push_back(MI);
1696 // Not a DBG_VALUE instruction.
1698 AtBlockEntry = false;
1700 // First known non-DBG_VALUE and non-frame setup location marks
1701 // the beginning of the function body.
1702 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1703 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1704 PrologEndLoc = MI->getDebugLoc();
1706 // Check if the instruction clobbers any registers with debug vars.
1707 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1708 MOE = MI->operands_end();
1709 MOI != MOE; ++MOI) {
1710 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1712 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true); AI.isValid();
1715 const MDNode *Var = LiveUserVar[Reg];
1718 // Reg is now clobbered.
1719 LiveUserVar[Reg] = 0;
1721 // Was MD last defined by a DBG_VALUE referring to Reg?
1722 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1723 if (HistI == DbgValues.end())
1725 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1726 if (History.empty())
1728 const MachineInstr *Prev = History.back();
1729 // Sanity-check: Register assignments are terminated at the end of
1731 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1733 // Is the variable still in Reg?
1734 if (!isDbgValueInDefinedReg(Prev) ||
1735 Prev->getOperand(0).getReg() != Reg)
1737 // Var is clobbered. Make sure the next instruction gets a label.
1738 History.push_back(MI);
1745 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1747 SmallVectorImpl<const MachineInstr *> &History = I->second;
1748 if (History.empty())
1751 // Make sure the final register assignments are terminated.
1752 const MachineInstr *Prev = History.back();
1753 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1754 const MachineBasicBlock *PrevMBB = Prev->getParent();
1755 MachineBasicBlock::const_iterator LastMI =
1756 PrevMBB->getLastNonDebugInstr();
1757 if (LastMI == PrevMBB->end())
1758 // Drop DBG_VALUE for empty range.
1760 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1761 // Terminate after LastMI.
1762 History.push_back(LastMI);
1765 // Request labels for the full history.
1766 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1767 const MachineInstr *MI = History[i];
1768 if (MI->isDebugValue())
1769 requestLabelBeforeInsn(MI);
1771 requestLabelAfterInsn(MI);
1775 PrevInstLoc = DebugLoc();
1776 PrevLabel = FunctionBeginSym;
1778 // Record beginning of function.
1779 if (!PrologEndLoc.isUnknown()) {
1780 DebugLoc FnStartDL =
1781 getFnDebugLoc(PrologEndLoc, MF->getFunction()->getContext());
1783 FnStartDL.getLine(), FnStartDL.getCol(),
1784 FnStartDL.getScope(MF->getFunction()->getContext()),
1785 // We'd like to list the prologue as "not statements" but GDB behaves
1786 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1787 DWARF2_FLAG_IS_STMT);
1791 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1792 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1793 DIVariable DV = Var->getVariable();
1794 // Variables with positive arg numbers are parameters.
1795 if (unsigned ArgNum = DV.getArgNumber()) {
1796 // Keep all parameters in order at the start of the variable list to ensure
1797 // function types are correct (no out-of-order parameters)
1799 // This could be improved by only doing it for optimized builds (unoptimized
1800 // builds have the right order to begin with), searching from the back (this
1801 // would catch the unoptimized case quickly), or doing a binary search
1802 // rather than linear search.
1803 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1804 while (I != Vars.end()) {
1805 unsigned CurNum = (*I)->getVariable().getArgNumber();
1806 // A local (non-parameter) variable has been found, insert immediately
1810 // A later indexed parameter has been found, insert immediately before it.
1811 if (CurNum > ArgNum)
1815 Vars.insert(I, Var);
1819 Vars.push_back(Var);
1822 // Gather and emit post-function debug information.
1823 void DwarfDebug::endFunction(const MachineFunction *MF) {
1824 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1826 // Define end label for subprogram.
1827 FunctionEndSym = Asm->GetTempSymbol("func_end",
1828 Asm->getFunctionNumber());
1829 // Assumes in correct section after the entry point.
1830 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1831 // Set DwarfCompileUnitID in MCContext to default value.
1832 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1834 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1835 collectVariableInfo(MF, ProcessedVars);
1837 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1838 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1839 assert(TheCU && "Unable to find compile unit!");
1841 // Construct abstract scopes.
1842 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1843 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1844 LexicalScope *AScope = AList[i];
1845 DISubprogram SP(AScope->getScopeNode());
1846 if (SP.isSubprogram()) {
1847 // Collect info for variables that were optimized out.
1848 DIArray Variables = SP.getVariables();
1849 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1850 DIVariable DV(Variables.getElement(i));
1851 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1853 // Check that DbgVariable for DV wasn't created earlier, when
1854 // findAbstractVariable() was called for inlined instance of DV.
1855 LLVMContext &Ctx = DV->getContext();
1856 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1857 if (AbstractVariables.lookup(CleanDV))
1859 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1860 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1863 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1864 constructScopeDIE(TheCU, AScope);
1867 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1869 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1870 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1873 for (ScopeVariablesMap::iterator
1874 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1875 DeleteContainerPointers(I->second);
1876 ScopeVariables.clear();
1877 DeleteContainerPointers(CurrentFnArguments);
1878 UserVariables.clear();
1880 AbstractVariables.clear();
1881 LabelsBeforeInsn.clear();
1882 LabelsAfterInsn.clear();
1886 // Register a source line with debug info. Returns the unique label that was
1887 // emitted and which provides correspondence to the source line list.
1888 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1894 DIDescriptor Scope(S);
1896 if (Scope.isCompileUnit()) {
1897 DICompileUnit CU(S);
1898 Fn = CU.getFilename();
1899 Dir = CU.getDirectory();
1900 } else if (Scope.isFile()) {
1902 Fn = F.getFilename();
1903 Dir = F.getDirectory();
1904 } else if (Scope.isSubprogram()) {
1906 Fn = SP.getFilename();
1907 Dir = SP.getDirectory();
1908 } else if (Scope.isLexicalBlockFile()) {
1909 DILexicalBlockFile DBF(S);
1910 Fn = DBF.getFilename();
1911 Dir = DBF.getDirectory();
1912 } else if (Scope.isLexicalBlock()) {
1913 DILexicalBlock DB(S);
1914 Fn = DB.getFilename();
1915 Dir = DB.getDirectory();
1917 llvm_unreachable("Unexpected scope info");
1919 Src = getOrCreateSourceID(Fn, Dir,
1920 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1922 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1925 //===----------------------------------------------------------------------===//
1927 //===----------------------------------------------------------------------===//
1929 // Compute the size and offset of a DIE. The offset is relative to start of the
1930 // CU. It returns the offset after laying out the DIE.
1932 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1933 // Get the children.
1934 const std::vector<DIE *> &Children = Die->getChildren();
1936 // Record the abbreviation.
1937 assignAbbrevNumber(Die->getAbbrev());
1939 // Get the abbreviation for this DIE.
1940 unsigned AbbrevNumber = Die->getAbbrevNumber();
1941 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1944 Die->setOffset(Offset);
1946 // Start the size with the size of abbreviation code.
1947 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1949 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1950 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1952 // Size the DIE attribute values.
1953 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1954 // Size attribute value.
1955 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1957 // Size the DIE children if any.
1958 if (!Children.empty()) {
1959 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1960 "Children flag not set");
1962 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1963 Offset = computeSizeAndOffset(Children[j], Offset);
1965 // End of children marker.
1966 Offset += sizeof(int8_t);
1969 Die->setSize(Offset - Die->getOffset());
1973 // Compute the size and offset for each DIE.
1974 void DwarfUnits::computeSizeAndOffsets() {
1975 // Offset from the first CU in the debug info section is 0 initially.
1976 unsigned SecOffset = 0;
1978 // Iterate over each compile unit and set the size and offsets for each
1979 // DIE within each compile unit. All offsets are CU relative.
1980 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1981 E = CUs.end(); I != E; ++I) {
1982 (*I)->setDebugInfoOffset(SecOffset);
1984 // CU-relative offset is reset to 0 here.
1985 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1986 (*I)->getHeaderSize(); // Unit-specific headers
1988 // EndOffset here is CU-relative, after laying out
1989 // all of the CU DIE.
1990 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1991 SecOffset += EndOffset;
1995 // Emit initial Dwarf sections with a label at the start of each one.
1996 void DwarfDebug::emitSectionLabels() {
1997 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1999 // Dwarf sections base addresses.
2000 DwarfInfoSectionSym =
2001 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
2002 DwarfAbbrevSectionSym =
2003 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
2004 if (useSplitDwarf())
2005 DwarfAbbrevDWOSectionSym =
2006 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
2007 "section_abbrev_dwo");
2008 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
2010 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
2011 emitSectionSym(Asm, MacroInfo);
2013 DwarfLineSectionSym =
2014 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
2015 emitSectionSym(Asm, TLOF.getDwarfLocSection());
2016 if (GenerateGnuPubSections) {
2017 DwarfGnuPubNamesSectionSym =
2018 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
2019 DwarfGnuPubTypesSectionSym =
2020 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2021 } else if (HasDwarfPubSections) {
2022 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2023 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2026 DwarfStrSectionSym =
2027 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2028 if (useSplitDwarf()) {
2029 DwarfStrDWOSectionSym =
2030 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2031 DwarfAddrSectionSym =
2032 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2034 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2037 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
2038 "section_debug_loc");
2040 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2041 emitSectionSym(Asm, TLOF.getDataSection());
2044 // Recursively emits a debug information entry.
2045 void DwarfDebug::emitDIE(DIE *Die, ArrayRef<DIEAbbrev *> Abbrevs) {
2046 // Get the abbreviation for this DIE.
2047 unsigned AbbrevNumber = Die->getAbbrevNumber();
2048 const DIEAbbrev *Abbrev = Abbrevs[AbbrevNumber - 1];
2050 // Emit the code (index) for the abbreviation.
2051 if (Asm->isVerbose())
2052 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2053 Twine::utohexstr(Die->getOffset()) + ":0x" +
2054 Twine::utohexstr(Die->getSize()) + " " +
2055 dwarf::TagString(Abbrev->getTag()));
2056 Asm->EmitULEB128(AbbrevNumber);
2058 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
2059 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2061 // Emit the DIE attribute values.
2062 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2063 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
2064 dwarf::Form Form = AbbrevData[i].getForm();
2065 assert(Form && "Too many attributes for DIE (check abbreviation)");
2067 if (Asm->isVerbose())
2068 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2071 case dwarf::DW_AT_abstract_origin:
2072 case dwarf::DW_AT_type:
2073 case dwarf::DW_AT_friend:
2074 case dwarf::DW_AT_specification:
2075 case dwarf::DW_AT_import:
2076 case dwarf::DW_AT_containing_type: {
2077 DIEEntry *E = cast<DIEEntry>(Values[i]);
2078 DIE *Origin = E->getEntry();
2079 unsigned Addr = Origin->getOffset();
2080 if (Form == dwarf::DW_FORM_ref_addr) {
2081 assert(!useSplitDwarf() && "TODO: dwo files can't have relocations.");
2082 // For DW_FORM_ref_addr, output the offset from beginning of debug info
2083 // section. Origin->getOffset() returns the offset from start of the
2085 CompileUnit *CU = CUDieMap.lookup(Origin->getCompileUnit());
2086 assert(CU && "CUDie should belong to a CU.");
2087 Addr += CU->getDebugInfoOffset();
2088 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2089 Asm->EmitLabelPlusOffset(DwarfInfoSectionSym, Addr,
2090 DIEEntry::getRefAddrSize(Asm));
2092 Asm->EmitLabelOffsetDifference(DwarfInfoSectionSym, Addr,
2093 DwarfInfoSectionSym,
2094 DIEEntry::getRefAddrSize(Asm));
2096 // Make sure Origin belong to the same CU.
2097 assert(Die->getCompileUnit() == Origin->getCompileUnit() &&
2098 "The referenced DIE should belong to the same CU in ref4");
2099 Asm->EmitInt32(Addr);
2103 case dwarf::DW_AT_ranges: {
2104 // DW_AT_range Value encodes offset in debug_range section.
2105 DIEInteger *V = cast<DIEInteger>(Values[i]);
2107 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
2108 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2112 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2114 DwarfDebugRangeSectionSym,
2119 case dwarf::DW_AT_location: {
2120 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2121 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2122 Asm->EmitLabelReference(L->getValue(), 4);
2124 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2126 Values[i]->EmitValue(Asm, Form);
2130 case dwarf::DW_AT_accessibility: {
2131 if (Asm->isVerbose()) {
2132 DIEInteger *V = cast<DIEInteger>(Values[i]);
2133 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2135 Values[i]->EmitValue(Asm, Form);
2139 // Emit an attribute using the defined form.
2140 Values[i]->EmitValue(Asm, Form);
2145 // Emit the DIE children if any.
2146 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2147 const std::vector<DIE *> &Children = Die->getChildren();
2149 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2150 emitDIE(Children[j], Abbrevs);
2152 if (Asm->isVerbose())
2153 Asm->OutStreamer.AddComment("End Of Children Mark");
2158 // Emit the various dwarf units to the unit section USection with
2159 // the abbreviations going into ASection.
2160 void DwarfUnits::emitUnits(DwarfDebug *DD,
2161 const MCSection *USection,
2162 const MCSection *ASection,
2163 const MCSymbol *ASectionSym) {
2164 Asm->OutStreamer.SwitchSection(USection);
2165 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2166 E = CUs.end(); I != E; ++I) {
2167 CompileUnit *TheCU = *I;
2168 DIE *Die = TheCU->getCUDie();
2170 // Emit the compile units header.
2172 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2173 TheCU->getUniqueID()));
2175 // Emit size of content not including length itself
2176 Asm->OutStreamer.AddComment("Length of Unit");
2177 Asm->EmitInt32(TheCU->getHeaderSize() + Die->getSize());
2179 TheCU->emitHeader(ASection, ASectionSym);
2181 DD->emitDIE(Die, Abbreviations);
2182 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2183 TheCU->getUniqueID()));
2187 // Emit the debug info section.
2188 void DwarfDebug::emitDebugInfo() {
2189 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2191 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2192 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2193 DwarfAbbrevSectionSym);
2196 // Emit the abbreviation section.
2197 void DwarfDebug::emitAbbreviations() {
2198 if (!useSplitDwarf())
2199 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2202 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2205 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2206 std::vector<DIEAbbrev *> *Abbrevs) {
2207 // Check to see if it is worth the effort.
2208 if (!Abbrevs->empty()) {
2209 // Start the debug abbrev section.
2210 Asm->OutStreamer.SwitchSection(Section);
2212 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2213 Asm->OutStreamer.EmitLabel(Begin);
2215 // For each abbrevation.
2216 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2217 // Get abbreviation data
2218 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2220 // Emit the abbrevations code (base 1 index.)
2221 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2223 // Emit the abbreviations data.
2227 // Mark end of abbreviations.
2228 Asm->EmitULEB128(0, "EOM(3)");
2230 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2231 Asm->OutStreamer.EmitLabel(End);
2235 // Emit the last address of the section and the end of the line matrix.
2236 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2237 // Define last address of section.
2238 Asm->OutStreamer.AddComment("Extended Op");
2241 Asm->OutStreamer.AddComment("Op size");
2242 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2243 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2244 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2246 Asm->OutStreamer.AddComment("Section end label");
2248 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2249 Asm->getDataLayout().getPointerSize());
2251 // Mark end of matrix.
2252 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2258 // Emit visible names into a hashed accelerator table section.
2259 void DwarfDebug::emitAccelNames() {
2260 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2261 dwarf::DW_FORM_data4));
2262 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2263 E = CUMap.end(); I != E; ++I) {
2264 CompileUnit *TheCU = I->second;
2265 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2266 for (StringMap<std::vector<DIE*> >::const_iterator
2267 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2268 StringRef Name = GI->getKey();
2269 const std::vector<DIE *> &Entities = GI->second;
2270 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2271 DE = Entities.end(); DI != DE; ++DI)
2272 AT.AddName(Name, (*DI));
2276 AT.FinalizeTable(Asm, "Names");
2277 Asm->OutStreamer.SwitchSection(
2278 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2279 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2280 Asm->OutStreamer.EmitLabel(SectionBegin);
2282 // Emit the full data.
2283 AT.Emit(Asm, SectionBegin, &InfoHolder);
2286 // Emit objective C classes and categories into a hashed accelerator table
2288 void DwarfDebug::emitAccelObjC() {
2289 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2290 dwarf::DW_FORM_data4));
2291 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2292 E = CUMap.end(); I != E; ++I) {
2293 CompileUnit *TheCU = I->second;
2294 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2295 for (StringMap<std::vector<DIE*> >::const_iterator
2296 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2297 StringRef Name = GI->getKey();
2298 const std::vector<DIE *> &Entities = GI->second;
2299 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2300 DE = Entities.end(); DI != DE; ++DI)
2301 AT.AddName(Name, (*DI));
2305 AT.FinalizeTable(Asm, "ObjC");
2306 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2307 .getDwarfAccelObjCSection());
2308 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2309 Asm->OutStreamer.EmitLabel(SectionBegin);
2311 // Emit the full data.
2312 AT.Emit(Asm, SectionBegin, &InfoHolder);
2315 // Emit namespace dies into a hashed accelerator table.
2316 void DwarfDebug::emitAccelNamespaces() {
2317 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2318 dwarf::DW_FORM_data4));
2319 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2320 E = CUMap.end(); I != E; ++I) {
2321 CompileUnit *TheCU = I->second;
2322 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2323 for (StringMap<std::vector<DIE*> >::const_iterator
2324 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2325 StringRef Name = GI->getKey();
2326 const std::vector<DIE *> &Entities = GI->second;
2327 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2328 DE = Entities.end(); DI != DE; ++DI)
2329 AT.AddName(Name, (*DI));
2333 AT.FinalizeTable(Asm, "namespac");
2334 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2335 .getDwarfAccelNamespaceSection());
2336 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2337 Asm->OutStreamer.EmitLabel(SectionBegin);
2339 // Emit the full data.
2340 AT.Emit(Asm, SectionBegin, &InfoHolder);
2343 // Emit type dies into a hashed accelerator table.
2344 void DwarfDebug::emitAccelTypes() {
2345 std::vector<DwarfAccelTable::Atom> Atoms;
2346 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2347 dwarf::DW_FORM_data4));
2348 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag,
2349 dwarf::DW_FORM_data2));
2350 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags,
2351 dwarf::DW_FORM_data1));
2352 DwarfAccelTable AT(Atoms);
2353 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2354 E = CUMap.end(); I != E; ++I) {
2355 CompileUnit *TheCU = I->second;
2356 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2357 = TheCU->getAccelTypes();
2358 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2359 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2360 StringRef Name = GI->getKey();
2361 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2362 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2363 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2364 AT.AddName(Name, (*DI).first, (*DI).second);
2368 AT.FinalizeTable(Asm, "types");
2369 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2370 .getDwarfAccelTypesSection());
2371 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2372 Asm->OutStreamer.EmitLabel(SectionBegin);
2374 // Emit the full data.
2375 AT.Emit(Asm, SectionBegin, &InfoHolder);
2378 // Public name handling.
2379 // The format for the various pubnames:
2381 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2382 // for the DIE that is named.
2384 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2385 // into the CU and the index value is computed according to the type of value
2386 // for the DIE that is named.
2388 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2389 // it's the offset within the debug_info/debug_types dwo section, however, the
2390 // reference in the pubname header doesn't change.
2392 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2393 static dwarf::PubIndexEntryDescriptor computeIndexValue(CompileUnit *CU,
2395 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2397 // We could have a specification DIE that has our most of our knowledge,
2398 // look for that now.
2399 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2401 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2402 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2403 Linkage = dwarf::GIEL_EXTERNAL;
2404 } else if (Die->findAttribute(dwarf::DW_AT_external))
2405 Linkage = dwarf::GIEL_EXTERNAL;
2407 switch (Die->getTag()) {
2408 case dwarf::DW_TAG_class_type:
2409 case dwarf::DW_TAG_structure_type:
2410 case dwarf::DW_TAG_union_type:
2411 case dwarf::DW_TAG_enumeration_type:
2412 return dwarf::PubIndexEntryDescriptor(
2413 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2414 ? dwarf::GIEL_STATIC
2415 : dwarf::GIEL_EXTERNAL);
2416 case dwarf::DW_TAG_typedef:
2417 case dwarf::DW_TAG_base_type:
2418 case dwarf::DW_TAG_subrange_type:
2419 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2420 case dwarf::DW_TAG_namespace:
2421 return dwarf::GIEK_TYPE;
2422 case dwarf::DW_TAG_subprogram:
2423 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2424 case dwarf::DW_TAG_constant:
2425 case dwarf::DW_TAG_variable:
2426 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2427 case dwarf::DW_TAG_enumerator:
2428 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2429 dwarf::GIEL_STATIC);
2431 return dwarf::GIEK_NONE;
2435 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2437 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2438 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2439 const MCSection *PSec =
2440 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2441 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2443 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2444 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2445 CompileUnit *TheCU = I->second;
2446 unsigned ID = TheCU->getUniqueID();
2448 // Start the dwarf pubnames section.
2449 Asm->OutStreamer.SwitchSection(PSec);
2451 // Emit a label so we can reference the beginning of this pubname section.
2453 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames",
2454 TheCU->getUniqueID()));
2457 Asm->OutStreamer.AddComment("Length of Public Names Info");
2458 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2459 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2461 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2463 Asm->OutStreamer.AddComment("DWARF Version");
2464 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2466 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2467 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2468 DwarfInfoSectionSym);
2470 Asm->OutStreamer.AddComment("Compilation Unit Length");
2471 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2472 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2475 // Emit the pubnames for this compilation unit.
2476 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2477 for (StringMap<DIE*>::const_iterator
2478 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2479 const char *Name = GI->getKeyData();
2480 DIE *Entity = GI->second;
2482 Asm->OutStreamer.AddComment("DIE offset");
2483 Asm->EmitInt32(Entity->getOffset());
2486 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2487 Asm->OutStreamer.AddComment(
2488 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2489 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2490 Asm->EmitInt8(Desc.toBits());
2493 if (Asm->isVerbose())
2494 Asm->OutStreamer.AddComment("External Name");
2495 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2498 Asm->OutStreamer.AddComment("End Mark");
2500 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2504 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2505 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2506 const MCSection *PSec =
2507 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2508 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2510 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2513 CompileUnit *TheCU = I->second;
2514 // Start the dwarf pubtypes section.
2515 Asm->OutStreamer.SwitchSection(PSec);
2517 // Emit a label so we can reference the beginning of this pubtype section.
2519 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes",
2520 TheCU->getUniqueID()));
2523 Asm->OutStreamer.AddComment("Length of Public Types Info");
2524 Asm->EmitLabelDifference(
2525 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2526 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2528 Asm->OutStreamer.EmitLabel(
2529 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()));
2531 if (Asm->isVerbose())
2532 Asm->OutStreamer.AddComment("DWARF Version");
2533 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2535 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2536 Asm->EmitSectionOffset(
2537 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()),
2538 DwarfInfoSectionSym);
2540 Asm->OutStreamer.AddComment("Compilation Unit Length");
2541 Asm->EmitLabelDifference(
2542 Asm->GetTempSymbol(ISec->getLabelEndName(), TheCU->getUniqueID()),
2543 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()), 4);
2545 // Emit the pubtypes.
2546 const StringMap<DIE *> &Globals = TheCU->getGlobalTypes();
2547 for (StringMap<DIE *>::const_iterator GI = Globals.begin(),
2550 const char *Name = GI->getKeyData();
2551 DIE *Entity = GI->second;
2553 if (Asm->isVerbose())
2554 Asm->OutStreamer.AddComment("DIE offset");
2555 Asm->EmitInt32(Entity->getOffset());
2558 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2559 Asm->OutStreamer.AddComment(
2560 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2561 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2562 Asm->EmitInt8(Desc.toBits());
2565 if (Asm->isVerbose())
2566 Asm->OutStreamer.AddComment("External Name");
2568 // Emit the name with a terminating null byte.
2569 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2572 Asm->OutStreamer.AddComment("End Mark");
2574 Asm->OutStreamer.EmitLabel(
2575 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()));
2579 // Emit strings into a string section.
2580 void DwarfUnits::emitStrings(const MCSection *StrSection,
2581 const MCSection *OffsetSection = NULL,
2582 const MCSymbol *StrSecSym = NULL) {
2584 if (StringPool.empty()) return;
2586 // Start the dwarf str section.
2587 Asm->OutStreamer.SwitchSection(StrSection);
2589 // Get all of the string pool entries and put them in an array by their ID so
2590 // we can sort them.
2591 SmallVector<std::pair<unsigned,
2592 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2594 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2595 I = StringPool.begin(), E = StringPool.end();
2597 Entries.push_back(std::make_pair(I->second.second, &*I));
2599 array_pod_sort(Entries.begin(), Entries.end());
2601 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2602 // Emit a label for reference from debug information entries.
2603 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2605 // Emit the string itself with a terminating null byte.
2606 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2607 Entries[i].second->getKeyLength()+1));
2610 // If we've got an offset section go ahead and emit that now as well.
2611 if (OffsetSection) {
2612 Asm->OutStreamer.SwitchSection(OffsetSection);
2613 unsigned offset = 0;
2614 unsigned size = 4; // FIXME: DWARF64 is 8.
2615 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2616 Asm->OutStreamer.EmitIntValue(offset, size);
2617 offset += Entries[i].second->getKeyLength() + 1;
2622 // Emit strings into a string section.
2623 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2625 if (AddressPool.empty()) return;
2627 // Start the dwarf addr section.
2628 Asm->OutStreamer.SwitchSection(AddrSection);
2630 // Order the address pool entries by ID
2631 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2633 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2634 E = AddressPool.end();
2636 Entries[I->second] = I->first;
2638 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2639 // Emit an expression for reference from debug information entries.
2640 if (const MCExpr *Expr = Entries[i])
2641 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2643 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(), E = DotDebugLocEntries.end();
2662 DotDebugLocEntry &Entry = *I;
2663 if (I + 1 != DotDebugLocEntries.end())
2667 // Start the dwarf loc section.
2668 Asm->OutStreamer.SwitchSection(
2669 Asm->getObjFileLowering().getDwarfLocSection());
2670 unsigned char Size = Asm->getDataLayout().getPointerSize();
2671 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2673 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2674 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2675 I != E; ++I, ++index) {
2676 DotDebugLocEntry &Entry = *I;
2677 if (Entry.isMerged()) continue;
2678 if (Entry.isEmpty()) {
2679 Asm->OutStreamer.EmitIntValue(0, Size);
2680 Asm->OutStreamer.EmitIntValue(0, Size);
2681 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2683 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2684 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2685 DIVariable DV(Entry.getVariable());
2686 Asm->OutStreamer.AddComment("Loc expr size");
2687 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2688 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2689 Asm->EmitLabelDifference(end, begin, 2);
2690 Asm->OutStreamer.EmitLabel(begin);
2691 if (Entry.isInt()) {
2692 DIBasicType BTy(DV.getType());
2694 (BTy.getEncoding() == dwarf::DW_ATE_signed
2695 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2696 Asm->OutStreamer.AddComment("DW_OP_consts");
2697 Asm->EmitInt8(dwarf::DW_OP_consts);
2698 Asm->EmitSLEB128(Entry.getInt());
2700 Asm->OutStreamer.AddComment("DW_OP_constu");
2701 Asm->EmitInt8(dwarf::DW_OP_constu);
2702 Asm->EmitULEB128(Entry.getInt());
2704 } else if (Entry.isLocation()) {
2705 MachineLocation Loc = Entry.getLoc();
2706 if (!DV.hasComplexAddress())
2708 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2710 // Complex address entry.
2711 unsigned N = DV.getNumAddrElements();
2713 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2714 if (Loc.getOffset()) {
2716 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2717 Asm->OutStreamer.AddComment("DW_OP_deref");
2718 Asm->EmitInt8(dwarf::DW_OP_deref);
2719 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2720 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2721 Asm->EmitSLEB128(DV.getAddrElement(1));
2723 // If first address element is OpPlus then emit
2724 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2725 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2726 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2730 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2733 // Emit remaining complex address elements.
2734 for (; i < N; ++i) {
2735 uint64_t Element = DV.getAddrElement(i);
2736 if (Element == DIBuilder::OpPlus) {
2737 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2738 Asm->EmitULEB128(DV.getAddrElement(++i));
2739 } else if (Element == DIBuilder::OpDeref) {
2741 Asm->EmitInt8(dwarf::DW_OP_deref);
2743 llvm_unreachable("unknown Opcode found in complex address");
2747 // else ... ignore constant fp. There is not any good way to
2748 // to represent them here in dwarf.
2749 Asm->OutStreamer.EmitLabel(end);
2754 struct SymbolCUSorter {
2755 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2756 const MCStreamer &Streamer;
2758 bool operator() (const SymbolCU &A, const SymbolCU &B) {
2759 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2760 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2762 // Symbols with no order assigned should be placed at the end.
2763 // (e.g. section end labels)
2765 IA = (unsigned)(-1);
2767 IB = (unsigned)(-1);
2772 static bool CUSort(const CompileUnit *A, const CompileUnit *B) {
2773 return (A->getUniqueID() < B->getUniqueID());
2777 const MCSymbol *Start, *End;
2780 // Emit a debug aranges section, containing a CU lookup for any
2781 // address we can tie back to a CU.
2782 void DwarfDebug::emitDebugARanges() {
2783 // Start the dwarf aranges section.
2785 .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2787 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2791 // Build a list of sections used.
2792 std::vector<const MCSection *> Sections;
2793 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2795 const MCSection *Section = it->first;
2796 Sections.push_back(Section);
2799 // Sort the sections into order.
2800 // This is only done to ensure consistent output order across different runs.
2801 std::sort(Sections.begin(), Sections.end(), SectionSort);
2803 // Build a set of address spans, sorted by CU.
2804 for (size_t SecIdx=0;SecIdx<Sections.size();SecIdx++) {
2805 const MCSection *Section = Sections[SecIdx];
2806 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2807 if (List.size() < 2)
2810 // Sort the symbols by offset within the section.
2811 SymbolCUSorter sorter(Asm->OutStreamer);
2812 std::sort(List.begin(), List.end(), sorter);
2814 // If we have no section (e.g. common), just write out
2815 // individual spans for each symbol.
2816 if (Section == NULL) {
2817 for (size_t n = 0; n < List.size(); n++) {
2818 const SymbolCU &Cur = List[n];
2821 Span.Start = Cur.Sym;
2824 Spans[Cur.CU].push_back(Span);
2827 // Build spans between each label.
2828 const MCSymbol *StartSym = List[0].Sym;
2829 for (size_t n = 1; n < List.size(); n++) {
2830 const SymbolCU &Prev = List[n - 1];
2831 const SymbolCU &Cur = List[n];
2833 // Try and build the longest span we can within the same CU.
2834 if (Cur.CU != Prev.CU) {
2836 Span.Start = StartSym;
2838 Spans[Prev.CU].push_back(Span);
2845 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2846 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2848 // Build a list of CUs used.
2849 std::vector<CompileUnit *> CUs;
2850 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2851 CompileUnit *CU = it->first;
2855 // Sort the CU list (again, to ensure consistent output order).
2856 std::sort(CUs.begin(), CUs.end(), CUSort);
2858 // Emit an arange table for each CU we used.
2859 for (size_t CUIdx=0;CUIdx<CUs.size();CUIdx++) {
2860 CompileUnit *CU = CUs[CUIdx];
2861 std::vector<ArangeSpan> &List = Spans[CU];
2863 // Emit size of content not including length itself.
2864 unsigned ContentSize
2865 = sizeof(int16_t) // DWARF ARange version number
2866 + sizeof(int32_t) // Offset of CU in the .debug_info section
2867 + sizeof(int8_t) // Pointer Size (in bytes)
2868 + sizeof(int8_t); // Segment Size (in bytes)
2870 unsigned TupleSize = PtrSize * 2;
2872 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2873 unsigned Padding = 0;
2874 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2877 ContentSize += Padding;
2878 ContentSize += (List.size() + 1) * TupleSize;
2880 // For each compile unit, write the list of spans it covers.
2881 Asm->OutStreamer.AddComment("Length of ARange Set");
2882 Asm->EmitInt32(ContentSize);
2883 Asm->OutStreamer.AddComment("DWARF Arange version number");
2884 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2885 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2886 Asm->EmitSectionOffset(
2887 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2888 DwarfInfoSectionSym);
2889 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2890 Asm->EmitInt8(PtrSize);
2891 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2894 for (unsigned n = 0; n < Padding; n++)
2895 Asm->EmitInt8(0xff);
2897 for (unsigned n = 0; n < List.size(); n++) {
2898 const ArangeSpan &Span = List[n];
2899 Asm->EmitLabelReference(Span.Start, PtrSize);
2901 // Calculate the size as being from the span start to it's end.
2903 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2905 // For symbols without an end marker (e.g. common), we
2906 // write a single arange entry containing just that one symbol.
2907 uint64_t Size = SymSize[Span.Start];
2911 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2915 Asm->OutStreamer.AddComment("ARange terminator");
2916 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2917 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2921 // Emit visible names into a debug ranges section.
2922 void DwarfDebug::emitDebugRanges() {
2923 // Start the dwarf ranges section.
2925 .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2926 unsigned char Size = Asm->getDataLayout().getPointerSize();
2927 for (SmallVectorImpl<const MCSymbol *>::iterator
2928 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2931 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2933 Asm->OutStreamer.EmitIntValue(0, Size);
2937 // Emit visible names into a debug macinfo section.
2938 void DwarfDebug::emitDebugMacInfo() {
2939 if (const MCSection *LineInfo =
2940 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2941 // Start the dwarf macinfo section.
2942 Asm->OutStreamer.SwitchSection(LineInfo);
2946 // DWARF5 Experimental Separate Dwarf emitters.
2948 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2949 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2950 // DW_AT_ranges_base, DW_AT_addr_base.
2951 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2953 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2954 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2955 Asm, this, &SkeletonHolder);
2957 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2958 DICompileUnit(CU->getNode()).getSplitDebugFilename());
2960 // Relocate to the beginning of the addr_base section, else 0 for the
2961 // beginning of the one for this compile unit.
2962 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2963 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2964 DwarfAddrSectionSym);
2966 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2967 dwarf::DW_FORM_sec_offset, 0);
2969 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2970 // into an entity. We're using 0, or a NULL label for this.
2971 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2973 // DW_AT_stmt_list is a offset of line number information for this
2974 // compile unit in debug_line section.
2975 // FIXME: Should handle multiple compile units.
2976 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2977 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2978 DwarfLineSectionSym);
2980 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2982 if (!CompilationDir.empty())
2983 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2985 // Flags to let the linker know we have emitted new style pubnames.
2986 if (GenerateGnuPubSections) {
2987 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2988 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubnames, dwarf::DW_FORM_sec_offset,
2989 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
2991 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubnames, dwarf::DW_FORM_data4,
2992 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
2993 DwarfGnuPubNamesSectionSym);
2995 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2996 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubtypes, dwarf::DW_FORM_sec_offset,
2997 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
2999 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubtypes, dwarf::DW_FORM_data4,
3000 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
3001 DwarfGnuPubTypesSectionSym);
3004 // Flag if we've emitted any ranges and their location for the compile unit.
3005 if (DebugRangeSymbols.size()) {
3006 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
3007 NewCU->addLabel(Die, dwarf::DW_AT_GNU_ranges_base,
3008 dwarf::DW_FORM_sec_offset, DwarfDebugRangeSectionSym);
3010 NewCU->addUInt(Die, dwarf::DW_AT_GNU_ranges_base, dwarf::DW_FORM_data4,
3014 SkeletonHolder.addUnit(NewCU);
3015 SkeletonCUs.push_back(NewCU);
3020 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
3021 assert(useSplitDwarf() && "No split dwarf debug info?");
3022 emitAbbrevs(Section, &SkeletonAbbrevs);
3025 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3026 // compile units that would normally be in debug_info.
3027 void DwarfDebug::emitDebugInfoDWO() {
3028 assert(useSplitDwarf() && "No split dwarf debug info?");
3029 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
3030 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3031 DwarfAbbrevDWOSectionSym);
3034 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3035 // abbreviations for the .debug_info.dwo section.
3036 void DwarfDebug::emitDebugAbbrevDWO() {
3037 assert(useSplitDwarf() && "No split dwarf?");
3038 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
3042 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3043 // string section and is identical in format to traditional .debug_str
3045 void DwarfDebug::emitDebugStrDWO() {
3046 assert(useSplitDwarf() && "No split dwarf?");
3047 const MCSection *OffSec = Asm->getObjFileLowering()
3048 .getDwarfStrOffDWOSection();
3049 const MCSymbol *StrSym = DwarfStrSectionSym;
3050 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),