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"
17 #include "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/DIBuilder.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegisterInfo.h"
49 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
51 cl::desc("Disable debug info printing"));
53 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54 cl::desc("Make an absence of debug location information explicit."),
57 static cl::opt<bool> GenerateDwarfPubNamesSection("generate-dwarf-pubnames",
58 cl::Hidden, cl::init(false),
59 cl::desc("Generate DWARF pubnames section"));
63 Default, Enable, Disable
67 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
68 cl::desc("Output prototype dwarf accelerator tables."),
70 clEnumVal(Default, "Default for platform"),
71 clEnumVal(Enable, "Enabled"),
72 clEnumVal(Disable, "Disabled"),
76 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
77 cl::desc("Compatibility with Darwin gdb."),
79 clEnumVal(Default, "Default for platform"),
80 clEnumVal(Enable, "Enabled"),
81 clEnumVal(Disable, "Disabled"),
85 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
86 cl::desc("Output prototype dwarf split debug info."),
88 clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"),
95 const char *DWARFGroupName = "DWARF Emission";
96 const char *DbgTimerName = "DWARF Debug Writer";
99 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
100 return lhs.first < rhs.first;
103 } // end anonymous namespace
105 //===----------------------------------------------------------------------===//
107 // Configuration values for initial hash set sizes (log2).
109 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
113 DIType DbgVariable::getType() const {
114 DIType Ty = Var.getType();
115 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
116 // addresses instead.
117 if (Var.isBlockByrefVariable()) {
118 /* Byref variables, in Blocks, are declared by the programmer as
119 "SomeType VarName;", but the compiler creates a
120 __Block_byref_x_VarName struct, and gives the variable VarName
121 either the struct, or a pointer to the struct, as its type. This
122 is necessary for various behind-the-scenes things the compiler
123 needs to do with by-reference variables in blocks.
125 However, as far as the original *programmer* is concerned, the
126 variable should still have type 'SomeType', as originally declared.
128 The following function dives into the __Block_byref_x_VarName
129 struct to find the original type of the variable. This will be
130 passed back to the code generating the type for the Debug
131 Information Entry for the variable 'VarName'. 'VarName' will then
132 have the original type 'SomeType' in its debug information.
134 The original type 'SomeType' will be the type of the field named
135 'VarName' inside the __Block_byref_x_VarName struct.
137 NOTE: In order for this to not completely fail on the debugger
138 side, the Debug Information Entry for the variable VarName needs to
139 have a DW_AT_location that tells the debugger how to unwind through
140 the pointers and __Block_byref_x_VarName struct to find the actual
141 value of the variable. The function addBlockByrefType does this. */
143 unsigned tag = Ty.getTag();
145 if (tag == dwarf::DW_TAG_pointer_type) {
146 DIDerivedType DTy = DIDerivedType(Ty);
147 subType = DTy.getTypeDerivedFrom();
150 DICompositeType blockStruct = DICompositeType(subType);
151 DIArray Elements = blockStruct.getTypeArray();
153 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
154 DIDescriptor Element = Elements.getElement(i);
155 DIDerivedType DT = DIDerivedType(Element);
156 if (getName() == DT.getName())
157 return (DT.getTypeDerivedFrom());
163 } // end llvm namespace
165 /// Return Dwarf Version by checking module flags.
166 static unsigned getDwarfVersionFromModule(const Module *M) {
167 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
168 M->getModuleFlagsMetadata(ModuleFlags);
169 for (unsigned I = 0, E = ModuleFlags.size(); I < E; ++I) {
170 const Module::ModuleFlagEntry &MFE = ModuleFlags[I];
171 StringRef Key = MFE.Key->getString();
172 Value *Val = MFE.Val;
174 if (Key == "Dwarf Version")
175 return cast<ConstantInt>(Val)->getZExtValue();
177 return dwarf::DWARF_VERSION;
180 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
181 : Asm(A), MMI(Asm->MMI), FirstCU(0),
182 AbbreviationsSet(InitAbbreviationsSetSize),
183 SourceIdMap(DIEValueAllocator),
184 PrevLabel(NULL), GlobalCUIndexCount(0),
185 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
187 SkeletonAbbrevSet(InitAbbreviationsSetSize),
188 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
191 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
192 DwarfStrSectionSym = TextSectionSym = 0;
193 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
194 DwarfAddrSectionSym = 0;
195 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
196 FunctionBeginSym = FunctionEndSym = 0;
198 // Turn on accelerator tables and older gdb compatibility
200 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
201 if (DarwinGDBCompat == Default) {
203 IsDarwinGDBCompat = true;
205 IsDarwinGDBCompat = false;
207 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
209 if (DwarfAccelTables == Default) {
211 HasDwarfAccelTables = true;
213 HasDwarfAccelTables = false;
215 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
217 if (SplitDwarf == Default)
218 HasSplitDwarf = false;
220 HasSplitDwarf = SplitDwarf == Enable ? true : false;
222 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
225 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
229 DwarfDebug::~DwarfDebug() {
232 // Switch to the specified MCSection and emit an assembler
233 // temporary label to it if SymbolStem is specified.
234 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
235 const char *SymbolStem = 0) {
236 Asm->OutStreamer.SwitchSection(Section);
237 if (!SymbolStem) return 0;
239 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
240 Asm->OutStreamer.EmitLabel(TmpSym);
244 MCSymbol *DwarfUnits::getStringPoolSym() {
245 return Asm->GetTempSymbol(StringPref);
248 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
249 std::pair<MCSymbol*, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
251 if (Entry.first) return Entry.first;
253 Entry.second = NextStringPoolNumber++;
254 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
257 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
258 std::pair<MCSymbol*, unsigned> &Entry =
259 StringPool.GetOrCreateValue(Str).getValue();
260 if (Entry.first) return Entry.second;
262 Entry.second = NextStringPoolNumber++;
263 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
267 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
268 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
271 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
272 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
273 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
275 ++NextAddrPoolNumber;
276 return P.first->second;
279 // Define a unique number for the abbreviation.
281 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
282 // Check the set for priors.
283 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
285 // If it's newly added.
286 if (InSet == &Abbrev) {
287 // Add to abbreviation list.
288 Abbreviations->push_back(&Abbrev);
290 // Assign the vector position + 1 as its number.
291 Abbrev.setNumber(Abbreviations->size());
293 // Assign existing abbreviation number.
294 Abbrev.setNumber(InSet->getNumber());
298 static bool isObjCClass(StringRef Name) {
299 return Name.startswith("+") || Name.startswith("-");
302 static bool hasObjCCategory(StringRef Name) {
303 if (!isObjCClass(Name)) return false;
305 size_t pos = Name.find(')');
306 if (pos != std::string::npos) {
307 if (Name[pos+1] != ' ') return false;
313 static void getObjCClassCategory(StringRef In, StringRef &Class,
314 StringRef &Category) {
315 if (!hasObjCCategory(In)) {
316 Class = In.slice(In.find('[') + 1, In.find(' '));
321 Class = In.slice(In.find('[') + 1, In.find('('));
322 Category = In.slice(In.find('[') + 1, In.find(' '));
326 static StringRef getObjCMethodName(StringRef In) {
327 return In.slice(In.find(' ') + 1, In.find(']'));
330 // Add the various names to the Dwarf accelerator table names.
331 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
333 if (!SP.isDefinition()) return;
335 TheCU->addAccelName(SP.getName(), Die);
337 // If the linkage name is different than the name, go ahead and output
338 // that as well into the name table.
339 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
340 TheCU->addAccelName(SP.getLinkageName(), Die);
342 // If this is an Objective-C selector name add it to the ObjC accelerator
344 if (isObjCClass(SP.getName())) {
345 StringRef Class, Category;
346 getObjCClassCategory(SP.getName(), Class, Category);
347 TheCU->addAccelObjC(Class, Die);
349 TheCU->addAccelObjC(Category, Die);
350 // Also add the base method name to the name table.
351 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
355 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
356 // and DW_AT_high_pc attributes. If there are global variables in this
357 // scope then create and insert DIEs for these variables.
358 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
359 const MDNode *SPNode) {
360 DIE *SPDie = SPCU->getDIE(SPNode);
362 assert(SPDie && "Unable to find subprogram DIE!");
363 DISubprogram SP(SPNode);
365 // If we're updating an abstract DIE, then we will be adding the children and
366 // object pointer later on. But what we don't want to do is process the
367 // concrete DIE twice.
368 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
370 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
371 // Pick up abstract subprogram DIE.
372 SPDie = new DIE(dwarf::DW_TAG_subprogram);
373 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
375 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
376 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
380 DISubprogram SPDecl = SP.getFunctionDeclaration();
381 if (!SPDecl.isSubprogram()) {
382 // There is not any need to generate specification DIE for a function
383 // defined at compile unit level. If a function is defined inside another
384 // function then gdb prefers the definition at top level and but does not
385 // expect specification DIE in parent function. So avoid creating
386 // specification DIE for a function defined inside a function.
387 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
388 !SP.getContext().isFile() &&
389 !isSubprogramContext(SP.getContext())) {
390 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
393 DICompositeType SPTy = SP.getType();
394 DIArray Args = SPTy.getTypeArray();
395 unsigned SPTag = SPTy.getTag();
396 if (SPTag == dwarf::DW_TAG_subroutine_type)
397 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
398 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
399 DIType ATy = DIType(Args.getElement(i));
400 SPCU->addType(Arg, ATy);
401 if (ATy.isArtificial())
402 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
403 if (ATy.isObjectPointer())
404 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
405 dwarf::DW_FORM_ref4, Arg);
406 SPDie->addChild(Arg);
408 DIE *SPDeclDie = SPDie;
409 SPDie = new DIE(dwarf::DW_TAG_subprogram);
410 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
411 dwarf::DW_FORM_ref4, SPDeclDie);
417 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
418 Asm->GetTempSymbol("func_begin",
419 Asm->getFunctionNumber()));
420 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
421 Asm->GetTempSymbol("func_end",
422 Asm->getFunctionNumber()));
423 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
424 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
425 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
427 // Add name to the name table, we do this here because we're guaranteed
428 // to have concrete versions of our DW_TAG_subprogram nodes.
429 addSubprogramNames(SPCU, SP, SPDie);
434 // Construct new DW_TAG_lexical_block for this scope and attach
435 // DW_AT_low_pc/DW_AT_high_pc labels.
436 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
437 LexicalScope *Scope) {
438 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
439 if (Scope->isAbstractScope())
442 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
446 // If we have multiple ranges, emit them into the range section.
447 if (Ranges.size() > 1) {
448 // .debug_range section has not been laid out yet. Emit offset in
449 // .debug_range as a uint, size 4, for now. emitDIE will handle
450 // DW_AT_ranges appropriately.
451 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
452 DebugRangeSymbols.size()
453 * Asm->getDataLayout().getPointerSize());
454 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
455 RE = Ranges.end(); RI != RE; ++RI) {
456 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
457 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
460 // Terminate the range list.
461 DebugRangeSymbols.push_back(NULL);
462 DebugRangeSymbols.push_back(NULL);
466 // Construct the address range for this DIE.
467 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
468 MCSymbol *Start = getLabelBeforeInsn(RI->first);
469 MCSymbol *End = getLabelAfterInsn(RI->second);
471 if (End == 0) return 0;
473 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
474 assert(End->isDefined() && "Invalid end label for an inlined scope!");
476 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
477 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
482 // This scope represents inlined body of a function. Construct DIE to
483 // represent this concrete inlined copy of the function.
484 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
485 LexicalScope *Scope) {
486 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
487 assert(Ranges.empty() == false &&
488 "LexicalScope does not have instruction markers!");
490 if (!Scope->getScopeNode())
492 DIScope DS(Scope->getScopeNode());
493 DISubprogram InlinedSP = getDISubprogram(DS);
494 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
496 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
500 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
501 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
502 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
504 if (StartLabel == 0 || EndLabel == 0) {
505 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
507 assert(StartLabel->isDefined() &&
508 "Invalid starting label for an inlined scope!");
509 assert(EndLabel->isDefined() &&
510 "Invalid end label for an inlined scope!");
512 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
513 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
514 dwarf::DW_FORM_ref4, OriginDIE);
516 if (Ranges.size() > 1) {
517 // .debug_range section has not been laid out yet. Emit offset in
518 // .debug_range as a uint, size 4, for now. emitDIE will handle
519 // DW_AT_ranges appropriately.
520 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
521 DebugRangeSymbols.size()
522 * Asm->getDataLayout().getPointerSize());
523 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
524 RE = Ranges.end(); RI != RE; ++RI) {
525 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
526 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
528 DebugRangeSymbols.push_back(NULL);
529 DebugRangeSymbols.push_back(NULL);
531 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
532 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
535 InlinedSubprogramDIEs.insert(OriginDIE);
537 // Track the start label for this inlined function.
538 //.debug_inlined section specification does not clearly state how
539 // to emit inlined scope that is split into multiple instruction ranges.
540 // For now, use first instruction range and emit low_pc/high_pc pair and
541 // corresponding .debug_inlined section entry for this pair.
542 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
543 I = InlineInfo.find(InlinedSP);
545 if (I == InlineInfo.end()) {
546 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
547 InlinedSPNodes.push_back(InlinedSP);
549 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
551 DILocation DL(Scope->getInlinedAt());
552 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
553 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
554 TheCU->getUniqueID()));
555 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
557 // Add name to the name table, we do this here because we're guaranteed
558 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
559 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
564 // Construct a DIE for this scope.
565 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
566 if (!Scope || !Scope->getScopeNode())
569 DIScope DS(Scope->getScopeNode());
570 // Early return to avoid creating dangling variable|scope DIEs.
571 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
575 SmallVector<DIE *, 8> Children;
576 DIE *ObjectPointer = NULL;
578 // Collect arguments for current function.
579 if (LScopes.isCurrentFunctionScope(Scope))
580 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
581 if (DbgVariable *ArgDV = CurrentFnArguments[i])
583 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
584 Children.push_back(Arg);
585 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
588 // Collect lexical scope children first.
589 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
590 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
592 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
593 Children.push_back(Variable);
594 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
596 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
597 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
598 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
599 Children.push_back(Nested);
600 DIE *ScopeDIE = NULL;
601 if (Scope->getInlinedAt())
602 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
603 else if (DS.isSubprogram()) {
604 ProcessedSPNodes.insert(DS);
605 if (Scope->isAbstractScope()) {
606 ScopeDIE = TheCU->getDIE(DS);
607 // Note down abstract DIE.
609 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
612 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
615 // There is no need to emit empty lexical block DIE.
616 std::pair<ImportedEntityMap::const_iterator,
617 ImportedEntityMap::const_iterator> Range = std::equal_range(
618 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
619 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
621 if (Children.empty() && Range.first == Range.second)
623 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
624 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
626 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
629 if (!ScopeDIE) return NULL;
632 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
633 E = Children.end(); I != E; ++I)
634 ScopeDIE->addChild(*I);
636 if (DS.isSubprogram() && ObjectPointer != NULL)
637 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
638 dwarf::DW_FORM_ref4, ObjectPointer);
640 if (DS.isSubprogram())
641 TheCU->addPubTypes(DISubprogram(DS));
646 // Look up the source id with the given directory and source file names.
647 // If none currently exists, create a new id and insert it in the
648 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
650 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
651 StringRef DirName, unsigned CUID) {
652 // If we use .loc in assembly, we can't separate .file entries according to
653 // compile units. Thus all files will belong to the default compile unit.
654 if (Asm->TM.hasMCUseLoc() &&
655 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
658 // If FE did not provide a file name, then assume stdin.
659 if (FileName.empty())
660 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
662 // TODO: this might not belong here. See if we can factor this better.
663 if (DirName == CompilationDir)
666 // FileIDCUMap stores the current ID for the given compile unit.
667 unsigned SrcId = FileIDCUMap[CUID] + 1;
669 // We look up the CUID/file/dir by concatenating them with a zero byte.
670 SmallString<128> NamePair;
671 NamePair += utostr(CUID);
674 NamePair += '\0'; // Zero bytes are not allowed in paths.
675 NamePair += FileName;
677 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
678 if (Ent.getValue() != SrcId)
679 return Ent.getValue();
681 FileIDCUMap[CUID] = SrcId;
682 // Print out a .file directive to specify files for .loc directives.
683 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
688 // Create new CompileUnit for the given metadata node with tag
689 // DW_TAG_compile_unit.
690 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
691 DICompileUnit DIUnit(N);
692 StringRef FN = DIUnit.getFilename();
693 CompilationDir = DIUnit.getDirectory();
695 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
696 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
697 DIUnit.getLanguage(), Die, N, Asm,
700 FileIDCUMap[NewCU->getUniqueID()] = 0;
701 // Call this to emit a .file directive if it wasn't emitted for the source
702 // file this CU comes from yet.
703 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
705 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
706 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
707 DIUnit.getLanguage());
708 NewCU->addString(Die, dwarf::DW_AT_name, FN);
710 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
711 // into an entity. We're using 0 (or a NULL label) for this. For
712 // split dwarf it's in the skeleton CU so omit it here.
713 if (!useSplitDwarf())
714 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
716 // Define start line table label for each Compile Unit.
717 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
718 NewCU->getUniqueID());
719 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
720 NewCU->getUniqueID());
722 // Use a single line table if we are using .loc and generating assembly.
724 (Asm->TM.hasMCUseLoc() &&
725 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
726 (NewCU->getUniqueID() == 0);
728 // DW_AT_stmt_list is a offset of line number information for this
729 // compile unit in debug_line section. For split dwarf this is
730 // left in the skeleton CU and so not included.
731 // The line table entries are not always emitted in assembly, so it
732 // is not okay to use line_table_start here.
733 if (!useSplitDwarf()) {
734 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
735 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
737 Asm->GetTempSymbol("section_line") : LineTableStartSym);
738 else if (UseTheFirstCU)
739 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
741 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
742 LineTableStartSym, DwarfLineSectionSym);
745 // If we're using split dwarf the compilation dir is going to be in the
746 // skeleton CU and so we don't need to duplicate it here.
747 if (!useSplitDwarf() && !CompilationDir.empty())
748 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
749 if (DIUnit.isOptimized())
750 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
752 StringRef Flags = DIUnit.getFlags();
754 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
756 if (unsigned RVer = DIUnit.getRunTimeVersion())
757 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
758 dwarf::DW_FORM_data1, RVer);
763 InfoHolder.addUnit(NewCU);
765 CUMap.insert(std::make_pair(N, NewCU));
769 // Construct subprogram DIE.
770 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
772 CompileUnit *&CURef = SPMap[N];
778 if (!SP.isDefinition())
779 // This is a method declaration which will be handled while constructing
783 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
786 TheCU->insertDIE(N, SubprogramDie);
788 // Add to context owner.
789 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
791 // Expose as global, if requested.
792 if (GenerateDwarfPubNamesSection)
793 TheCU->addGlobalName(SP.getName(), SubprogramDie);
796 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
798 DIImportedEntity Module(N);
799 if (!Module.Verify())
801 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
802 constructImportedEntityDIE(TheCU, Module, D);
805 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
807 DIImportedEntity Module(N);
808 if (!Module.Verify())
810 return constructImportedEntityDIE(TheCU, Module, Context);
813 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
814 const DIImportedEntity &Module,
816 assert(Module.Verify() &&
817 "Use one of the MDNode * overloads to handle invalid metadata");
818 assert(Context && "Should always have a context for an imported_module");
819 DIE *IMDie = new DIE(Module.getTag());
820 TheCU->insertDIE(Module, IMDie);
822 DIDescriptor Entity = Module.getEntity();
823 if (Entity.isNameSpace())
824 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
825 else if (Entity.isSubprogram())
826 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
827 else if (Entity.isType())
828 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
830 EntityDie = TheCU->getDIE(Entity);
831 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
832 Module.getContext().getDirectory(),
833 TheCU->getUniqueID());
834 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
835 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
836 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
838 StringRef Name = Module.getName();
840 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
841 Context->addChild(IMDie);
844 // Emit all Dwarf sections that should come prior to the content. Create
845 // global DIEs and emit initial debug info sections. This is invoked by
846 // the target AsmPrinter.
847 void DwarfDebug::beginModule() {
848 if (DisableDebugInfoPrinting)
851 const Module *M = MMI->getModule();
853 // If module has named metadata anchors then use them, otherwise scan the
854 // module using debug info finder to collect debug info.
855 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
859 // Emit initial sections so we can reference labels later.
862 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
863 DICompileUnit CUNode(CU_Nodes->getOperand(i));
864 CompileUnit *CU = constructCompileUnit(CUNode);
865 DIArray ImportedEntities = CUNode.getImportedEntities();
866 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
867 ScopesWithImportedEntities.push_back(std::make_pair(
868 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
869 ImportedEntities.getElement(i)));
870 std::sort(ScopesWithImportedEntities.begin(),
871 ScopesWithImportedEntities.end(), CompareFirst());
872 DIArray GVs = CUNode.getGlobalVariables();
873 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
874 CU->createGlobalVariableDIE(GVs.getElement(i));
875 DIArray SPs = CUNode.getSubprograms();
876 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
877 constructSubprogramDIE(CU, SPs.getElement(i));
878 DIArray EnumTypes = CUNode.getEnumTypes();
879 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
880 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
881 DIArray RetainedTypes = CUNode.getRetainedTypes();
882 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
883 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
884 // Emit imported_modules last so that the relevant context is already
886 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
887 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
888 // If we're splitting the dwarf out now that we've got the entire
889 // CU then construct a skeleton CU based upon it.
890 if (useSplitDwarf()) {
891 // This should be a unique identifier when we want to build .dwp files.
892 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
893 dwarf::DW_FORM_data8, 0);
894 // Now construct the skeleton CU associated.
895 constructSkeletonCU(CUNode);
899 // Tell MMI that we have debug info.
900 MMI->setDebugInfoAvailability(true);
902 // Prime section data.
903 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
906 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
907 void DwarfDebug::computeInlinedDIEs() {
908 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
909 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
910 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
912 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
914 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
915 AE = AbstractSPDies.end(); AI != AE; ++AI) {
916 DIE *ISP = AI->second;
917 if (InlinedSubprogramDIEs.count(ISP))
919 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
923 // Collect info for variables that were optimized out.
924 void DwarfDebug::collectDeadVariables() {
925 const Module *M = MMI->getModule();
926 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
928 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
929 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
930 DICompileUnit TheCU(CU_Nodes->getOperand(i));
931 DIArray Subprograms = TheCU.getSubprograms();
932 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
933 DISubprogram SP(Subprograms.getElement(i));
934 if (ProcessedSPNodes.count(SP) != 0) continue;
935 if (!SP.Verify()) continue;
936 if (!SP.isDefinition()) continue;
937 DIArray Variables = SP.getVariables();
938 if (Variables.getNumElements() == 0) continue;
940 LexicalScope *Scope =
941 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
942 DeadFnScopeMap[SP] = Scope;
944 // Construct subprogram DIE and add variables DIEs.
945 CompileUnit *SPCU = CUMap.lookup(TheCU);
946 assert(SPCU && "Unable to find Compile Unit!");
947 constructSubprogramDIE(SPCU, SP);
948 DIE *ScopeDIE = SPCU->getDIE(SP);
949 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
950 DIVariable DV(Variables.getElement(vi));
951 if (!DV.Verify()) continue;
952 DbgVariable *NewVar = new DbgVariable(DV, NULL);
953 if (DIE *VariableDIE =
954 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
955 ScopeDIE->addChild(VariableDIE);
960 DeleteContainerSeconds(DeadFnScopeMap);
963 void DwarfDebug::finalizeModuleInfo() {
964 // Collect info for variables that were optimized out.
965 collectDeadVariables();
967 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
968 computeInlinedDIEs();
970 // Emit DW_AT_containing_type attribute to connect types with their
971 // vtable holding type.
972 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
973 CUE = CUMap.end(); CUI != CUE; ++CUI) {
974 CompileUnit *TheCU = CUI->second;
975 TheCU->constructContainingTypeDIEs();
978 // Compute DIE offsets and sizes.
979 InfoHolder.computeSizeAndOffsets();
981 SkeletonHolder.computeSizeAndOffsets();
984 void DwarfDebug::endSections() {
985 // Standard sections final addresses.
986 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
987 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
988 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
989 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
991 // End text sections.
992 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
993 Asm->OutStreamer.SwitchSection(SectionMap[I]);
994 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
998 // Emit all Dwarf sections that should come after the content.
999 void DwarfDebug::endModule() {
1001 if (!FirstCU) return;
1003 // End any existing sections.
1004 // TODO: Does this need to happen?
1007 // Finalize the debug info for the module.
1008 finalizeModuleInfo();
1010 if (!useSplitDwarf()) {
1011 // Emit all the DIEs into a debug info section.
1014 // Corresponding abbreviations into a abbrev section.
1015 emitAbbreviations();
1017 // Emit info into a debug loc section.
1020 // Emit info into a debug aranges section.
1023 // Emit info into a debug ranges section.
1026 // Emit info into a debug macinfo section.
1029 // Emit inline info.
1030 // TODO: When we don't need the option anymore we
1031 // can remove all of the code that this section
1033 if (useDarwinGDBCompat())
1034 emitDebugInlineInfo();
1036 // TODO: Fill this in for separated debug sections and separate
1037 // out information into new sections.
1039 // Emit the debug info section and compile units.
1043 // Corresponding abbreviations into a abbrev section.
1044 emitAbbreviations();
1045 emitDebugAbbrevDWO();
1047 // Emit info into a debug loc section.
1050 // Emit info into a debug aranges section.
1053 // Emit info into a debug ranges section.
1056 // Emit info into a debug macinfo section.
1059 // Emit DWO addresses.
1060 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1062 // Emit inline info.
1063 // TODO: When we don't need the option anymore we
1064 // can remove all of the code that this section
1066 if (useDarwinGDBCompat())
1067 emitDebugInlineInfo();
1070 // Emit info into the dwarf accelerator table sections.
1071 if (useDwarfAccelTables()) {
1074 emitAccelNamespaces();
1078 // Emit info into a debug pubnames section, if requested.
1079 if (GenerateDwarfPubNamesSection)
1080 emitDebugPubnames();
1082 // Emit info into a debug pubtypes section.
1083 // TODO: When we don't need the option anymore we can
1084 // remove all of the code that adds to the table.
1085 if (useDarwinGDBCompat())
1086 emitDebugPubTypes();
1088 // Finally emit string information into a string table.
1090 if (useSplitDwarf())
1095 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1096 E = CUMap.end(); I != E; ++I)
1099 for (SmallVector<CompileUnit *, 1>::iterator I = SkeletonCUs.begin(),
1100 E = SkeletonCUs.end(); I != E; ++I)
1103 // Reset these for the next Module if we have one.
1107 // Find abstract variable, if any, associated with Var.
1108 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1109 DebugLoc ScopeLoc) {
1110 LLVMContext &Ctx = DV->getContext();
1111 // More then one inlined variable corresponds to one abstract variable.
1112 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1113 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1115 return AbsDbgVariable;
1117 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1121 AbsDbgVariable = new DbgVariable(Var, NULL);
1122 addScopeVariable(Scope, AbsDbgVariable);
1123 AbstractVariables[Var] = AbsDbgVariable;
1124 return AbsDbgVariable;
1127 // If Var is a current function argument then add it to CurrentFnArguments list.
1128 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1129 DbgVariable *Var, LexicalScope *Scope) {
1130 if (!LScopes.isCurrentFunctionScope(Scope))
1132 DIVariable DV = Var->getVariable();
1133 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1135 unsigned ArgNo = DV.getArgNumber();
1139 size_t Size = CurrentFnArguments.size();
1141 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1142 // llvm::Function argument size is not good indicator of how many
1143 // arguments does the function have at source level.
1145 CurrentFnArguments.resize(ArgNo * 2);
1146 CurrentFnArguments[ArgNo - 1] = Var;
1150 // Collect variable information from side table maintained by MMI.
1152 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1153 SmallPtrSet<const MDNode *, 16> &Processed) {
1154 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1155 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1156 VE = VMap.end(); VI != VE; ++VI) {
1157 const MDNode *Var = VI->first;
1159 Processed.insert(Var);
1161 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1163 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1165 // If variable scope is not found then skip this variable.
1169 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1170 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1171 RegVar->setFrameIndex(VP.first);
1172 if (!addCurrentFnArgument(MF, RegVar, Scope))
1173 addScopeVariable(Scope, RegVar);
1175 AbsDbgVariable->setFrameIndex(VP.first);
1179 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1181 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1182 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1183 return MI->getNumOperands() == 3 &&
1184 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1185 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1188 // Get .debug_loc entry for the instruction range starting at MI.
1189 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1190 const MCSymbol *FLabel,
1191 const MCSymbol *SLabel,
1192 const MachineInstr *MI) {
1193 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1195 assert(MI->getNumOperands() == 3);
1196 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1197 MachineLocation MLoc;
1198 // TODO: Currently an offset of 0 in a DBG_VALUE means
1199 // we need to generate a direct register value.
1200 // There is no way to specify an indirect value with offset 0.
1201 if (MI->getOperand(1).getImm() == 0)
1202 MLoc.set(MI->getOperand(0).getReg());
1204 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1205 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1207 if (MI->getOperand(0).isImm())
1208 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1209 if (MI->getOperand(0).isFPImm())
1210 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1211 if (MI->getOperand(0).isCImm())
1212 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1214 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1217 // Find variables for each lexical scope.
1219 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1220 SmallPtrSet<const MDNode *, 16> &Processed) {
1222 // collection info from MMI table.
1223 collectVariableInfoFromMMITable(MF, Processed);
1225 for (SmallVectorImpl<const MDNode*>::const_iterator
1226 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1228 const MDNode *Var = *UVI;
1229 if (Processed.count(Var))
1232 // History contains relevant DBG_VALUE instructions for Var and instructions
1234 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1235 if (History.empty())
1237 const MachineInstr *MInsn = History.front();
1240 LexicalScope *Scope = NULL;
1241 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1242 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1243 Scope = LScopes.getCurrentFunctionScope();
1244 else if (MDNode *IA = DV.getInlinedAt())
1245 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1247 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1248 // If variable scope is not found then skip this variable.
1252 Processed.insert(DV);
1253 assert(MInsn->isDebugValue() && "History must begin with debug value");
1254 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1255 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1256 if (!addCurrentFnArgument(MF, RegVar, Scope))
1257 addScopeVariable(Scope, RegVar);
1259 AbsVar->setMInsn(MInsn);
1261 // Simplify ranges that are fully coalesced.
1262 if (History.size() <= 1 || (History.size() == 2 &&
1263 MInsn->isIdenticalTo(History.back()))) {
1264 RegVar->setMInsn(MInsn);
1268 // Handle multiple DBG_VALUE instructions describing one variable.
1269 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1271 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1272 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1273 const MachineInstr *Begin = *HI;
1274 assert(Begin->isDebugValue() && "Invalid History entry");
1276 // Check if DBG_VALUE is truncating a range.
1277 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1278 && !Begin->getOperand(0).getReg())
1281 // Compute the range for a register location.
1282 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1283 const MCSymbol *SLabel = 0;
1286 // If Begin is the last instruction in History then its value is valid
1287 // until the end of the function.
1288 SLabel = FunctionEndSym;
1290 const MachineInstr *End = HI[1];
1291 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1292 << "\t" << *Begin << "\t" << *End << "\n");
1293 if (End->isDebugValue())
1294 SLabel = getLabelBeforeInsn(End);
1296 // End is a normal instruction clobbering the range.
1297 SLabel = getLabelAfterInsn(End);
1298 assert(SLabel && "Forgot label after clobber instruction");
1303 // The value is valid until the next DBG_VALUE or clobber.
1304 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1307 DotDebugLocEntries.push_back(DotDebugLocEntry());
1310 // Collect info for variables that were optimized out.
1311 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1312 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1313 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1314 DIVariable DV(Variables.getElement(i));
1315 if (!DV || !DV.Verify() || !Processed.insert(DV))
1317 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1318 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1322 // Return Label preceding the instruction.
1323 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1324 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1325 assert(Label && "Didn't insert label before instruction");
1329 // Return Label immediately following the instruction.
1330 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1331 return LabelsAfterInsn.lookup(MI);
1334 // Process beginning of an instruction.
1335 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1336 // Check if source location changes, but ignore DBG_VALUE locations.
1337 if (!MI->isDebugValue()) {
1338 DebugLoc DL = MI->getDebugLoc();
1339 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1342 if (DL == PrologEndLoc) {
1343 Flags |= DWARF2_FLAG_PROLOGUE_END;
1344 PrologEndLoc = DebugLoc();
1346 if (PrologEndLoc.isUnknown())
1347 Flags |= DWARF2_FLAG_IS_STMT;
1349 if (!DL.isUnknown()) {
1350 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1351 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1353 recordSourceLine(0, 0, 0, 0);
1357 // Insert labels where requested.
1358 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1359 LabelsBeforeInsn.find(MI);
1362 if (I == LabelsBeforeInsn.end())
1365 // Label already assigned.
1370 PrevLabel = MMI->getContext().CreateTempSymbol();
1371 Asm->OutStreamer.EmitLabel(PrevLabel);
1373 I->second = PrevLabel;
1376 // Process end of an instruction.
1377 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1378 // Don't create a new label after DBG_VALUE instructions.
1379 // They don't generate code.
1380 if (!MI->isDebugValue())
1383 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1384 LabelsAfterInsn.find(MI);
1387 if (I == LabelsAfterInsn.end())
1390 // Label already assigned.
1394 // We need a label after this instruction.
1396 PrevLabel = MMI->getContext().CreateTempSymbol();
1397 Asm->OutStreamer.EmitLabel(PrevLabel);
1399 I->second = PrevLabel;
1402 // Each LexicalScope has first instruction and last instruction to mark
1403 // beginning and end of a scope respectively. Create an inverse map that list
1404 // scopes starts (and ends) with an instruction. One instruction may start (or
1405 // end) multiple scopes. Ignore scopes that are not reachable.
1406 void DwarfDebug::identifyScopeMarkers() {
1407 SmallVector<LexicalScope *, 4> WorkList;
1408 WorkList.push_back(LScopes.getCurrentFunctionScope());
1409 while (!WorkList.empty()) {
1410 LexicalScope *S = WorkList.pop_back_val();
1412 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1413 if (!Children.empty())
1414 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1415 SE = Children.end(); SI != SE; ++SI)
1416 WorkList.push_back(*SI);
1418 if (S->isAbstractScope())
1421 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1424 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1425 RE = Ranges.end(); RI != RE; ++RI) {
1426 assert(RI->first && "InsnRange does not have first instruction!");
1427 assert(RI->second && "InsnRange does not have second instruction!");
1428 requestLabelBeforeInsn(RI->first);
1429 requestLabelAfterInsn(RI->second);
1434 // Get MDNode for DebugLoc's scope.
1435 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1436 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1437 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1438 return DL.getScope(Ctx);
1441 // Walk up the scope chain of given debug loc and find line number info
1442 // for the function.
1443 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1444 const MDNode *Scope = getScopeNode(DL, Ctx);
1445 DISubprogram SP = getDISubprogram(Scope);
1447 // Check for number of operands since the compatibility is
1449 if (SP->getNumOperands() > 19)
1450 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1452 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1458 // Gather pre-function debug information. Assumes being called immediately
1459 // after the function entry point has been emitted.
1460 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1461 if (!MMI->hasDebugInfo()) return;
1462 LScopes.initialize(*MF);
1463 if (LScopes.empty()) return;
1464 identifyScopeMarkers();
1466 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1468 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1469 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1470 assert(TheCU && "Unable to find compile unit!");
1471 if (Asm->TM.hasMCUseLoc() &&
1472 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1473 // Use a single line table if we are using .loc and generating assembly.
1474 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1476 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1478 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1479 Asm->getFunctionNumber());
1480 // Assumes in correct section after the entry point.
1481 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1483 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1485 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1486 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1487 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1489 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1491 bool AtBlockEntry = true;
1492 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1494 const MachineInstr *MI = II;
1496 if (MI->isDebugValue()) {
1497 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1499 // Keep track of user variables.
1501 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1503 // Variable is in a register, we need to check for clobbers.
1504 if (isDbgValueInDefinedReg(MI))
1505 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1507 // Check the history of this variable.
1508 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1509 if (History.empty()) {
1510 UserVariables.push_back(Var);
1511 // The first mention of a function argument gets the FunctionBeginSym
1512 // label, so arguments are visible when breaking at function entry.
1514 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1515 DISubprogram(getDISubprogram(DV.getContext()))
1516 .describes(MF->getFunction()))
1517 LabelsBeforeInsn[MI] = FunctionBeginSym;
1519 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1520 const MachineInstr *Prev = History.back();
1521 if (Prev->isDebugValue()) {
1522 // Coalesce identical entries at the end of History.
1523 if (History.size() >= 2 &&
1524 Prev->isIdenticalTo(History[History.size() - 2])) {
1525 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1527 << "\t" << *History[History.size() - 2] << "\n");
1531 // Terminate old register assignments that don't reach MI;
1532 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1533 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1534 isDbgValueInDefinedReg(Prev)) {
1535 // Previous register assignment needs to terminate at the end of
1537 MachineBasicBlock::const_iterator LastMI =
1538 PrevMBB->getLastNonDebugInstr();
1539 if (LastMI == PrevMBB->end()) {
1540 // Drop DBG_VALUE for empty range.
1541 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1542 << "\t" << *Prev << "\n");
1544 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1545 // Terminate after LastMI.
1546 History.push_back(LastMI);
1550 History.push_back(MI);
1552 // Not a DBG_VALUE instruction.
1554 AtBlockEntry = false;
1556 // First known non-DBG_VALUE and non-frame setup location marks
1557 // the beginning of the function body.
1558 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1559 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1560 PrologEndLoc = MI->getDebugLoc();
1562 // Check if the instruction clobbers any registers with debug vars.
1563 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1564 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1565 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1567 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1568 AI.isValid(); ++AI) {
1570 const MDNode *Var = LiveUserVar[Reg];
1573 // Reg is now clobbered.
1574 LiveUserVar[Reg] = 0;
1576 // Was MD last defined by a DBG_VALUE referring to Reg?
1577 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1578 if (HistI == DbgValues.end())
1580 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1581 if (History.empty())
1583 const MachineInstr *Prev = History.back();
1584 // Sanity-check: Register assignments are terminated at the end of
1586 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1588 // Is the variable still in Reg?
1589 if (!isDbgValueInDefinedReg(Prev) ||
1590 Prev->getOperand(0).getReg() != Reg)
1592 // Var is clobbered. Make sure the next instruction gets a label.
1593 History.push_back(MI);
1600 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1602 SmallVectorImpl<const MachineInstr*> &History = I->second;
1603 if (History.empty())
1606 // Make sure the final register assignments are terminated.
1607 const MachineInstr *Prev = History.back();
1608 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1609 const MachineBasicBlock *PrevMBB = Prev->getParent();
1610 MachineBasicBlock::const_iterator LastMI =
1611 PrevMBB->getLastNonDebugInstr();
1612 if (LastMI == PrevMBB->end())
1613 // Drop DBG_VALUE for empty range.
1615 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1616 // Terminate after LastMI.
1617 History.push_back(LastMI);
1620 // Request labels for the full history.
1621 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1622 const MachineInstr *MI = History[i];
1623 if (MI->isDebugValue())
1624 requestLabelBeforeInsn(MI);
1626 requestLabelAfterInsn(MI);
1630 PrevInstLoc = DebugLoc();
1631 PrevLabel = FunctionBeginSym;
1633 // Record beginning of function.
1634 if (!PrologEndLoc.isUnknown()) {
1635 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1636 MF->getFunction()->getContext());
1637 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1638 FnStartDL.getScope(MF->getFunction()->getContext()),
1639 // We'd like to list the prologue as "not statements" but GDB behaves
1640 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1641 DWARF2_FLAG_IS_STMT);
1645 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1646 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1647 DIVariable DV = Var->getVariable();
1648 // Variables with positive arg numbers are parameters.
1649 if (unsigned ArgNum = DV.getArgNumber()) {
1650 // Keep all parameters in order at the start of the variable list to ensure
1651 // function types are correct (no out-of-order parameters)
1653 // This could be improved by only doing it for optimized builds (unoptimized
1654 // builds have the right order to begin with), searching from the back (this
1655 // would catch the unoptimized case quickly), or doing a binary search
1656 // rather than linear search.
1657 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1658 while (I != Vars.end()) {
1659 unsigned CurNum = (*I)->getVariable().getArgNumber();
1660 // A local (non-parameter) variable has been found, insert immediately
1664 // A later indexed parameter has been found, insert immediately before it.
1665 if (CurNum > ArgNum)
1669 Vars.insert(I, Var);
1673 Vars.push_back(Var);
1676 // Gather and emit post-function debug information.
1677 void DwarfDebug::endFunction(const MachineFunction *MF) {
1678 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1680 // Define end label for subprogram.
1681 FunctionEndSym = Asm->GetTempSymbol("func_end",
1682 Asm->getFunctionNumber());
1683 // Assumes in correct section after the entry point.
1684 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1685 // Set DwarfCompileUnitID in MCContext to default value.
1686 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1688 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1689 collectVariableInfo(MF, ProcessedVars);
1691 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1692 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1693 assert(TheCU && "Unable to find compile unit!");
1695 // Construct abstract scopes.
1696 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1697 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1698 LexicalScope *AScope = AList[i];
1699 DISubprogram SP(AScope->getScopeNode());
1701 // Collect info for variables that were optimized out.
1702 DIArray Variables = SP.getVariables();
1703 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1704 DIVariable DV(Variables.getElement(i));
1705 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1707 // Check that DbgVariable for DV wasn't created earlier, when
1708 // findAbstractVariable() was called for inlined instance of DV.
1709 LLVMContext &Ctx = DV->getContext();
1710 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1711 if (AbstractVariables.lookup(CleanDV))
1713 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1714 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1717 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1718 constructScopeDIE(TheCU, AScope);
1721 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1723 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1724 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1727 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1728 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1729 DeleteContainerPointers(I->second);
1730 ScopeVariables.clear();
1731 DeleteContainerPointers(CurrentFnArguments);
1732 UserVariables.clear();
1734 AbstractVariables.clear();
1735 LabelsBeforeInsn.clear();
1736 LabelsAfterInsn.clear();
1740 // Register a source line with debug info. Returns the unique label that was
1741 // emitted and which provides correspondence to the source line list.
1742 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1748 DIDescriptor Scope(S);
1750 if (Scope.isCompileUnit()) {
1751 DICompileUnit CU(S);
1752 Fn = CU.getFilename();
1753 Dir = CU.getDirectory();
1754 } else if (Scope.isFile()) {
1756 Fn = F.getFilename();
1757 Dir = F.getDirectory();
1758 } else if (Scope.isSubprogram()) {
1760 Fn = SP.getFilename();
1761 Dir = SP.getDirectory();
1762 } else if (Scope.isLexicalBlockFile()) {
1763 DILexicalBlockFile DBF(S);
1764 Fn = DBF.getFilename();
1765 Dir = DBF.getDirectory();
1766 } else if (Scope.isLexicalBlock()) {
1767 DILexicalBlock DB(S);
1768 Fn = DB.getFilename();
1769 Dir = DB.getDirectory();
1771 llvm_unreachable("Unexpected scope info");
1773 Src = getOrCreateSourceID(Fn, Dir,
1774 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1776 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1779 //===----------------------------------------------------------------------===//
1781 //===----------------------------------------------------------------------===//
1783 // Compute the size and offset of a DIE.
1785 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1786 // Get the children.
1787 const std::vector<DIE *> &Children = Die->getChildren();
1789 // Record the abbreviation.
1790 assignAbbrevNumber(Die->getAbbrev());
1792 // Get the abbreviation for this DIE.
1793 unsigned AbbrevNumber = Die->getAbbrevNumber();
1794 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1797 Die->setOffset(Offset);
1799 // Start the size with the size of abbreviation code.
1800 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1802 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1803 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1805 // Size the DIE attribute values.
1806 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1807 // Size attribute value.
1808 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1810 // Size the DIE children if any.
1811 if (!Children.empty()) {
1812 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1813 "Children flag not set");
1815 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1816 Offset = computeSizeAndOffset(Children[j], Offset);
1818 // End of children marker.
1819 Offset += sizeof(int8_t);
1822 Die->setSize(Offset - Die->getOffset());
1826 // Compute the size and offset of all the DIEs.
1827 void DwarfUnits::computeSizeAndOffsets() {
1828 // Offset from the beginning of debug info section.
1829 unsigned SecOffset = 0;
1830 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1831 E = CUs.end(); I != E; ++I) {
1832 (*I)->setDebugInfoOffset(SecOffset);
1834 sizeof(int32_t) + // Length of Compilation Unit Info
1835 sizeof(int16_t) + // DWARF version number
1836 sizeof(int32_t) + // Offset Into Abbrev. Section
1837 sizeof(int8_t); // Pointer Size (in bytes)
1839 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1840 SecOffset += EndOffset;
1844 // Emit initial Dwarf sections with a label at the start of each one.
1845 void DwarfDebug::emitSectionLabels() {
1846 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1848 // Dwarf sections base addresses.
1849 DwarfInfoSectionSym =
1850 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1851 DwarfAbbrevSectionSym =
1852 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1853 if (useSplitDwarf())
1854 DwarfAbbrevDWOSectionSym =
1855 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1856 "section_abbrev_dwo");
1857 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1859 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1860 emitSectionSym(Asm, MacroInfo);
1862 DwarfLineSectionSym =
1863 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1864 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1865 if (GenerateDwarfPubNamesSection)
1866 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1867 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1868 DwarfStrSectionSym =
1869 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1870 if (useSplitDwarf()) {
1871 DwarfStrDWOSectionSym =
1872 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1873 DwarfAddrSectionSym =
1874 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1876 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1879 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1880 "section_debug_loc");
1882 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1883 emitSectionSym(Asm, TLOF.getDataSection());
1886 // Recursively emits a debug information entry.
1887 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1888 // Get the abbreviation for this DIE.
1889 unsigned AbbrevNumber = Die->getAbbrevNumber();
1890 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1892 // Emit the code (index) for the abbreviation.
1893 if (Asm->isVerbose())
1894 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1895 Twine::utohexstr(Die->getOffset()) + ":0x" +
1896 Twine::utohexstr(Die->getSize()) + " " +
1897 dwarf::TagString(Abbrev->getTag()));
1898 Asm->EmitULEB128(AbbrevNumber);
1900 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1901 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1903 // Emit the DIE attribute values.
1904 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1905 unsigned Attr = AbbrevData[i].getAttribute();
1906 unsigned Form = AbbrevData[i].getForm();
1907 assert(Form && "Too many attributes for DIE (check abbreviation)");
1909 if (Asm->isVerbose())
1910 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1913 case dwarf::DW_AT_abstract_origin: {
1914 DIEEntry *E = cast<DIEEntry>(Values[i]);
1915 DIE *Origin = E->getEntry();
1916 unsigned Addr = Origin->getOffset();
1917 if (Form == dwarf::DW_FORM_ref_addr) {
1918 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1919 // section. Origin->getOffset() returns the offset from start of the
1921 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1922 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1924 Asm->OutStreamer.EmitIntValue(Addr,
1925 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1928 case dwarf::DW_AT_ranges: {
1929 // DW_AT_range Value encodes offset in debug_range section.
1930 DIEInteger *V = cast<DIEInteger>(Values[i]);
1932 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1933 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1937 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1939 DwarfDebugRangeSectionSym,
1944 case dwarf::DW_AT_location: {
1945 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1946 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1947 Asm->EmitLabelReference(L->getValue(), 4);
1949 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1951 Values[i]->EmitValue(Asm, Form);
1955 case dwarf::DW_AT_accessibility: {
1956 if (Asm->isVerbose()) {
1957 DIEInteger *V = cast<DIEInteger>(Values[i]);
1958 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1960 Values[i]->EmitValue(Asm, Form);
1964 // Emit an attribute using the defined form.
1965 Values[i]->EmitValue(Asm, Form);
1970 // Emit the DIE children if any.
1971 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1972 const std::vector<DIE *> &Children = Die->getChildren();
1974 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1975 emitDIE(Children[j], Abbrevs);
1977 if (Asm->isVerbose())
1978 Asm->OutStreamer.AddComment("End Of Children Mark");
1983 // Emit the various dwarf units to the unit section USection with
1984 // the abbreviations going into ASection.
1985 void DwarfUnits::emitUnits(DwarfDebug *DD,
1986 const MCSection *USection,
1987 const MCSection *ASection,
1988 const MCSymbol *ASectionSym) {
1989 Asm->OutStreamer.SwitchSection(USection);
1990 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1991 E = CUs.end(); I != E; ++I) {
1992 CompileUnit *TheCU = *I;
1993 DIE *Die = TheCU->getCUDie();
1995 // Emit the compile units header.
1997 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1998 TheCU->getUniqueID()));
2000 // Emit size of content not including length itself
2001 unsigned ContentSize = Die->getSize() +
2002 sizeof(int16_t) + // DWARF version number
2003 sizeof(int32_t) + // Offset Into Abbrev. Section
2004 sizeof(int8_t); // Pointer Size (in bytes)
2006 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2007 Asm->EmitInt32(ContentSize);
2008 Asm->OutStreamer.AddComment("DWARF version number");
2009 Asm->EmitInt16(DD->getDwarfVersion());
2010 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2011 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2013 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2014 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2016 DD->emitDIE(Die, Abbreviations);
2017 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2018 TheCU->getUniqueID()));
2022 /// For a given compile unit DIE, returns offset from beginning of debug info.
2023 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2024 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2025 "Input DIE should be compile unit in getCUOffset.");
2026 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2027 E = CUs.end(); I != E; ++I) {
2028 CompileUnit *TheCU = *I;
2029 if (TheCU->getCUDie() == Die)
2030 return TheCU->getDebugInfoOffset();
2032 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2035 // Emit the debug info section.
2036 void DwarfDebug::emitDebugInfo() {
2037 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2039 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2040 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2041 DwarfAbbrevSectionSym);
2044 // Emit the abbreviation section.
2045 void DwarfDebug::emitAbbreviations() {
2046 if (!useSplitDwarf())
2047 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2050 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2053 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2054 std::vector<DIEAbbrev *> *Abbrevs) {
2055 // Check to see if it is worth the effort.
2056 if (!Abbrevs->empty()) {
2057 // Start the debug abbrev section.
2058 Asm->OutStreamer.SwitchSection(Section);
2060 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2061 Asm->OutStreamer.EmitLabel(Begin);
2063 // For each abbrevation.
2064 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2065 // Get abbreviation data
2066 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2068 // Emit the abbrevations code (base 1 index.)
2069 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2071 // Emit the abbreviations data.
2075 // Mark end of abbreviations.
2076 Asm->EmitULEB128(0, "EOM(3)");
2078 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2079 Asm->OutStreamer.EmitLabel(End);
2083 // Emit the last address of the section and the end of the line matrix.
2084 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2085 // Define last address of section.
2086 Asm->OutStreamer.AddComment("Extended Op");
2089 Asm->OutStreamer.AddComment("Op size");
2090 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2091 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2092 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2094 Asm->OutStreamer.AddComment("Section end label");
2096 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2097 Asm->getDataLayout().getPointerSize());
2099 // Mark end of matrix.
2100 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2106 // Emit visible names into a hashed accelerator table section.
2107 void DwarfDebug::emitAccelNames() {
2108 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2109 dwarf::DW_FORM_data4));
2110 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2111 E = CUMap.end(); I != E; ++I) {
2112 CompileUnit *TheCU = I->second;
2113 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2114 for (StringMap<std::vector<DIE*> >::const_iterator
2115 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2116 StringRef Name = GI->getKey();
2117 const std::vector<DIE *> &Entities = GI->second;
2118 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2119 DE = Entities.end(); DI != DE; ++DI)
2120 AT.AddName(Name, (*DI));
2124 AT.FinalizeTable(Asm, "Names");
2125 Asm->OutStreamer.SwitchSection(
2126 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2127 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2128 Asm->OutStreamer.EmitLabel(SectionBegin);
2130 // Emit the full data.
2131 AT.Emit(Asm, SectionBegin, &InfoHolder);
2134 // Emit objective C classes and categories into a hashed accelerator table
2136 void DwarfDebug::emitAccelObjC() {
2137 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2138 dwarf::DW_FORM_data4));
2139 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2140 E = CUMap.end(); I != E; ++I) {
2141 CompileUnit *TheCU = I->second;
2142 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2143 for (StringMap<std::vector<DIE*> >::const_iterator
2144 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2145 StringRef Name = GI->getKey();
2146 const std::vector<DIE *> &Entities = GI->second;
2147 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2148 DE = Entities.end(); DI != DE; ++DI)
2149 AT.AddName(Name, (*DI));
2153 AT.FinalizeTable(Asm, "ObjC");
2154 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2155 .getDwarfAccelObjCSection());
2156 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2157 Asm->OutStreamer.EmitLabel(SectionBegin);
2159 // Emit the full data.
2160 AT.Emit(Asm, SectionBegin, &InfoHolder);
2163 // Emit namespace dies into a hashed accelerator table.
2164 void DwarfDebug::emitAccelNamespaces() {
2165 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2166 dwarf::DW_FORM_data4));
2167 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2168 E = CUMap.end(); I != E; ++I) {
2169 CompileUnit *TheCU = I->second;
2170 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2171 for (StringMap<std::vector<DIE*> >::const_iterator
2172 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2173 StringRef Name = GI->getKey();
2174 const std::vector<DIE *> &Entities = GI->second;
2175 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2176 DE = Entities.end(); DI != DE; ++DI)
2177 AT.AddName(Name, (*DI));
2181 AT.FinalizeTable(Asm, "namespac");
2182 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2183 .getDwarfAccelNamespaceSection());
2184 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2185 Asm->OutStreamer.EmitLabel(SectionBegin);
2187 // Emit the full data.
2188 AT.Emit(Asm, SectionBegin, &InfoHolder);
2191 // Emit type dies into a hashed accelerator table.
2192 void DwarfDebug::emitAccelTypes() {
2193 std::vector<DwarfAccelTable::Atom> Atoms;
2194 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2195 dwarf::DW_FORM_data4));
2196 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2197 dwarf::DW_FORM_data2));
2198 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2199 dwarf::DW_FORM_data1));
2200 DwarfAccelTable AT(Atoms);
2201 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2202 E = CUMap.end(); I != E; ++I) {
2203 CompileUnit *TheCU = I->second;
2204 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2205 = TheCU->getAccelTypes();
2206 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2207 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2208 StringRef Name = GI->getKey();
2209 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2210 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2211 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2212 AT.AddName(Name, (*DI).first, (*DI).second);
2216 AT.FinalizeTable(Asm, "types");
2217 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2218 .getDwarfAccelTypesSection());
2219 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2220 Asm->OutStreamer.EmitLabel(SectionBegin);
2222 // Emit the full data.
2223 AT.Emit(Asm, SectionBegin, &InfoHolder);
2226 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2228 void DwarfDebug::emitDebugPubnames() {
2229 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2231 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2232 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2233 CompileUnit *TheCU = I->second;
2234 unsigned ID = TheCU->getUniqueID();
2236 if (TheCU->getGlobalNames().empty())
2239 // Start the dwarf pubnames section.
2240 Asm->OutStreamer.SwitchSection(
2241 Asm->getObjFileLowering().getDwarfPubNamesSection());
2243 Asm->OutStreamer.AddComment("Length of Public Names Info");
2244 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2245 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2247 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2249 Asm->OutStreamer.AddComment("DWARF Version");
2250 Asm->EmitInt16(DwarfVersion);
2252 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2253 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2254 DwarfInfoSectionSym);
2256 Asm->OutStreamer.AddComment("Compilation Unit Length");
2257 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2258 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2261 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2262 for (StringMap<DIE*>::const_iterator
2263 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2264 const char *Name = GI->getKeyData();
2265 const DIE *Entity = GI->second;
2267 Asm->OutStreamer.AddComment("DIE offset");
2268 Asm->EmitInt32(Entity->getOffset());
2270 if (Asm->isVerbose())
2271 Asm->OutStreamer.AddComment("External Name");
2272 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2275 Asm->OutStreamer.AddComment("End Mark");
2277 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2281 void DwarfDebug::emitDebugPubTypes() {
2282 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2283 E = CUMap.end(); I != E; ++I) {
2284 CompileUnit *TheCU = I->second;
2285 // Start the dwarf pubtypes section.
2286 Asm->OutStreamer.SwitchSection(
2287 Asm->getObjFileLowering().getDwarfPubTypesSection());
2288 Asm->OutStreamer.AddComment("Length of Public Types Info");
2289 Asm->EmitLabelDifference(
2290 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2291 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2293 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2294 TheCU->getUniqueID()));
2296 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2297 Asm->EmitInt16(DwarfVersion);
2299 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2300 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2301 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2302 TheCU->getUniqueID()),
2303 DwarfInfoSectionSym);
2305 Asm->OutStreamer.AddComment("Compilation Unit Length");
2306 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2307 TheCU->getUniqueID()),
2308 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2309 TheCU->getUniqueID()),
2312 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2313 for (StringMap<DIE*>::const_iterator
2314 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2315 const char *Name = GI->getKeyData();
2316 DIE *Entity = GI->second;
2318 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2319 Asm->EmitInt32(Entity->getOffset());
2321 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2322 // Emit the name with a terminating null byte.
2323 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2326 Asm->OutStreamer.AddComment("End Mark");
2328 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2329 TheCU->getUniqueID()));
2333 // Emit strings into a string section.
2334 void DwarfUnits::emitStrings(const MCSection *StrSection,
2335 const MCSection *OffsetSection = NULL,
2336 const MCSymbol *StrSecSym = NULL) {
2338 if (StringPool.empty()) return;
2340 // Start the dwarf str section.
2341 Asm->OutStreamer.SwitchSection(StrSection);
2343 // Get all of the string pool entries and put them in an array by their ID so
2344 // we can sort them.
2345 SmallVector<std::pair<unsigned,
2346 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2348 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2349 I = StringPool.begin(), E = StringPool.end();
2351 Entries.push_back(std::make_pair(I->second.second, &*I));
2353 array_pod_sort(Entries.begin(), Entries.end());
2355 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2356 // Emit a label for reference from debug information entries.
2357 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2359 // Emit the string itself with a terminating null byte.
2360 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2361 Entries[i].second->getKeyLength()+1));
2364 // If we've got an offset section go ahead and emit that now as well.
2365 if (OffsetSection) {
2366 Asm->OutStreamer.SwitchSection(OffsetSection);
2367 unsigned offset = 0;
2368 unsigned size = 4; // FIXME: DWARF64 is 8.
2369 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2370 Asm->OutStreamer.EmitIntValue(offset, size);
2371 offset += Entries[i].second->getKeyLength() + 1;
2376 // Emit strings into a string section.
2377 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2379 if (AddressPool.empty()) return;
2381 // Start the dwarf addr section.
2382 Asm->OutStreamer.SwitchSection(AddrSection);
2384 // Get all of the address pool entries and put them in an array by their ID so
2385 // we can sort them.
2386 SmallVector<std::pair<unsigned, const MCExpr *>, 64> Entries;
2388 for (DenseMap<const MCExpr *, unsigned>::iterator
2389 I = AddressPool.begin(),
2390 E = AddressPool.end();
2392 Entries.push_back(std::make_pair(I->second, I->first));
2394 array_pod_sort(Entries.begin(), Entries.end());
2396 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2397 // Emit an expression for reference from debug information entries.
2398 if (const MCExpr *Expr = Entries[i].second)
2399 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2401 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2406 // Emit visible names into a debug str section.
2407 void DwarfDebug::emitDebugStr() {
2408 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2409 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2412 // Emit locations into the debug loc section.
2413 void DwarfDebug::emitDebugLoc() {
2414 if (DotDebugLocEntries.empty())
2417 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2418 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2420 DotDebugLocEntry &Entry = *I;
2421 if (I + 1 != DotDebugLocEntries.end())
2425 // Start the dwarf loc section.
2426 Asm->OutStreamer.SwitchSection(
2427 Asm->getObjFileLowering().getDwarfLocSection());
2428 unsigned char Size = Asm->getDataLayout().getPointerSize();
2429 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2431 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2432 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2433 I != E; ++I, ++index) {
2434 DotDebugLocEntry &Entry = *I;
2435 if (Entry.isMerged()) continue;
2436 if (Entry.isEmpty()) {
2437 Asm->OutStreamer.EmitIntValue(0, Size);
2438 Asm->OutStreamer.EmitIntValue(0, Size);
2439 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2441 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2442 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2443 DIVariable DV(Entry.Variable);
2444 Asm->OutStreamer.AddComment("Loc expr size");
2445 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2446 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2447 Asm->EmitLabelDifference(end, begin, 2);
2448 Asm->OutStreamer.EmitLabel(begin);
2449 if (Entry.isInt()) {
2450 DIBasicType BTy(DV.getType());
2452 (BTy.getEncoding() == dwarf::DW_ATE_signed
2453 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2454 Asm->OutStreamer.AddComment("DW_OP_consts");
2455 Asm->EmitInt8(dwarf::DW_OP_consts);
2456 Asm->EmitSLEB128(Entry.getInt());
2458 Asm->OutStreamer.AddComment("DW_OP_constu");
2459 Asm->EmitInt8(dwarf::DW_OP_constu);
2460 Asm->EmitULEB128(Entry.getInt());
2462 } else if (Entry.isLocation()) {
2463 if (!DV.hasComplexAddress())
2465 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2467 // Complex address entry.
2468 unsigned N = DV.getNumAddrElements();
2470 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2471 if (Entry.Loc.getOffset()) {
2473 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2474 Asm->OutStreamer.AddComment("DW_OP_deref");
2475 Asm->EmitInt8(dwarf::DW_OP_deref);
2476 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2477 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2478 Asm->EmitSLEB128(DV.getAddrElement(1));
2480 // If first address element is OpPlus then emit
2481 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2482 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2483 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2487 Asm->EmitDwarfRegOp(Entry.Loc, DV.isIndirect());
2490 // Emit remaining complex address elements.
2491 for (; i < N; ++i) {
2492 uint64_t Element = DV.getAddrElement(i);
2493 if (Element == DIBuilder::OpPlus) {
2494 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2495 Asm->EmitULEB128(DV.getAddrElement(++i));
2496 } else if (Element == DIBuilder::OpDeref) {
2497 if (!Entry.Loc.isReg())
2498 Asm->EmitInt8(dwarf::DW_OP_deref);
2500 llvm_unreachable("unknown Opcode found in complex address");
2504 // else ... ignore constant fp. There is not any good way to
2505 // to represent them here in dwarf.
2506 Asm->OutStreamer.EmitLabel(end);
2511 // Emit visible names into a debug aranges section.
2512 void DwarfDebug::emitDebugARanges() {
2513 // Start the dwarf aranges section.
2514 Asm->OutStreamer.SwitchSection(
2515 Asm->getObjFileLowering().getDwarfARangesSection());
2518 // Emit visible names into a debug ranges section.
2519 void DwarfDebug::emitDebugRanges() {
2520 // Start the dwarf ranges section.
2521 Asm->OutStreamer.SwitchSection(
2522 Asm->getObjFileLowering().getDwarfRangesSection());
2523 unsigned char Size = Asm->getDataLayout().getPointerSize();
2524 for (SmallVectorImpl<const MCSymbol *>::iterator
2525 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2528 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2530 Asm->OutStreamer.EmitIntValue(0, Size);
2534 // Emit visible names into a debug macinfo section.
2535 void DwarfDebug::emitDebugMacInfo() {
2536 if (const MCSection *LineInfo =
2537 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2538 // Start the dwarf macinfo section.
2539 Asm->OutStreamer.SwitchSection(LineInfo);
2543 // Emit inline info using following format.
2545 // 1. length of section
2546 // 2. Dwarf version number
2549 // Entries (one "entry" for each function that was inlined):
2551 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2552 // otherwise offset into __debug_str for regular function name.
2553 // 2. offset into __debug_str section for regular function name.
2554 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2555 // instances for the function.
2557 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2558 // inlined instance; the die_offset points to the inlined_subroutine die in the
2559 // __debug_info section, and the low_pc is the starting address for the
2560 // inlining instance.
2561 void DwarfDebug::emitDebugInlineInfo() {
2562 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2568 Asm->OutStreamer.SwitchSection(
2569 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2571 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2572 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2573 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2575 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2577 Asm->OutStreamer.AddComment("Dwarf Version");
2578 Asm->EmitInt16(DwarfVersion);
2579 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2580 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2582 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2583 E = InlinedSPNodes.end(); I != E; ++I) {
2585 const MDNode *Node = *I;
2586 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2587 = InlineInfo.find(Node);
2588 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2589 DISubprogram SP(Node);
2590 StringRef LName = SP.getLinkageName();
2591 StringRef Name = SP.getName();
2593 Asm->OutStreamer.AddComment("MIPS linkage name");
2595 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2596 DwarfStrSectionSym);
2598 Asm->EmitSectionOffset(
2599 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2600 DwarfStrSectionSym);
2602 Asm->OutStreamer.AddComment("Function name");
2603 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2604 DwarfStrSectionSym);
2605 Asm->EmitULEB128(Labels.size(), "Inline count");
2607 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2608 LE = Labels.end(); LI != LE; ++LI) {
2609 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2610 Asm->EmitInt32(LI->second->getOffset());
2612 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2613 Asm->OutStreamer.EmitSymbolValue(LI->first,
2614 Asm->getDataLayout().getPointerSize());
2618 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2621 // DWARF5 Experimental Separate Dwarf emitters.
2623 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2624 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2625 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2626 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2627 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2628 DICompileUnit DIUnit(N);
2629 CompilationDir = DIUnit.getDirectory();
2631 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2632 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2633 DIUnit.getLanguage(), Die, N, Asm,
2634 this, &SkeletonHolder);
2636 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2637 DIUnit.getSplitDebugFilename());
2639 // This should be a unique identifier when we want to build .dwp files.
2640 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2642 // Relocate to the beginning of the addr_base section, else 0 for the
2643 // beginning of the one for this compile unit.
2644 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2645 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2646 DwarfAddrSectionSym);
2648 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2649 dwarf::DW_FORM_sec_offset, 0);
2651 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2652 // into an entity. We're using 0, or a NULL label for this.
2653 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2655 // DW_AT_stmt_list is a offset of line number information for this
2656 // compile unit in debug_line section.
2657 // FIXME: Should handle multiple compile units.
2658 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2659 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2660 DwarfLineSectionSym);
2662 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2664 if (!CompilationDir.empty())
2665 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2667 SkeletonHolder.addUnit(NewCU);
2668 SkeletonCUs.push_back(NewCU);
2673 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2674 assert(useSplitDwarf() && "No split dwarf debug info?");
2675 emitAbbrevs(Section, &SkeletonAbbrevs);
2678 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2679 // compile units that would normally be in debug_info.
2680 void DwarfDebug::emitDebugInfoDWO() {
2681 assert(useSplitDwarf() && "No split dwarf debug info?");
2682 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2683 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2684 DwarfAbbrevDWOSectionSym);
2687 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2688 // abbreviations for the .debug_info.dwo section.
2689 void DwarfDebug::emitDebugAbbrevDWO() {
2690 assert(useSplitDwarf() && "No split dwarf?");
2691 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2695 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2696 // string section and is identical in format to traditional .debug_str
2698 void DwarfDebug::emitDebugStrDWO() {
2699 assert(useSplitDwarf() && "No split dwarf?");
2700 const MCSection *OffSec = Asm->getObjFileLowering()
2701 .getDwarfStrOffDWOSection();
2702 const MCSymbol *StrSym = DwarfStrSectionSym;
2703 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),