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 and older gdb compatibility
200 // for Darwin by default, pubnames by default for non-Darwin,
201 // and handle split dwarf.
202 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
204 if (DwarfAccelTables == Default)
205 HasDwarfAccelTables = IsDarwin;
207 HasDwarfAccelTables = DwarfAccelTables == Enable;
209 if (SplitDwarf == Default)
210 HasSplitDwarf = false;
212 HasSplitDwarf = SplitDwarf == Enable;
214 if (DwarfPubSections == Default)
215 HasDwarfPubSections = !IsDarwin;
217 HasDwarfPubSections = DwarfPubSections == Enable;
219 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
222 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
226 DwarfDebug::~DwarfDebug() {
229 // Switch to the specified MCSection and emit an assembler
230 // temporary label to it if SymbolStem is specified.
231 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
232 const char *SymbolStem = 0) {
233 Asm->OutStreamer.SwitchSection(Section);
234 if (!SymbolStem) return 0;
236 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
237 Asm->OutStreamer.EmitLabel(TmpSym);
241 MCSymbol *DwarfUnits::getStringPoolSym() {
242 return Asm->GetTempSymbol(StringPref);
245 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
246 std::pair<MCSymbol*, unsigned> &Entry =
247 StringPool.GetOrCreateValue(Str).getValue();
248 if (Entry.first) return Entry.first;
250 Entry.second = NextStringPoolNumber++;
251 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
254 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
255 std::pair<MCSymbol*, unsigned> &Entry =
256 StringPool.GetOrCreateValue(Str).getValue();
257 if (Entry.first) return Entry.second;
259 Entry.second = NextStringPoolNumber++;
260 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
264 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
265 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
268 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
269 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
270 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
272 ++NextAddrPoolNumber;
273 return P.first->second;
276 // Define a unique number for the abbreviation.
278 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
279 // Check the set for priors.
280 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
282 // If it's newly added.
283 if (InSet == &Abbrev) {
284 // Add to abbreviation list.
285 Abbreviations->push_back(&Abbrev);
287 // Assign the vector position + 1 as its number.
288 Abbrev.setNumber(Abbreviations->size());
290 // Assign existing abbreviation number.
291 Abbrev.setNumber(InSet->getNumber());
295 static bool isObjCClass(StringRef Name) {
296 return Name.startswith("+") || Name.startswith("-");
299 static bool hasObjCCategory(StringRef Name) {
300 if (!isObjCClass(Name)) return false;
302 return Name.find(") ") != StringRef::npos;
305 static void getObjCClassCategory(StringRef In, StringRef &Class,
306 StringRef &Category) {
307 if (!hasObjCCategory(In)) {
308 Class = In.slice(In.find('[') + 1, In.find(' '));
313 Class = In.slice(In.find('[') + 1, In.find('('));
314 Category = In.slice(In.find('[') + 1, In.find(' '));
318 static StringRef getObjCMethodName(StringRef In) {
319 return In.slice(In.find(' ') + 1, In.find(']'));
322 // Helper for sorting sections into a stable output order.
323 static bool SectionSort(const MCSection *A, const MCSection *B) {
324 std::string LA = (A ? A->getLabelBeginName() : "");
325 std::string LB = (B ? B->getLabelBeginName() : "");
329 // Add the various names to the Dwarf accelerator table names.
330 // TODO: Determine whether or not we should add names for programs
331 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
332 // is only slightly different than the lookup of non-standard ObjC names.
333 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
335 if (!SP.isDefinition()) return;
336 TheCU->addAccelName(SP.getName(), Die);
338 // If the linkage name is different than the name, go ahead and output
339 // that as well into the name table.
340 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
341 TheCU->addAccelName(SP.getLinkageName(), Die);
343 // If this is an Objective-C selector name add it to the ObjC accelerator
345 if (isObjCClass(SP.getName())) {
346 StringRef Class, Category;
347 getObjCClassCategory(SP.getName(), Class, Category);
348 TheCU->addAccelObjC(Class, Die);
350 TheCU->addAccelObjC(Category, Die);
351 // Also add the base method name to the name table.
352 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
356 /// isSubprogramContext - Return true if Context is either a subprogram
357 /// or another context nested inside a subprogram.
358 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
361 DIDescriptor D(Context);
362 if (D.isSubprogram())
365 return isSubprogramContext(resolve(DIType(Context).getContext()));
369 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
370 // and DW_AT_high_pc attributes. If there are global variables in this
371 // scope then create and insert DIEs for these variables.
372 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
373 const MDNode *SPNode) {
374 DIE *SPDie = SPCU->getDIE(SPNode);
376 assert(SPDie && "Unable to find subprogram DIE!");
377 DISubprogram SP(SPNode);
379 // If we're updating an abstract DIE, then we will be adding the children and
380 // object pointer later on. But what we don't want to do is process the
381 // concrete DIE twice.
382 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
383 // Pick up abstract subprogram DIE.
384 SPDie = new DIE(dwarf::DW_TAG_subprogram);
385 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
388 DISubprogram SPDecl = SP.getFunctionDeclaration();
389 if (!SPDecl.isSubprogram()) {
390 // There is not any need to generate specification DIE for a function
391 // defined at compile unit level. If a function is defined inside another
392 // function then gdb prefers the definition at top level and but does not
393 // expect specification DIE in parent function. So avoid creating
394 // specification DIE for a function defined inside a function.
395 DIScope SPContext = resolve(SP.getContext());
396 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
397 !SPContext.isFile() &&
398 !isSubprogramContext(SPContext)) {
399 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
402 DICompositeType SPTy = SP.getType();
403 DIArray Args = SPTy.getTypeArray();
404 uint16_t SPTag = SPTy.getTag();
405 if (SPTag == dwarf::DW_TAG_subroutine_type)
406 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
407 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
408 DIType ATy = DIType(Args.getElement(i));
409 SPCU->addType(Arg, ATy);
410 if (ATy.isArtificial())
411 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
412 if (ATy.isObjectPointer())
413 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, Arg);
414 SPDie->addChild(Arg);
416 DIE *SPDeclDie = SPDie;
417 SPDie = new DIE(dwarf::DW_TAG_subprogram);
418 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
424 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
425 Asm->GetTempSymbol("func_begin",
426 Asm->getFunctionNumber()));
427 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
428 Asm->GetTempSymbol("func_end",
429 Asm->getFunctionNumber()));
430 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
431 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
432 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
434 // Add name to the name table, we do this here because we're guaranteed
435 // to have concrete versions of our DW_TAG_subprogram nodes.
436 addSubprogramNames(SPCU, SP, SPDie);
441 /// Check whether we should create a DIE for the given Scope, return true
442 /// if we don't create a DIE (the corresponding DIE is null).
443 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
444 if (Scope->isAbstractScope())
447 // We don't create a DIE if there is no Range.
448 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
452 if (Ranges.size() > 1)
455 // We don't create a DIE if we have a single Range and the end label
457 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
458 MCSymbol *End = getLabelAfterInsn(RI->second);
462 // Construct new DW_TAG_lexical_block for this scope and attach
463 // DW_AT_low_pc/DW_AT_high_pc labels.
464 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
465 LexicalScope *Scope) {
466 if (isLexicalScopeDIENull(Scope))
469 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
470 if (Scope->isAbstractScope())
473 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
474 // If we have multiple ranges, emit them into the range section.
475 if (Ranges.size() > 1) {
476 // .debug_range section has not been laid out yet. Emit offset in
477 // .debug_range as a uint, size 4, for now. emitDIE will handle
478 // DW_AT_ranges appropriately.
479 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
480 DebugRangeSymbols.size()
481 * Asm->getDataLayout().getPointerSize());
482 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
483 RE = Ranges.end(); RI != RE; ++RI) {
484 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
485 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
488 // Terminate the range list.
489 DebugRangeSymbols.push_back(NULL);
490 DebugRangeSymbols.push_back(NULL);
494 // Construct the address range for this DIE.
495 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
496 MCSymbol *Start = getLabelBeforeInsn(RI->first);
497 MCSymbol *End = getLabelAfterInsn(RI->second);
498 assert(End && "End label should not be null!");
500 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
501 assert(End->isDefined() && "Invalid end label for an inlined scope!");
503 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
504 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
509 // This scope represents inlined body of a function. Construct DIE to
510 // represent this concrete inlined copy of the function.
511 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
512 LexicalScope *Scope) {
513 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
514 assert(Ranges.empty() == false &&
515 "LexicalScope does not have instruction markers!");
517 if (!Scope->getScopeNode())
519 DIScope DS(Scope->getScopeNode());
520 DISubprogram InlinedSP = getDISubprogram(DS);
521 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
523 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
527 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
528 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
530 if (Ranges.size() > 1) {
531 // .debug_range section has not been laid out yet. Emit offset in
532 // .debug_range as a uint, size 4, for now. emitDIE will handle
533 // DW_AT_ranges appropriately.
534 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
535 DebugRangeSymbols.size()
536 * Asm->getDataLayout().getPointerSize());
537 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
538 RE = Ranges.end(); RI != RE; ++RI) {
539 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
540 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
542 DebugRangeSymbols.push_back(NULL);
543 DebugRangeSymbols.push_back(NULL);
545 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
546 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
547 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
549 if (StartLabel == 0 || EndLabel == 0)
550 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
552 assert(StartLabel->isDefined() &&
553 "Invalid starting label for an inlined scope!");
554 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
556 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
557 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
560 InlinedSubprogramDIEs.insert(OriginDIE);
562 // Add the call site information to the DIE.
563 DILocation DL(Scope->getInlinedAt());
564 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
565 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
566 TheCU->getUniqueID()));
567 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
569 // Add name to the name table, we do this here because we're guaranteed
570 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
571 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
576 DIE *DwarfDebug::createScopeChildrenDIE(CompileUnit *TheCU, LexicalScope *Scope,
577 SmallVectorImpl<DIE*> &Children) {
578 DIE *ObjectPointer = NULL;
580 // Collect arguments for current function.
581 if (LScopes.isCurrentFunctionScope(Scope))
582 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
583 if (DbgVariable *ArgDV = CurrentFnArguments[i])
585 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
586 Children.push_back(Arg);
587 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
590 // Collect lexical scope children first.
591 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
592 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
594 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
595 Children.push_back(Variable);
596 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
598 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
599 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
600 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
601 Children.push_back(Nested);
602 return ObjectPointer;
605 // Construct a DIE for this scope.
606 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
607 if (!Scope || !Scope->getScopeNode())
610 DIScope DS(Scope->getScopeNode());
612 SmallVector<DIE *, 8> Children;
613 DIE *ObjectPointer = NULL;
614 bool ChildrenCreated = false;
616 // We try to create the scope DIE first, then the children DIEs. This will
617 // avoid creating un-used children then removing them later when we find out
618 // the scope DIE is null.
619 DIE *ScopeDIE = NULL;
620 if (Scope->getInlinedAt())
621 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
622 else if (DS.isSubprogram()) {
623 ProcessedSPNodes.insert(DS);
624 if (Scope->isAbstractScope()) {
625 ScopeDIE = TheCU->getDIE(DS);
626 // Note down abstract DIE.
628 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
631 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
634 // Early exit when we know the scope DIE is going to be null.
635 if (isLexicalScopeDIENull(Scope))
638 // We create children here when we know the scope DIE is not going to be
639 // null and the children will be added to the scope DIE.
640 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
641 ChildrenCreated = true;
643 // There is no need to emit empty lexical block DIE.
644 std::pair<ImportedEntityMap::const_iterator,
645 ImportedEntityMap::const_iterator> Range = std::equal_range(
646 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
647 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
649 if (Children.empty() && Range.first == Range.second)
651 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
652 assert(ScopeDIE && "Scope DIE should not be null.");
653 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
655 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
659 assert(Children.empty() &&
660 "We create children only when the scope DIE is not null.");
663 if (!ChildrenCreated)
664 // We create children when the scope DIE is not null.
665 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
668 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
669 E = Children.end(); I != E; ++I)
670 ScopeDIE->addChild(*I);
672 if (DS.isSubprogram() && ObjectPointer != NULL)
673 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
675 if (DS.isSubprogram())
676 TheCU->addPubTypes(DISubprogram(DS));
681 // Look up the source id with the given directory and source file names.
682 // If none currently exists, create a new id and insert it in the
683 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
685 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
686 StringRef DirName, unsigned CUID) {
687 // If we use .loc in assembly, we can't separate .file entries according to
688 // compile units. Thus all files will belong to the default compile unit.
690 // FIXME: add a better feature test than hasRawTextSupport. Even better,
691 // extend .file to support this.
692 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
695 // If FE did not provide a file name, then assume stdin.
696 if (FileName.empty())
697 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
699 // TODO: this might not belong here. See if we can factor this better.
700 if (DirName == CompilationDir)
703 // FileIDCUMap stores the current ID for the given compile unit.
704 unsigned SrcId = FileIDCUMap[CUID] + 1;
706 // We look up the CUID/file/dir by concatenating them with a zero byte.
707 SmallString<128> NamePair;
708 NamePair += utostr(CUID);
711 NamePair += '\0'; // Zero bytes are not allowed in paths.
712 NamePair += FileName;
714 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
715 if (Ent.getValue() != SrcId)
716 return Ent.getValue();
718 FileIDCUMap[CUID] = SrcId;
719 // Print out a .file directive to specify files for .loc directives.
720 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
725 // Create new CompileUnit for the given metadata node with tag
726 // DW_TAG_compile_unit.
727 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
728 DICompileUnit DIUnit(N);
729 StringRef FN = DIUnit.getFilename();
730 CompilationDir = DIUnit.getDirectory();
732 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
734 new CompileUnit(GlobalCUIndexCount++, Die, N, Asm, this, &InfoHolder);
736 FileIDCUMap[NewCU->getUniqueID()] = 0;
737 // Call this to emit a .file directive if it wasn't emitted for the source
738 // file this CU comes from yet.
739 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
741 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
742 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
743 DIUnit.getLanguage());
744 NewCU->addString(Die, dwarf::DW_AT_name, FN);
746 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
747 // into an entity. We're using 0 (or a NULL label) for this. For
748 // split dwarf it's in the skeleton CU so omit it here.
749 if (!useSplitDwarf())
750 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
752 // Define start line table label for each Compile Unit.
753 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
754 NewCU->getUniqueID());
755 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
756 NewCU->getUniqueID());
758 // Use a single line table if we are using .loc and generating assembly.
760 (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport()) ||
761 (NewCU->getUniqueID() == 0);
763 if (!useSplitDwarf()) {
764 // DW_AT_stmt_list is a offset of line number information for this
765 // compile unit in debug_line section. For split dwarf this is
766 // left in the skeleton CU and so not included.
767 // The line table entries are not always emitted in assembly, so it
768 // is not okay to use line_table_start here.
769 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
770 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
771 UseTheFirstCU ? Asm->GetTempSymbol("section_line")
772 : LineTableStartSym);
773 else if (UseTheFirstCU)
774 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
776 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
777 LineTableStartSym, DwarfLineSectionSym);
779 // If we're using split dwarf the compilation dir is going to be in the
780 // skeleton CU and so we don't need to duplicate it here.
781 if (!CompilationDir.empty())
782 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
784 // Flags to let the linker know we have emitted new style pubnames. Only
785 // emit it here if we don't have a skeleton CU for split dwarf.
786 if (GenerateGnuPubSections) {
787 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
788 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubnames,
789 dwarf::DW_FORM_sec_offset,
790 Asm->GetTempSymbol("gnu_pubnames",
791 NewCU->getUniqueID()));
793 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubnames, dwarf::DW_FORM_data4,
794 Asm->GetTempSymbol("gnu_pubnames",
795 NewCU->getUniqueID()),
796 DwarfGnuPubNamesSectionSym);
798 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
799 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubtypes,
800 dwarf::DW_FORM_sec_offset,
801 Asm->GetTempSymbol("gnu_pubtypes",
802 NewCU->getUniqueID()));
804 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubtypes, dwarf::DW_FORM_data4,
805 Asm->GetTempSymbol("gnu_pubtypes",
806 NewCU->getUniqueID()),
807 DwarfGnuPubTypesSectionSym);
811 if (DIUnit.isOptimized())
812 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
814 StringRef Flags = DIUnit.getFlags();
816 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
818 if (unsigned RVer = DIUnit.getRunTimeVersion())
819 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
820 dwarf::DW_FORM_data1, RVer);
825 InfoHolder.addUnit(NewCU);
827 CUMap.insert(std::make_pair(N, NewCU));
831 // Construct subprogram DIE.
832 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
834 CompileUnit *&CURef = SPMap[N];
840 if (!SP.isDefinition())
841 // This is a method declaration which will be handled while constructing
845 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
847 // Expose as a global name.
848 TheCU->addGlobalName(SP.getName(), SubprogramDie);
851 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
853 DIImportedEntity Module(N);
854 if (!Module.Verify())
856 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
857 constructImportedEntityDIE(TheCU, Module, D);
860 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
862 DIImportedEntity Module(N);
863 if (!Module.Verify())
865 return constructImportedEntityDIE(TheCU, Module, Context);
868 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
869 const DIImportedEntity &Module,
871 assert(Module.Verify() &&
872 "Use one of the MDNode * overloads to handle invalid metadata");
873 assert(Context && "Should always have a context for an imported_module");
874 DIE *IMDie = new DIE(Module.getTag());
875 TheCU->insertDIE(Module, IMDie);
877 DIDescriptor Entity = Module.getEntity();
878 if (Entity.isNameSpace())
879 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
880 else if (Entity.isSubprogram())
881 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
882 else if (Entity.isType())
883 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
885 EntityDie = TheCU->getDIE(Entity);
886 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
887 Module.getContext().getDirectory(),
888 TheCU->getUniqueID());
889 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
890 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
891 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
892 StringRef Name = Module.getName();
894 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
895 Context->addChild(IMDie);
898 // Emit all Dwarf sections that should come prior to the content. Create
899 // global DIEs and emit initial debug info sections. This is invoked by
900 // the target AsmPrinter.
901 void DwarfDebug::beginModule() {
902 if (DisableDebugInfoPrinting)
905 const Module *M = MMI->getModule();
907 // If module has named metadata anchors then use them, otherwise scan the
908 // module using debug info finder to collect debug info.
909 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
912 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
914 // Emit initial sections so we can reference labels later.
917 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
918 DICompileUnit CUNode(CU_Nodes->getOperand(i));
919 CompileUnit *CU = constructCompileUnit(CUNode);
920 DIArray ImportedEntities = CUNode.getImportedEntities();
921 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
922 ScopesWithImportedEntities.push_back(std::make_pair(
923 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
924 ImportedEntities.getElement(i)));
925 std::sort(ScopesWithImportedEntities.begin(),
926 ScopesWithImportedEntities.end(), less_first());
927 DIArray GVs = CUNode.getGlobalVariables();
928 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
929 CU->createGlobalVariableDIE(GVs.getElement(i));
930 DIArray SPs = CUNode.getSubprograms();
931 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
932 constructSubprogramDIE(CU, SPs.getElement(i));
933 DIArray EnumTypes = CUNode.getEnumTypes();
934 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
935 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
936 DIArray RetainedTypes = CUNode.getRetainedTypes();
937 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
938 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
939 // Emit imported_modules last so that the relevant context is already
941 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
942 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
945 // Tell MMI that we have debug info.
946 MMI->setDebugInfoAvailability(true);
948 // Prime section data.
949 SectionMap[Asm->getObjFileLowering().getTextSection()];
952 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
953 void DwarfDebug::computeInlinedDIEs() {
954 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
955 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
956 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
958 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
960 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
961 AE = AbstractSPDies.end(); AI != AE; ++AI) {
962 DIE *ISP = AI->second;
963 if (InlinedSubprogramDIEs.count(ISP))
965 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
969 // Collect info for variables that were optimized out.
970 void DwarfDebug::collectDeadVariables() {
971 const Module *M = MMI->getModule();
972 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
974 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
975 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
976 DICompileUnit TheCU(CU_Nodes->getOperand(i));
977 DIArray Subprograms = TheCU.getSubprograms();
978 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
979 DISubprogram SP(Subprograms.getElement(i));
980 if (ProcessedSPNodes.count(SP) != 0) continue;
981 if (!SP.isSubprogram()) continue;
982 if (!SP.isDefinition()) continue;
983 DIArray Variables = SP.getVariables();
984 if (Variables.getNumElements() == 0) continue;
986 LexicalScope *Scope =
987 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
988 DeadFnScopeMap[SP] = Scope;
990 // Construct subprogram DIE and add variables DIEs.
991 CompileUnit *SPCU = CUMap.lookup(TheCU);
992 assert(SPCU && "Unable to find Compile Unit!");
993 constructSubprogramDIE(SPCU, SP);
994 DIE *ScopeDIE = SPCU->getDIE(SP);
995 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
996 DIVariable DV(Variables.getElement(vi));
997 if (!DV.isVariable()) continue;
998 DbgVariable NewVar(DV, NULL, this);
999 if (DIE *VariableDIE =
1000 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
1001 ScopeDIE->addChild(VariableDIE);
1006 DeleteContainerSeconds(DeadFnScopeMap);
1009 // Type Signature [7.27] and ODR Hash code.
1011 /// \brief Grabs the string in whichever attribute is passed in and returns
1012 /// a reference to it. Returns "" if the attribute doesn't exist.
1013 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
1014 DIEValue *V = Die->findAttribute(Attr);
1016 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
1017 return S->getString();
1019 return StringRef("");
1022 /// Return true if the current DIE is contained within an anonymous namespace.
1023 static bool isContainedInAnonNamespace(DIE *Die) {
1024 DIE *Parent = Die->getParent();
1027 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
1028 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
1030 Parent = Parent->getParent();
1036 /// Test if the current CU language is C++ and that we have
1037 /// a named type that is not contained in an anonymous namespace.
1038 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
1039 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
1040 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
1041 !isContainedInAnonNamespace(Die);
1044 void DwarfDebug::finalizeModuleInfo() {
1045 // Collect info for variables that were optimized out.
1046 collectDeadVariables();
1048 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1049 computeInlinedDIEs();
1051 // Split out type units and conditionally add an ODR tag to the split
1053 // FIXME: Do type splitting.
1054 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
1055 DIE *Die = TypeUnits[i];
1057 // If we've requested ODR hashes and it's applicable for an ODR hash then
1058 // add the ODR signature now.
1059 // FIXME: This should be added onto the type unit, not the type, but this
1060 // works as an intermediate stage.
1061 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
1062 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
1063 dwarf::DW_FORM_data8,
1064 Hash.computeDIEODRSignature(Die));
1067 // Handle anything that needs to be done on a per-cu basis.
1068 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1070 CUI != CUE; ++CUI) {
1071 CompileUnit *TheCU = CUI->second;
1072 // Emit DW_AT_containing_type attribute to connect types with their
1073 // vtable holding type.
1074 TheCU->constructContainingTypeDIEs();
1076 // If we're splitting the dwarf out now that we've got the entire
1077 // CU then construct a skeleton CU based upon it.
1078 if (useSplitDwarf()) {
1080 if (GenerateCUHash) {
1082 ID = CUHash.computeCUSignature(TheCU->getCUDie());
1084 // This should be a unique identifier when we want to build .dwp files.
1085 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1086 dwarf::DW_FORM_data8, ID);
1087 // Now construct the skeleton CU associated.
1088 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1089 // This should be a unique identifier when we want to build .dwp files.
1090 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1091 dwarf::DW_FORM_data8, ID);
1095 // Compute DIE offsets and sizes.
1096 InfoHolder.computeSizeAndOffsets();
1097 if (useSplitDwarf())
1098 SkeletonHolder.computeSizeAndOffsets();
1101 void DwarfDebug::endSections() {
1102 // Filter labels by section.
1103 for (size_t n = 0; n < ArangeLabels.size(); n++) {
1104 const SymbolCU &SCU = ArangeLabels[n];
1105 if (SCU.Sym->isInSection()) {
1106 // Make a note of this symbol and it's section.
1107 const MCSection *Section = &SCU.Sym->getSection();
1108 if (!Section->getKind().isMetadata())
1109 SectionMap[Section].push_back(SCU);
1111 // Some symbols (e.g. common/bss on mach-o) can have no section but still
1112 // appear in the output. This sucks as we rely on sections to build
1113 // arange spans. We can do it without, but it's icky.
1114 SectionMap[NULL].push_back(SCU);
1118 // Build a list of sections used.
1119 std::vector<const MCSection *> Sections;
1120 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
1122 const MCSection *Section = it->first;
1123 Sections.push_back(Section);
1126 // Sort the sections into order.
1127 // This is only done to ensure consistent output order across different runs.
1128 std::sort(Sections.begin(), Sections.end(), SectionSort);
1130 // Add terminating symbols for each section.
1131 for (unsigned ID=0;ID<Sections.size();ID++) {
1132 const MCSection *Section = Sections[ID];
1133 MCSymbol *Sym = NULL;
1136 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1137 // if we know the section name up-front. For user-created sections, the resulting
1138 // label may not be valid to use as a label. (section names can use a greater
1139 // set of characters on some systems)
1140 Sym = Asm->GetTempSymbol("debug_end", ID);
1141 Asm->OutStreamer.SwitchSection(Section);
1142 Asm->OutStreamer.EmitLabel(Sym);
1145 // Insert a final terminator.
1146 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1150 // Emit all Dwarf sections that should come after the content.
1151 void DwarfDebug::endModule() {
1153 if (!FirstCU) return;
1155 // End any existing sections.
1156 // TODO: Does this need to happen?
1159 // Finalize the debug info for the module.
1160 finalizeModuleInfo();
1162 if (!useSplitDwarf()) {
1165 // Emit all the DIEs into a debug info section.
1168 // Corresponding abbreviations into a abbrev section.
1169 emitAbbreviations();
1171 // Emit info into a debug loc section.
1174 // Emit info into a debug aranges section.
1177 // Emit info into a debug ranges section.
1180 // Emit info into a debug macinfo section.
1184 // TODO: Fill this in for separated debug sections and separate
1185 // out information into new sections.
1187 if (useSplitDwarf())
1190 // Emit the debug info section and compile units.
1194 // Corresponding abbreviations into a abbrev section.
1195 emitAbbreviations();
1196 emitDebugAbbrevDWO();
1198 // Emit info into a debug loc section.
1201 // Emit info into a debug aranges section.
1204 // Emit info into a debug ranges section.
1207 // Emit info into a debug macinfo section.
1210 // Emit DWO addresses.
1211 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1215 // Emit info into the dwarf accelerator table sections.
1216 if (useDwarfAccelTables()) {
1219 emitAccelNamespaces();
1223 // Emit the pubnames and pubtypes sections if requested.
1224 if (HasDwarfPubSections) {
1225 emitDebugPubNames(GenerateGnuPubSections);
1226 emitDebugPubTypes(GenerateGnuPubSections);
1231 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1232 E = CUMap.end(); I != E; ++I)
1235 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1236 E = SkeletonCUs.end(); I != E; ++I)
1239 // Reset these for the next Module if we have one.
1243 // Find abstract variable, if any, associated with Var.
1244 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1245 DebugLoc ScopeLoc) {
1246 LLVMContext &Ctx = DV->getContext();
1247 // More then one inlined variable corresponds to one abstract variable.
1248 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1249 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1251 return AbsDbgVariable;
1253 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1257 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1258 addScopeVariable(Scope, AbsDbgVariable);
1259 AbstractVariables[Var] = AbsDbgVariable;
1260 return AbsDbgVariable;
1263 // If Var is a current function argument then add it to CurrentFnArguments list.
1264 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1265 DbgVariable *Var, LexicalScope *Scope) {
1266 if (!LScopes.isCurrentFunctionScope(Scope))
1268 DIVariable DV = Var->getVariable();
1269 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1271 unsigned ArgNo = DV.getArgNumber();
1275 size_t Size = CurrentFnArguments.size();
1277 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1278 // llvm::Function argument size is not good indicator of how many
1279 // arguments does the function have at source level.
1281 CurrentFnArguments.resize(ArgNo * 2);
1282 CurrentFnArguments[ArgNo - 1] = Var;
1286 // Collect variable information from side table maintained by MMI.
1288 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1289 SmallPtrSet<const MDNode *, 16> &Processed) {
1290 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1291 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1292 VE = VMap.end(); VI != VE; ++VI) {
1293 const MDNode *Var = VI->first;
1295 Processed.insert(Var);
1297 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1299 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1301 // If variable scope is not found then skip this variable.
1305 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1306 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1307 RegVar->setFrameIndex(VP.first);
1308 if (!addCurrentFnArgument(MF, RegVar, Scope))
1309 addScopeVariable(Scope, RegVar);
1311 AbsDbgVariable->setFrameIndex(VP.first);
1315 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1317 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1318 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1319 return MI->getNumOperands() == 3 &&
1320 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1321 (MI->getOperand(1).isImm() ||
1322 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1325 // Get .debug_loc entry for the instruction range starting at MI.
1326 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1327 const MCSymbol *FLabel,
1328 const MCSymbol *SLabel,
1329 const MachineInstr *MI) {
1330 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1332 assert(MI->getNumOperands() == 3);
1333 if (MI->getOperand(0).isReg()) {
1334 MachineLocation MLoc;
1335 // If the second operand is an immediate, this is a
1336 // register-indirect address.
1337 if (!MI->getOperand(1).isImm())
1338 MLoc.set(MI->getOperand(0).getReg());
1340 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1341 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1343 if (MI->getOperand(0).isImm())
1344 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1345 if (MI->getOperand(0).isFPImm())
1346 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1347 if (MI->getOperand(0).isCImm())
1348 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1350 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1353 // Find variables for each lexical scope.
1355 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1356 SmallPtrSet<const MDNode *, 16> &Processed) {
1358 // Grab the variable info that was squirreled away in the MMI side-table.
1359 collectVariableInfoFromMMITable(MF, Processed);
1361 for (SmallVectorImpl<const MDNode*>::const_iterator
1362 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1364 const MDNode *Var = *UVI;
1365 if (Processed.count(Var))
1368 // History contains relevant DBG_VALUE instructions for Var and instructions
1370 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1371 if (History.empty())
1373 const MachineInstr *MInsn = History.front();
1376 LexicalScope *Scope = NULL;
1377 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1378 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1379 Scope = LScopes.getCurrentFunctionScope();
1380 else if (MDNode *IA = DV.getInlinedAt())
1381 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1383 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1384 // If variable scope is not found then skip this variable.
1388 Processed.insert(DV);
1389 assert(MInsn->isDebugValue() && "History must begin with debug value");
1390 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1391 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1392 if (!addCurrentFnArgument(MF, RegVar, Scope))
1393 addScopeVariable(Scope, RegVar);
1395 AbsVar->setMInsn(MInsn);
1397 // Simplify ranges that are fully coalesced.
1398 if (History.size() <= 1 || (History.size() == 2 &&
1399 MInsn->isIdenticalTo(History.back()))) {
1400 RegVar->setMInsn(MInsn);
1404 // Handle multiple DBG_VALUE instructions describing one variable.
1405 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1407 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1408 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1409 const MachineInstr *Begin = *HI;
1410 assert(Begin->isDebugValue() && "Invalid History entry");
1412 // Check if DBG_VALUE is truncating a range.
1413 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1414 && !Begin->getOperand(0).getReg())
1417 // Compute the range for a register location.
1418 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1419 const MCSymbol *SLabel = 0;
1422 // If Begin is the last instruction in History then its value is valid
1423 // until the end of the function.
1424 SLabel = FunctionEndSym;
1426 const MachineInstr *End = HI[1];
1427 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1428 << "\t" << *Begin << "\t" << *End << "\n");
1429 if (End->isDebugValue())
1430 SLabel = getLabelBeforeInsn(End);
1432 // End is a normal instruction clobbering the range.
1433 SLabel = getLabelAfterInsn(End);
1434 assert(SLabel && "Forgot label after clobber instruction");
1439 // The value is valid until the next DBG_VALUE or clobber.
1440 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1443 DotDebugLocEntries.push_back(DotDebugLocEntry());
1446 // Collect info for variables that were optimized out.
1447 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1448 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1449 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1450 DIVariable DV(Variables.getElement(i));
1451 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1453 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1454 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1458 // Return Label preceding the instruction.
1459 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1460 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1461 assert(Label && "Didn't insert label before instruction");
1465 // Return Label immediately following the instruction.
1466 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1467 return LabelsAfterInsn.lookup(MI);
1470 // Process beginning of an instruction.
1471 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1472 // Check if source location changes, but ignore DBG_VALUE locations.
1473 if (!MI->isDebugValue()) {
1474 DebugLoc DL = MI->getDebugLoc();
1475 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1478 if (DL == PrologEndLoc) {
1479 Flags |= DWARF2_FLAG_PROLOGUE_END;
1480 PrologEndLoc = DebugLoc();
1482 if (PrologEndLoc.isUnknown())
1483 Flags |= DWARF2_FLAG_IS_STMT;
1485 if (!DL.isUnknown()) {
1486 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1487 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1489 recordSourceLine(0, 0, 0, 0);
1493 // Insert labels where requested.
1494 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1495 LabelsBeforeInsn.find(MI);
1498 if (I == LabelsBeforeInsn.end())
1501 // Label already assigned.
1506 PrevLabel = MMI->getContext().CreateTempSymbol();
1507 Asm->OutStreamer.EmitLabel(PrevLabel);
1509 I->second = PrevLabel;
1512 // Process end of an instruction.
1513 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1514 // Don't create a new label after DBG_VALUE instructions.
1515 // They don't generate code.
1516 if (!MI->isDebugValue())
1519 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1520 LabelsAfterInsn.find(MI);
1523 if (I == LabelsAfterInsn.end())
1526 // Label already assigned.
1530 // We need a label after this instruction.
1532 PrevLabel = MMI->getContext().CreateTempSymbol();
1533 Asm->OutStreamer.EmitLabel(PrevLabel);
1535 I->second = PrevLabel;
1538 // Each LexicalScope has first instruction and last instruction to mark
1539 // beginning and end of a scope respectively. Create an inverse map that list
1540 // scopes starts (and ends) with an instruction. One instruction may start (or
1541 // end) multiple scopes. Ignore scopes that are not reachable.
1542 void DwarfDebug::identifyScopeMarkers() {
1543 SmallVector<LexicalScope *, 4> WorkList;
1544 WorkList.push_back(LScopes.getCurrentFunctionScope());
1545 while (!WorkList.empty()) {
1546 LexicalScope *S = WorkList.pop_back_val();
1548 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1549 if (!Children.empty())
1550 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1551 SE = Children.end(); SI != SE; ++SI)
1552 WorkList.push_back(*SI);
1554 if (S->isAbstractScope())
1557 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1560 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1561 RE = Ranges.end(); RI != RE; ++RI) {
1562 assert(RI->first && "InsnRange does not have first instruction!");
1563 assert(RI->second && "InsnRange does not have second instruction!");
1564 requestLabelBeforeInsn(RI->first);
1565 requestLabelAfterInsn(RI->second);
1570 // Get MDNode for DebugLoc's scope.
1571 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1572 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1573 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1574 return DL.getScope(Ctx);
1577 // Walk up the scope chain of given debug loc and find line number info
1578 // for the function.
1579 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1580 const MDNode *Scope = getScopeNode(DL, Ctx);
1581 DISubprogram SP = getDISubprogram(Scope);
1582 if (SP.isSubprogram()) {
1583 // Check for number of operands since the compatibility is
1585 if (SP->getNumOperands() > 19)
1586 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1588 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1594 // Gather pre-function debug information. Assumes being called immediately
1595 // after the function entry point has been emitted.
1596 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1597 if (!MMI->hasDebugInfo()) return;
1598 LScopes.initialize(*MF);
1599 if (LScopes.empty()) return;
1600 identifyScopeMarkers();
1602 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1604 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1605 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1606 assert(TheCU && "Unable to find compile unit!");
1607 if (Asm->TM.hasMCUseLoc() && Asm->OutStreamer.hasRawTextSupport())
1608 // Use a single line table if we are using .loc and generating assembly.
1609 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1611 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1613 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1614 Asm->getFunctionNumber());
1615 // Assumes in correct section after the entry point.
1616 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1618 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1620 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1621 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1622 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1624 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1626 bool AtBlockEntry = true;
1627 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1629 const MachineInstr *MI = II;
1631 if (MI->isDebugValue()) {
1632 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1634 // Keep track of user variables.
1636 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1638 // Variable is in a register, we need to check for clobbers.
1639 if (isDbgValueInDefinedReg(MI))
1640 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1642 // Check the history of this variable.
1643 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1644 if (History.empty()) {
1645 UserVariables.push_back(Var);
1646 // The first mention of a function argument gets the FunctionBeginSym
1647 // label, so arguments are visible when breaking at function entry.
1649 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1650 DISubprogram(getDISubprogram(DV.getContext()))
1651 .describes(MF->getFunction()))
1652 LabelsBeforeInsn[MI] = FunctionBeginSym;
1654 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1655 const MachineInstr *Prev = History.back();
1656 if (Prev->isDebugValue()) {
1657 // Coalesce identical entries at the end of History.
1658 if (History.size() >= 2 &&
1659 Prev->isIdenticalTo(History[History.size() - 2])) {
1660 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1662 << "\t" << *History[History.size() - 2] << "\n");
1666 // Terminate old register assignments that don't reach MI;
1667 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1668 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1669 isDbgValueInDefinedReg(Prev)) {
1670 // Previous register assignment needs to terminate at the end of
1672 MachineBasicBlock::const_iterator LastMI =
1673 PrevMBB->getLastNonDebugInstr();
1674 if (LastMI == PrevMBB->end()) {
1675 // Drop DBG_VALUE for empty range.
1676 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1677 << "\t" << *Prev << "\n");
1679 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1680 // Terminate after LastMI.
1681 History.push_back(LastMI);
1685 History.push_back(MI);
1687 // Not a DBG_VALUE instruction.
1689 AtBlockEntry = false;
1691 // First known non-DBG_VALUE and non-frame setup location marks
1692 // the beginning of the function body.
1693 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1694 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1695 PrologEndLoc = MI->getDebugLoc();
1697 // Check if the instruction clobbers any registers with debug vars.
1698 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1699 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1700 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1702 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1703 AI.isValid(); ++AI) {
1705 const MDNode *Var = LiveUserVar[Reg];
1708 // Reg is now clobbered.
1709 LiveUserVar[Reg] = 0;
1711 // Was MD last defined by a DBG_VALUE referring to Reg?
1712 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1713 if (HistI == DbgValues.end())
1715 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1716 if (History.empty())
1718 const MachineInstr *Prev = History.back();
1719 // Sanity-check: Register assignments are terminated at the end of
1721 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1723 // Is the variable still in Reg?
1724 if (!isDbgValueInDefinedReg(Prev) ||
1725 Prev->getOperand(0).getReg() != Reg)
1727 // Var is clobbered. Make sure the next instruction gets a label.
1728 History.push_back(MI);
1735 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1737 SmallVectorImpl<const MachineInstr*> &History = I->second;
1738 if (History.empty())
1741 // Make sure the final register assignments are terminated.
1742 const MachineInstr *Prev = History.back();
1743 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1744 const MachineBasicBlock *PrevMBB = Prev->getParent();
1745 MachineBasicBlock::const_iterator LastMI =
1746 PrevMBB->getLastNonDebugInstr();
1747 if (LastMI == PrevMBB->end())
1748 // Drop DBG_VALUE for empty range.
1750 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1751 // Terminate after LastMI.
1752 History.push_back(LastMI);
1755 // Request labels for the full history.
1756 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1757 const MachineInstr *MI = History[i];
1758 if (MI->isDebugValue())
1759 requestLabelBeforeInsn(MI);
1761 requestLabelAfterInsn(MI);
1765 PrevInstLoc = DebugLoc();
1766 PrevLabel = FunctionBeginSym;
1768 // Record beginning of function.
1769 if (!PrologEndLoc.isUnknown()) {
1770 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1771 MF->getFunction()->getContext());
1772 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1773 FnStartDL.getScope(MF->getFunction()->getContext()),
1774 // We'd like to list the prologue as "not statements" but GDB behaves
1775 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1776 DWARF2_FLAG_IS_STMT);
1780 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1781 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1782 DIVariable DV = Var->getVariable();
1783 // Variables with positive arg numbers are parameters.
1784 if (unsigned ArgNum = DV.getArgNumber()) {
1785 // Keep all parameters in order at the start of the variable list to ensure
1786 // function types are correct (no out-of-order parameters)
1788 // This could be improved by only doing it for optimized builds (unoptimized
1789 // builds have the right order to begin with), searching from the back (this
1790 // would catch the unoptimized case quickly), or doing a binary search
1791 // rather than linear search.
1792 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1793 while (I != Vars.end()) {
1794 unsigned CurNum = (*I)->getVariable().getArgNumber();
1795 // A local (non-parameter) variable has been found, insert immediately
1799 // A later indexed parameter has been found, insert immediately before it.
1800 if (CurNum > ArgNum)
1804 Vars.insert(I, Var);
1808 Vars.push_back(Var);
1811 // Gather and emit post-function debug information.
1812 void DwarfDebug::endFunction(const MachineFunction *MF) {
1813 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1815 // Define end label for subprogram.
1816 FunctionEndSym = Asm->GetTempSymbol("func_end",
1817 Asm->getFunctionNumber());
1818 // Assumes in correct section after the entry point.
1819 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1820 // Set DwarfCompileUnitID in MCContext to default value.
1821 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1823 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1824 collectVariableInfo(MF, ProcessedVars);
1826 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1827 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1828 assert(TheCU && "Unable to find compile unit!");
1830 // Construct abstract scopes.
1831 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1832 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1833 LexicalScope *AScope = AList[i];
1834 DISubprogram SP(AScope->getScopeNode());
1835 if (SP.isSubprogram()) {
1836 // Collect info for variables that were optimized out.
1837 DIArray Variables = SP.getVariables();
1838 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1839 DIVariable DV(Variables.getElement(i));
1840 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1842 // Check that DbgVariable for DV wasn't created earlier, when
1843 // findAbstractVariable() was called for inlined instance of DV.
1844 LLVMContext &Ctx = DV->getContext();
1845 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1846 if (AbstractVariables.lookup(CleanDV))
1848 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1849 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1852 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1853 constructScopeDIE(TheCU, AScope);
1856 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1858 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1859 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1862 for (ScopeVariablesMap::iterator
1863 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1864 DeleteContainerPointers(I->second);
1865 ScopeVariables.clear();
1866 DeleteContainerPointers(CurrentFnArguments);
1867 UserVariables.clear();
1869 AbstractVariables.clear();
1870 LabelsBeforeInsn.clear();
1871 LabelsAfterInsn.clear();
1875 // Register a source line with debug info. Returns the unique label that was
1876 // emitted and which provides correspondence to the source line list.
1877 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1883 DIDescriptor Scope(S);
1885 if (Scope.isCompileUnit()) {
1886 DICompileUnit CU(S);
1887 Fn = CU.getFilename();
1888 Dir = CU.getDirectory();
1889 } else if (Scope.isFile()) {
1891 Fn = F.getFilename();
1892 Dir = F.getDirectory();
1893 } else if (Scope.isSubprogram()) {
1895 Fn = SP.getFilename();
1896 Dir = SP.getDirectory();
1897 } else if (Scope.isLexicalBlockFile()) {
1898 DILexicalBlockFile DBF(S);
1899 Fn = DBF.getFilename();
1900 Dir = DBF.getDirectory();
1901 } else if (Scope.isLexicalBlock()) {
1902 DILexicalBlock DB(S);
1903 Fn = DB.getFilename();
1904 Dir = DB.getDirectory();
1906 llvm_unreachable("Unexpected scope info");
1908 Src = getOrCreateSourceID(Fn, Dir,
1909 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1911 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1914 //===----------------------------------------------------------------------===//
1916 //===----------------------------------------------------------------------===//
1918 // Compute the size and offset of a DIE.
1920 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1921 // Get the children.
1922 const std::vector<DIE *> &Children = Die->getChildren();
1924 // Record the abbreviation.
1925 assignAbbrevNumber(Die->getAbbrev());
1927 // Get the abbreviation for this DIE.
1928 unsigned AbbrevNumber = Die->getAbbrevNumber();
1929 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1932 Die->setOffset(Offset);
1934 // Start the size with the size of abbreviation code.
1935 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1937 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1938 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1940 // Size the DIE attribute values.
1941 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1942 // Size attribute value.
1943 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1945 // Size the DIE children if any.
1946 if (!Children.empty()) {
1947 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1948 "Children flag not set");
1950 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1951 Offset = computeSizeAndOffset(Children[j], Offset);
1953 // End of children marker.
1954 Offset += sizeof(int8_t);
1957 Die->setSize(Offset - Die->getOffset());
1961 // Compute the size and offset of all the DIEs.
1962 void DwarfUnits::computeSizeAndOffsets() {
1963 // Offset from the beginning of debug info section.
1964 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1965 E = CUs.end(); I != E; ++I) {
1967 sizeof(int32_t) + // Length of Compilation Unit Info
1968 sizeof(int16_t) + // DWARF version number
1969 sizeof(int32_t) + // Offset Into Abbrev. Section
1970 sizeof(int8_t); // Pointer Size (in bytes)
1971 computeSizeAndOffset((*I)->getCUDie(), Offset);
1975 // Emit initial Dwarf sections with a label at the start of each one.
1976 void DwarfDebug::emitSectionLabels() {
1977 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1979 // Dwarf sections base addresses.
1980 DwarfInfoSectionSym =
1981 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1982 DwarfAbbrevSectionSym =
1983 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1984 if (useSplitDwarf())
1985 DwarfAbbrevDWOSectionSym =
1986 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1987 "section_abbrev_dwo");
1988 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1990 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1991 emitSectionSym(Asm, MacroInfo);
1993 DwarfLineSectionSym =
1994 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1995 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1996 if (GenerateGnuPubSections) {
1997 DwarfGnuPubNamesSectionSym =
1998 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1999 DwarfGnuPubTypesSectionSym =
2000 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
2001 } else if (HasDwarfPubSections) {
2002 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
2003 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
2006 DwarfStrSectionSym =
2007 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
2008 if (useSplitDwarf()) {
2009 DwarfStrDWOSectionSym =
2010 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
2011 DwarfAddrSectionSym =
2012 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
2014 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
2017 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
2018 "section_debug_loc");
2020 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
2021 emitSectionSym(Asm, TLOF.getDataSection());
2024 // Recursively emits a debug information entry.
2025 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
2026 // Get the abbreviation for this DIE.
2027 unsigned AbbrevNumber = Die->getAbbrevNumber();
2028 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
2030 // Emit the code (index) for the abbreviation.
2031 if (Asm->isVerbose())
2032 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
2033 Twine::utohexstr(Die->getOffset()) + ":0x" +
2034 Twine::utohexstr(Die->getSize()) + " " +
2035 dwarf::TagString(Abbrev->getTag()));
2036 Asm->EmitULEB128(AbbrevNumber);
2038 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
2039 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
2041 // Emit the DIE attribute values.
2042 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
2043 unsigned Attr = AbbrevData[i].getAttribute();
2044 unsigned Form = AbbrevData[i].getForm();
2045 assert(Form && "Too many attributes for DIE (check abbreviation)");
2047 if (Asm->isVerbose())
2048 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
2051 case dwarf::DW_AT_abstract_origin: {
2052 DIEEntry *E = cast<DIEEntry>(Values[i]);
2053 DIE *Origin = E->getEntry();
2054 unsigned Addr = Origin->getOffset();
2055 Asm->EmitInt32(Addr);
2058 case dwarf::DW_AT_ranges: {
2059 // DW_AT_range Value encodes offset in debug_range section.
2060 DIEInteger *V = cast<DIEInteger>(Values[i]);
2062 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
2063 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
2067 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
2069 DwarfDebugRangeSectionSym,
2074 case dwarf::DW_AT_location: {
2075 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2076 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2077 Asm->EmitLabelReference(L->getValue(), 4);
2079 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2081 Values[i]->EmitValue(Asm, Form);
2085 case dwarf::DW_AT_accessibility: {
2086 if (Asm->isVerbose()) {
2087 DIEInteger *V = cast<DIEInteger>(Values[i]);
2088 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2090 Values[i]->EmitValue(Asm, Form);
2094 // Emit an attribute using the defined form.
2095 Values[i]->EmitValue(Asm, Form);
2100 // Emit the DIE children if any.
2101 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2102 const std::vector<DIE *> &Children = Die->getChildren();
2104 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2105 emitDIE(Children[j], Abbrevs);
2107 if (Asm->isVerbose())
2108 Asm->OutStreamer.AddComment("End Of Children Mark");
2113 // Emit the various dwarf units to the unit section USection with
2114 // the abbreviations going into ASection.
2115 void DwarfUnits::emitUnits(DwarfDebug *DD,
2116 const MCSection *USection,
2117 const MCSection *ASection,
2118 const MCSymbol *ASectionSym) {
2119 Asm->OutStreamer.SwitchSection(USection);
2120 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2121 E = CUs.end(); I != E; ++I) {
2122 CompileUnit *TheCU = *I;
2123 DIE *Die = TheCU->getCUDie();
2125 // Emit the compile units header.
2127 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2128 TheCU->getUniqueID()));
2130 // Emit size of content not including length itself
2131 unsigned ContentSize = Die->getSize() +
2132 sizeof(int16_t) + // DWARF version number
2133 sizeof(int32_t) + // Offset Into Abbrev. Section
2134 sizeof(int8_t); // Pointer Size (in bytes)
2136 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2137 Asm->EmitInt32(ContentSize);
2138 Asm->OutStreamer.AddComment("DWARF version number");
2139 Asm->EmitInt16(DD->getDwarfVersion());
2140 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2141 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2143 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2144 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2146 DD->emitDIE(Die, Abbreviations);
2147 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2148 TheCU->getUniqueID()));
2152 // Emit the debug info section.
2153 void DwarfDebug::emitDebugInfo() {
2154 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2156 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2157 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2158 DwarfAbbrevSectionSym);
2161 // Emit the abbreviation section.
2162 void DwarfDebug::emitAbbreviations() {
2163 if (!useSplitDwarf())
2164 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2167 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2170 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2171 std::vector<DIEAbbrev *> *Abbrevs) {
2172 // Check to see if it is worth the effort.
2173 if (!Abbrevs->empty()) {
2174 // Start the debug abbrev section.
2175 Asm->OutStreamer.SwitchSection(Section);
2177 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2178 Asm->OutStreamer.EmitLabel(Begin);
2180 // For each abbrevation.
2181 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2182 // Get abbreviation data
2183 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2185 // Emit the abbrevations code (base 1 index.)
2186 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2188 // Emit the abbreviations data.
2192 // Mark end of abbreviations.
2193 Asm->EmitULEB128(0, "EOM(3)");
2195 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2196 Asm->OutStreamer.EmitLabel(End);
2200 // Emit the last address of the section and the end of the line matrix.
2201 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2202 // Define last address of section.
2203 Asm->OutStreamer.AddComment("Extended Op");
2206 Asm->OutStreamer.AddComment("Op size");
2207 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2208 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2209 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2211 Asm->OutStreamer.AddComment("Section end label");
2213 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2214 Asm->getDataLayout().getPointerSize());
2216 // Mark end of matrix.
2217 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2223 // Emit visible names into a hashed accelerator table section.
2224 void DwarfDebug::emitAccelNames() {
2225 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2226 dwarf::DW_FORM_data4));
2227 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2228 E = CUMap.end(); I != E; ++I) {
2229 CompileUnit *TheCU = I->second;
2230 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2231 for (StringMap<std::vector<DIE*> >::const_iterator
2232 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2233 StringRef Name = GI->getKey();
2234 const std::vector<DIE *> &Entities = GI->second;
2235 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2236 DE = Entities.end(); DI != DE; ++DI)
2237 AT.AddName(Name, (*DI));
2241 AT.FinalizeTable(Asm, "Names");
2242 Asm->OutStreamer.SwitchSection(
2243 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2244 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2245 Asm->OutStreamer.EmitLabel(SectionBegin);
2247 // Emit the full data.
2248 AT.Emit(Asm, SectionBegin, &InfoHolder);
2251 // Emit objective C classes and categories into a hashed accelerator table
2253 void DwarfDebug::emitAccelObjC() {
2254 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2255 dwarf::DW_FORM_data4));
2256 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2257 E = CUMap.end(); I != E; ++I) {
2258 CompileUnit *TheCU = I->second;
2259 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2260 for (StringMap<std::vector<DIE*> >::const_iterator
2261 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2262 StringRef Name = GI->getKey();
2263 const std::vector<DIE *> &Entities = GI->second;
2264 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2265 DE = Entities.end(); DI != DE; ++DI)
2266 AT.AddName(Name, (*DI));
2270 AT.FinalizeTable(Asm, "ObjC");
2271 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2272 .getDwarfAccelObjCSection());
2273 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2274 Asm->OutStreamer.EmitLabel(SectionBegin);
2276 // Emit the full data.
2277 AT.Emit(Asm, SectionBegin, &InfoHolder);
2280 // Emit namespace dies into a hashed accelerator table.
2281 void DwarfDebug::emitAccelNamespaces() {
2282 DwarfAccelTable AT(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2283 dwarf::DW_FORM_data4));
2284 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2285 E = CUMap.end(); I != E; ++I) {
2286 CompileUnit *TheCU = I->second;
2287 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2288 for (StringMap<std::vector<DIE*> >::const_iterator
2289 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2290 StringRef Name = GI->getKey();
2291 const std::vector<DIE *> &Entities = GI->second;
2292 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2293 DE = Entities.end(); DI != DE; ++DI)
2294 AT.AddName(Name, (*DI));
2298 AT.FinalizeTable(Asm, "namespac");
2299 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2300 .getDwarfAccelNamespaceSection());
2301 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2302 Asm->OutStreamer.EmitLabel(SectionBegin);
2304 // Emit the full data.
2305 AT.Emit(Asm, SectionBegin, &InfoHolder);
2308 // Emit type dies into a hashed accelerator table.
2309 void DwarfDebug::emitAccelTypes() {
2310 std::vector<DwarfAccelTable::Atom> Atoms;
2311 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
2312 dwarf::DW_FORM_data4));
2313 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag,
2314 dwarf::DW_FORM_data2));
2315 Atoms.push_back(DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags,
2316 dwarf::DW_FORM_data1));
2317 DwarfAccelTable AT(Atoms);
2318 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2319 E = CUMap.end(); I != E; ++I) {
2320 CompileUnit *TheCU = I->second;
2321 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2322 = TheCU->getAccelTypes();
2323 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2324 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2325 StringRef Name = GI->getKey();
2326 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2327 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2328 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2329 AT.AddName(Name, (*DI).first, (*DI).second);
2333 AT.FinalizeTable(Asm, "types");
2334 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2335 .getDwarfAccelTypesSection());
2336 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2337 Asm->OutStreamer.EmitLabel(SectionBegin);
2339 // Emit the full data.
2340 AT.Emit(Asm, SectionBegin, &InfoHolder);
2343 // Public name handling.
2344 // The format for the various pubnames:
2346 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2347 // for the DIE that is named.
2349 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2350 // into the CU and the index value is computed according to the type of value
2351 // for the DIE that is named.
2353 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2354 // it's the offset within the debug_info/debug_types dwo section, however, the
2355 // reference in the pubname header doesn't change.
2357 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2358 static dwarf::PubIndexEntryDescriptor computeIndexValue(CompileUnit *CU,
2360 dwarf::GDBIndexEntryLinkage Linkage =
2361 Die->findAttribute(dwarf::DW_AT_external) ? dwarf::GIEL_EXTERNAL
2362 : dwarf::GIEL_STATIC;
2364 switch (Die->getTag()) {
2365 case dwarf::DW_TAG_class_type:
2366 case dwarf::DW_TAG_structure_type:
2367 case dwarf::DW_TAG_union_type:
2368 case dwarf::DW_TAG_enumeration_type:
2369 return dwarf::PubIndexEntryDescriptor(
2370 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2371 ? dwarf::GIEL_STATIC
2372 : dwarf::GIEL_EXTERNAL);
2373 case dwarf::DW_TAG_typedef:
2374 case dwarf::DW_TAG_base_type:
2375 case dwarf::DW_TAG_subrange_type:
2376 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2377 case dwarf::DW_TAG_namespace:
2378 return dwarf::GIEK_TYPE;
2379 case dwarf::DW_TAG_subprogram:
2380 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2381 case dwarf::DW_TAG_constant:
2382 case dwarf::DW_TAG_variable:
2383 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2384 case dwarf::DW_TAG_enumerator:
2385 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2386 dwarf::GIEL_STATIC);
2388 return dwarf::GIEK_NONE;
2392 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2394 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2395 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2396 const MCSection *PSec =
2397 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2398 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2400 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2401 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2402 CompileUnit *TheCU = I->second;
2403 unsigned ID = TheCU->getUniqueID();
2405 // Start the dwarf pubnames section.
2406 Asm->OutStreamer.SwitchSection(PSec);
2408 // Emit a label so we can reference the beginning of this pubname section.
2410 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubnames",
2411 TheCU->getUniqueID()));
2414 Asm->OutStreamer.AddComment("Length of Public Names Info");
2415 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2416 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2418 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2420 Asm->OutStreamer.AddComment("DWARF Version");
2421 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2423 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2424 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2425 DwarfInfoSectionSym);
2427 Asm->OutStreamer.AddComment("Compilation Unit Length");
2428 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2429 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2432 // Emit the pubnames for this compilation unit.
2433 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2434 for (StringMap<DIE*>::const_iterator
2435 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2436 const char *Name = GI->getKeyData();
2437 DIE *Entity = GI->second;
2439 Asm->OutStreamer.AddComment("DIE offset");
2440 Asm->EmitInt32(Entity->getOffset());
2443 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2444 Asm->OutStreamer.AddComment(
2445 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2446 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2447 Asm->EmitInt8(Desc.toBits());
2450 if (Asm->isVerbose())
2451 Asm->OutStreamer.AddComment("External Name");
2452 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2455 Asm->OutStreamer.AddComment("End Mark");
2457 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2461 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2462 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2463 const MCSection *PSec =
2464 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2465 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2467 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2470 CompileUnit *TheCU = I->second;
2471 // Start the dwarf pubtypes section.
2472 Asm->OutStreamer.SwitchSection(PSec);
2474 // Emit a label so we can reference the beginning of this pubtype section.
2476 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("gnu_pubtypes",
2477 TheCU->getUniqueID()));
2480 Asm->OutStreamer.AddComment("Length of Public Types Info");
2481 Asm->EmitLabelDifference(
2482 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2483 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2485 Asm->OutStreamer.EmitLabel(
2486 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()));
2488 if (Asm->isVerbose())
2489 Asm->OutStreamer.AddComment("DWARF Version");
2490 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2492 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2493 Asm->EmitSectionOffset(
2494 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()),
2495 DwarfInfoSectionSym);
2497 Asm->OutStreamer.AddComment("Compilation Unit Length");
2498 Asm->EmitLabelDifference(
2499 Asm->GetTempSymbol(ISec->getLabelEndName(), TheCU->getUniqueID()),
2500 Asm->GetTempSymbol(ISec->getLabelBeginName(), TheCU->getUniqueID()), 4);
2502 // Emit the pubtypes.
2503 const StringMap<DIE *> &Globals = TheCU->getGlobalTypes();
2504 for (StringMap<DIE *>::const_iterator GI = Globals.begin(),
2507 const char *Name = GI->getKeyData();
2508 DIE *Entity = GI->second;
2510 if (Asm->isVerbose())
2511 Asm->OutStreamer.AddComment("DIE offset");
2512 Asm->EmitInt32(Entity->getOffset());
2515 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheCU, Entity);
2516 Asm->OutStreamer.AddComment(
2517 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2518 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2519 Asm->EmitInt8(Desc.toBits());
2522 if (Asm->isVerbose())
2523 Asm->OutStreamer.AddComment("External Name");
2525 // Emit the name with a terminating null byte.
2526 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength() + 1));
2529 Asm->OutStreamer.AddComment("End Mark");
2531 Asm->OutStreamer.EmitLabel(
2532 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()));
2536 // Emit strings into a string section.
2537 void DwarfUnits::emitStrings(const MCSection *StrSection,
2538 const MCSection *OffsetSection = NULL,
2539 const MCSymbol *StrSecSym = NULL) {
2541 if (StringPool.empty()) return;
2543 // Start the dwarf str section.
2544 Asm->OutStreamer.SwitchSection(StrSection);
2546 // Get all of the string pool entries and put them in an array by their ID so
2547 // we can sort them.
2548 SmallVector<std::pair<unsigned,
2549 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2551 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2552 I = StringPool.begin(), E = StringPool.end();
2554 Entries.push_back(std::make_pair(I->second.second, &*I));
2556 array_pod_sort(Entries.begin(), Entries.end());
2558 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2559 // Emit a label for reference from debug information entries.
2560 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2562 // Emit the string itself with a terminating null byte.
2563 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2564 Entries[i].second->getKeyLength()+1));
2567 // If we've got an offset section go ahead and emit that now as well.
2568 if (OffsetSection) {
2569 Asm->OutStreamer.SwitchSection(OffsetSection);
2570 unsigned offset = 0;
2571 unsigned size = 4; // FIXME: DWARF64 is 8.
2572 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2573 Asm->OutStreamer.EmitIntValue(offset, size);
2574 offset += Entries[i].second->getKeyLength() + 1;
2579 // Emit strings into a string section.
2580 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2582 if (AddressPool.empty()) return;
2584 // Start the dwarf addr section.
2585 Asm->OutStreamer.SwitchSection(AddrSection);
2587 // Order the address pool entries by ID
2588 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2590 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2591 E = AddressPool.end();
2593 Entries[I->second] = I->first;
2595 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2596 // Emit an expression for reference from debug information entries.
2597 if (const MCExpr *Expr = Entries[i])
2598 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2600 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2605 // Emit visible names into a debug str section.
2606 void DwarfDebug::emitDebugStr() {
2607 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2608 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2611 // Emit locations into the debug loc section.
2612 void DwarfDebug::emitDebugLoc() {
2613 if (DotDebugLocEntries.empty())
2616 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2617 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2619 DotDebugLocEntry &Entry = *I;
2620 if (I + 1 != DotDebugLocEntries.end())
2624 // Start the dwarf loc section.
2625 Asm->OutStreamer.SwitchSection(
2626 Asm->getObjFileLowering().getDwarfLocSection());
2627 unsigned char Size = Asm->getDataLayout().getPointerSize();
2628 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2630 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2631 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2632 I != E; ++I, ++index) {
2633 DotDebugLocEntry &Entry = *I;
2634 if (Entry.isMerged()) continue;
2635 if (Entry.isEmpty()) {
2636 Asm->OutStreamer.EmitIntValue(0, Size);
2637 Asm->OutStreamer.EmitIntValue(0, Size);
2638 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2640 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2641 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2642 DIVariable DV(Entry.getVariable());
2643 Asm->OutStreamer.AddComment("Loc expr size");
2644 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2645 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2646 Asm->EmitLabelDifference(end, begin, 2);
2647 Asm->OutStreamer.EmitLabel(begin);
2648 if (Entry.isInt()) {
2649 DIBasicType BTy(DV.getType());
2651 (BTy.getEncoding() == dwarf::DW_ATE_signed
2652 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2653 Asm->OutStreamer.AddComment("DW_OP_consts");
2654 Asm->EmitInt8(dwarf::DW_OP_consts);
2655 Asm->EmitSLEB128(Entry.getInt());
2657 Asm->OutStreamer.AddComment("DW_OP_constu");
2658 Asm->EmitInt8(dwarf::DW_OP_constu);
2659 Asm->EmitULEB128(Entry.getInt());
2661 } else if (Entry.isLocation()) {
2662 MachineLocation Loc = Entry.getLoc();
2663 if (!DV.hasComplexAddress())
2665 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2667 // Complex address entry.
2668 unsigned N = DV.getNumAddrElements();
2670 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2671 if (Loc.getOffset()) {
2673 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2674 Asm->OutStreamer.AddComment("DW_OP_deref");
2675 Asm->EmitInt8(dwarf::DW_OP_deref);
2676 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2677 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2678 Asm->EmitSLEB128(DV.getAddrElement(1));
2680 // If first address element is OpPlus then emit
2681 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2682 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2683 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2687 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2690 // Emit remaining complex address elements.
2691 for (; i < N; ++i) {
2692 uint64_t Element = DV.getAddrElement(i);
2693 if (Element == DIBuilder::OpPlus) {
2694 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2695 Asm->EmitULEB128(DV.getAddrElement(++i));
2696 } else if (Element == DIBuilder::OpDeref) {
2698 Asm->EmitInt8(dwarf::DW_OP_deref);
2700 llvm_unreachable("unknown Opcode found in complex address");
2704 // else ... ignore constant fp. There is not any good way to
2705 // to represent them here in dwarf.
2706 Asm->OutStreamer.EmitLabel(end);
2711 struct SymbolCUSorter {
2712 SymbolCUSorter(const MCStreamer &s) : Streamer(s) {}
2713 const MCStreamer &Streamer;
2715 bool operator() (const SymbolCU &A, const SymbolCU &B) {
2716 unsigned IA = A.Sym ? Streamer.GetSymbolOrder(A.Sym) : 0;
2717 unsigned IB = B.Sym ? Streamer.GetSymbolOrder(B.Sym) : 0;
2719 // Symbols with no order assigned should be placed at the end.
2720 // (e.g. section end labels)
2722 IA = (unsigned)(-1);
2724 IB = (unsigned)(-1);
2729 static bool CUSort(const CompileUnit *A, const CompileUnit *B) {
2730 return (A->getUniqueID() < B->getUniqueID());
2734 const MCSymbol *Start, *End;
2737 // Emit a debug aranges section, containing a CU lookup for any
2738 // address we can tie back to a CU.
2739 void DwarfDebug::emitDebugARanges() {
2740 // Start the dwarf aranges section.
2742 .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2744 typedef DenseMap<CompileUnit *, std::vector<ArangeSpan> > SpansType;
2748 // Build a list of sections used.
2749 std::vector<const MCSection *> Sections;
2750 for (SectionMapType::iterator it = SectionMap.begin(); it != SectionMap.end();
2752 const MCSection *Section = it->first;
2753 Sections.push_back(Section);
2756 // Sort the sections into order.
2757 // This is only done to ensure consistent output order across different runs.
2758 std::sort(Sections.begin(), Sections.end(), SectionSort);
2760 // Build a set of address spans, sorted by CU.
2761 for (size_t SecIdx=0;SecIdx<Sections.size();SecIdx++) {
2762 const MCSection *Section = Sections[SecIdx];
2763 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2764 if (List.size() < 2)
2767 // Sort the symbols by offset within the section.
2768 SymbolCUSorter sorter(Asm->OutStreamer);
2769 std::sort(List.begin(), List.end(), sorter);
2771 // If we have no section (e.g. common), just write out
2772 // individual spans for each symbol.
2773 if (Section == NULL) {
2774 for (size_t n = 0; n < List.size(); n++) {
2775 const SymbolCU &Cur = List[n];
2778 Span.Start = Cur.Sym;
2781 Spans[Cur.CU].push_back(Span);
2784 // Build spans between each label.
2785 const MCSymbol *StartSym = List[0].Sym;
2786 for (size_t n = 1; n < List.size(); n++) {
2787 const SymbolCU &Prev = List[n - 1];
2788 const SymbolCU &Cur = List[n];
2790 // Try and build the longest span we can within the same CU.
2791 if (Cur.CU != Prev.CU) {
2793 Span.Start = StartSym;
2795 Spans[Prev.CU].push_back(Span);
2802 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2803 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2805 // Build a list of CUs used.
2806 std::vector<CompileUnit *> CUs;
2807 for (SpansType::iterator it = Spans.begin(); it != Spans.end(); it++) {
2808 CompileUnit *CU = it->first;
2812 // Sort the CU list (again, to ensure consistent output order).
2813 std::sort(CUs.begin(), CUs.end(), CUSort);
2815 // Emit an arange table for each CU we used.
2816 for (size_t CUIdx=0;CUIdx<CUs.size();CUIdx++) {
2817 CompileUnit *CU = CUs[CUIdx];
2818 std::vector<ArangeSpan> &List = Spans[CU];
2820 // Emit size of content not including length itself.
2821 unsigned ContentSize
2822 = sizeof(int16_t) // DWARF ARange version number
2823 + sizeof(int32_t) // Offset of CU in the .debug_info section
2824 + sizeof(int8_t) // Pointer Size (in bytes)
2825 + sizeof(int8_t); // Segment Size (in bytes)
2827 unsigned TupleSize = PtrSize * 2;
2829 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2830 unsigned Padding = 0;
2831 while (((sizeof(int32_t) + ContentSize + Padding) % TupleSize) != 0)
2834 ContentSize += Padding;
2835 ContentSize += (List.size() + 1) * TupleSize;
2837 // For each compile unit, write the list of spans it covers.
2838 Asm->OutStreamer.AddComment("Length of ARange Set");
2839 Asm->EmitInt32(ContentSize);
2840 Asm->OutStreamer.AddComment("DWARF Arange version number");
2841 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2842 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2843 Asm->EmitSectionOffset(
2844 Asm->GetTempSymbol(ISec->getLabelBeginName(), CU->getUniqueID()),
2845 DwarfInfoSectionSym);
2846 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2847 Asm->EmitInt8(PtrSize);
2848 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2851 for (unsigned n = 0; n < Padding; n++)
2852 Asm->EmitInt8(0xff);
2854 for (unsigned n = 0; n < List.size(); n++) {
2855 const ArangeSpan &Span = List[n];
2856 Asm->EmitLabelReference(Span.Start, PtrSize);
2858 // Calculate the size as being from the span start to it's end.
2860 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2862 // For symbols without an end marker (e.g. common), we
2863 // write a single arange entry containing just that one symbol.
2864 uint64_t Size = SymSize[Span.Start];
2868 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2872 Asm->OutStreamer.AddComment("ARange terminator");
2873 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2874 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2878 // Emit visible names into a debug ranges section.
2879 void DwarfDebug::emitDebugRanges() {
2880 // Start the dwarf ranges section.
2882 .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2883 unsigned char Size = Asm->getDataLayout().getPointerSize();
2884 for (SmallVectorImpl<const MCSymbol *>::iterator
2885 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2888 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2890 Asm->OutStreamer.EmitIntValue(0, Size);
2894 // Emit visible names into a debug macinfo section.
2895 void DwarfDebug::emitDebugMacInfo() {
2896 if (const MCSection *LineInfo =
2897 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2898 // Start the dwarf macinfo section.
2899 Asm->OutStreamer.SwitchSection(LineInfo);
2903 // DWARF5 Experimental Separate Dwarf emitters.
2905 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2906 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2907 // DW_AT_ranges_base, DW_AT_addr_base.
2908 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2910 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2911 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2912 Asm, this, &SkeletonHolder);
2914 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2915 DICompileUnit(CU->getNode()).getSplitDebugFilename());
2917 // Relocate to the beginning of the addr_base section, else 0 for the
2918 // beginning of the one for this compile unit.
2919 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2920 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2921 DwarfAddrSectionSym);
2923 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2924 dwarf::DW_FORM_sec_offset, 0);
2926 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2927 // into an entity. We're using 0, or a NULL label for this.
2928 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2930 // DW_AT_stmt_list is a offset of line number information for this
2931 // compile unit in debug_line section.
2932 // FIXME: Should handle multiple compile units.
2933 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2934 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2935 DwarfLineSectionSym);
2937 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2939 if (!CompilationDir.empty())
2940 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2942 // Flags to let the linker know we have emitted new style pubnames.
2943 if (GenerateGnuPubSections) {
2944 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2945 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubnames, dwarf::DW_FORM_sec_offset,
2946 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()));
2948 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubnames, dwarf::DW_FORM_data4,
2949 Asm->GetTempSymbol("gnu_pubnames", NewCU->getUniqueID()),
2950 DwarfGnuPubNamesSectionSym);
2952 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2953 NewCU->addLabel(Die, dwarf::DW_AT_GNU_pubtypes, dwarf::DW_FORM_sec_offset,
2954 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()));
2956 NewCU->addDelta(Die, dwarf::DW_AT_GNU_pubtypes, dwarf::DW_FORM_data4,
2957 Asm->GetTempSymbol("gnu_pubtypes", NewCU->getUniqueID()),
2958 DwarfGnuPubTypesSectionSym);
2961 // Flag if we've emitted any ranges and their location for the compile unit.
2962 if (DebugRangeSymbols.size()) {
2963 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2964 NewCU->addLabel(Die, dwarf::DW_AT_GNU_ranges_base,
2965 dwarf::DW_FORM_sec_offset, DwarfDebugRangeSectionSym);
2967 NewCU->addUInt(Die, dwarf::DW_AT_GNU_ranges_base, dwarf::DW_FORM_data4,
2971 SkeletonHolder.addUnit(NewCU);
2972 SkeletonCUs.push_back(NewCU);
2977 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2978 assert(useSplitDwarf() && "No split dwarf debug info?");
2979 emitAbbrevs(Section, &SkeletonAbbrevs);
2982 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2983 // compile units that would normally be in debug_info.
2984 void DwarfDebug::emitDebugInfoDWO() {
2985 assert(useSplitDwarf() && "No split dwarf debug info?");
2986 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2987 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2988 DwarfAbbrevDWOSectionSym);
2991 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2992 // abbreviations for the .debug_info.dwo section.
2993 void DwarfDebug::emitDebugAbbrevDWO() {
2994 assert(useSplitDwarf() && "No split dwarf?");
2995 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2999 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3000 // string section and is identical in format to traditional .debug_str
3002 void DwarfDebug::emitDebugStrDWO() {
3003 assert(useSplitDwarf() && "No split dwarf?");
3004 const MCSection *OffSec = Asm->getObjFileLowering()
3005 .getDwarfStrOffDWOSection();
3006 const MCSymbol *StrSym = DwarfStrSectionSym;
3007 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),