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 SmallVectorImpl<InsnRange> &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 (SmallVectorImpl<InsnRange>::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 SmallVectorImpl<InsnRange>::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 SmallVectorImpl<InsnRange> &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 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
501 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
502 dwarf::DW_FORM_ref4, OriginDIE);
504 if (Ranges.size() > 1) {
505 // .debug_range section has not been laid out yet. Emit offset in
506 // .debug_range as a uint, size 4, for now. emitDIE will handle
507 // DW_AT_ranges appropriately.
508 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
509 DebugRangeSymbols.size()
510 * Asm->getDataLayout().getPointerSize());
511 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
512 RE = Ranges.end(); RI != RE; ++RI) {
513 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
514 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
516 DebugRangeSymbols.push_back(NULL);
517 DebugRangeSymbols.push_back(NULL);
519 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
520 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
521 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
523 if (StartLabel == 0 || EndLabel == 0)
524 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
526 assert(StartLabel->isDefined() &&
527 "Invalid starting label for an inlined scope!");
528 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
530 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
531 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
534 InlinedSubprogramDIEs.insert(OriginDIE);
536 // Add the call site information to the DIE.
537 DILocation DL(Scope->getInlinedAt());
538 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
539 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
540 TheCU->getUniqueID()));
541 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
543 // Track the start label for this inlined function.
544 //.debug_inlined section specification does not clearly state how
545 // to emit inlined scopes that are split into multiple instruction ranges.
546 // For now, use the first instruction range and emit low_pc/high_pc pair and
547 // corresponding the .debug_inlined section entry for this pair.
548 if (Asm->MAI->doesDwarfUseInlineInfoSection()) {
549 MCSymbol *StartLabel = getLabelBeforeInsn(Ranges.begin()->first);
550 InlineInfoMap::iterator I = InlineInfo.find(InlinedSP);
552 if (I == InlineInfo.end()) {
553 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
554 InlinedSPNodes.push_back(InlinedSP);
556 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
559 // Add name to the name table, we do this here because we're guaranteed
560 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
561 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
566 // Construct a DIE for this scope.
567 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
568 if (!Scope || !Scope->getScopeNode())
571 DIScope DS(Scope->getScopeNode());
572 // Early return to avoid creating dangling variable|scope DIEs.
573 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
577 SmallVector<DIE *, 8> Children;
578 DIE *ObjectPointer = NULL;
580 // Collect arguments for current function.
581 if (LScopes.isCurrentFunctionScope(Scope))
582 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
583 if (DbgVariable *ArgDV = CurrentFnArguments[i])
585 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
586 Children.push_back(Arg);
587 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
590 // Collect lexical scope children first.
591 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
592 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
594 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
595 Children.push_back(Variable);
596 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
598 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
599 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
600 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
601 Children.push_back(Nested);
602 DIE *ScopeDIE = NULL;
603 if (Scope->getInlinedAt())
604 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
605 else if (DS.isSubprogram()) {
606 ProcessedSPNodes.insert(DS);
607 if (Scope->isAbstractScope()) {
608 ScopeDIE = TheCU->getDIE(DS);
609 // Note down abstract DIE.
611 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
614 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
617 // There is no need to emit empty lexical block DIE.
618 std::pair<ImportedEntityMap::const_iterator,
619 ImportedEntityMap::const_iterator> Range = std::equal_range(
620 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
621 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
623 if (Children.empty() && Range.first == Range.second)
625 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
626 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
628 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
631 if (!ScopeDIE) return NULL;
634 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
635 E = Children.end(); I != E; ++I)
636 ScopeDIE->addChild(*I);
638 if (DS.isSubprogram() && ObjectPointer != NULL)
639 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
640 dwarf::DW_FORM_ref4, ObjectPointer);
642 if (DS.isSubprogram())
643 TheCU->addPubTypes(DISubprogram(DS));
648 // Look up the source id with the given directory and source file names.
649 // If none currently exists, create a new id and insert it in the
650 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
652 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
653 StringRef DirName, unsigned CUID) {
654 // If we use .loc in assembly, we can't separate .file entries according to
655 // compile units. Thus all files will belong to the default compile unit.
656 if (Asm->TM.hasMCUseLoc() &&
657 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
660 // If FE did not provide a file name, then assume stdin.
661 if (FileName.empty())
662 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
664 // TODO: this might not belong here. See if we can factor this better.
665 if (DirName == CompilationDir)
668 // FileIDCUMap stores the current ID for the given compile unit.
669 unsigned SrcId = FileIDCUMap[CUID] + 1;
671 // We look up the CUID/file/dir by concatenating them with a zero byte.
672 SmallString<128> NamePair;
673 NamePair += utostr(CUID);
676 NamePair += '\0'; // Zero bytes are not allowed in paths.
677 NamePair += FileName;
679 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
680 if (Ent.getValue() != SrcId)
681 return Ent.getValue();
683 FileIDCUMap[CUID] = SrcId;
684 // Print out a .file directive to specify files for .loc directives.
685 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
690 // Create new CompileUnit for the given metadata node with tag
691 // DW_TAG_compile_unit.
692 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
693 DICompileUnit DIUnit(N);
694 StringRef FN = DIUnit.getFilename();
695 CompilationDir = DIUnit.getDirectory();
697 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
698 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
699 DIUnit.getLanguage(), Die, N, Asm,
702 FileIDCUMap[NewCU->getUniqueID()] = 0;
703 // Call this to emit a .file directive if it wasn't emitted for the source
704 // file this CU comes from yet.
705 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
707 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
708 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
709 DIUnit.getLanguage());
710 NewCU->addString(Die, dwarf::DW_AT_name, FN);
712 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
713 // into an entity. We're using 0 (or a NULL label) for this. For
714 // split dwarf it's in the skeleton CU so omit it here.
715 if (!useSplitDwarf())
716 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
718 // Define start line table label for each Compile Unit.
719 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
720 NewCU->getUniqueID());
721 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
722 NewCU->getUniqueID());
724 // Use a single line table if we are using .loc and generating assembly.
726 (Asm->TM.hasMCUseLoc() &&
727 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
728 (NewCU->getUniqueID() == 0);
730 // DW_AT_stmt_list is a offset of line number information for this
731 // compile unit in debug_line section. For split dwarf this is
732 // left in the skeleton CU and so not included.
733 // The line table entries are not always emitted in assembly, so it
734 // is not okay to use line_table_start here.
735 if (!useSplitDwarf()) {
736 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
737 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
739 Asm->GetTempSymbol("section_line") : LineTableStartSym);
740 else if (UseTheFirstCU)
741 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
743 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
744 LineTableStartSym, DwarfLineSectionSym);
747 // If we're using split dwarf the compilation dir is going to be in the
748 // skeleton CU and so we don't need to duplicate it here.
749 if (!useSplitDwarf() && !CompilationDir.empty())
750 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
751 if (DIUnit.isOptimized())
752 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
754 StringRef Flags = DIUnit.getFlags();
756 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
758 if (unsigned RVer = DIUnit.getRunTimeVersion())
759 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
760 dwarf::DW_FORM_data1, RVer);
765 InfoHolder.addUnit(NewCU);
767 CUMap.insert(std::make_pair(N, NewCU));
771 // Construct subprogram DIE.
772 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
774 CompileUnit *&CURef = SPMap[N];
780 if (!SP.isDefinition())
781 // This is a method declaration which will be handled while constructing
785 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
788 TheCU->insertDIE(N, SubprogramDie);
790 // Add to context owner.
791 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
793 // Expose as global, if requested.
794 if (GenerateDwarfPubNamesSection)
795 TheCU->addGlobalName(SP.getName(), SubprogramDie);
798 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
800 DIImportedEntity Module(N);
801 if (!Module.Verify())
803 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
804 constructImportedEntityDIE(TheCU, Module, D);
807 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
809 DIImportedEntity Module(N);
810 if (!Module.Verify())
812 return constructImportedEntityDIE(TheCU, Module, Context);
815 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
816 const DIImportedEntity &Module,
818 assert(Module.Verify() &&
819 "Use one of the MDNode * overloads to handle invalid metadata");
820 assert(Context && "Should always have a context for an imported_module");
821 DIE *IMDie = new DIE(Module.getTag());
822 TheCU->insertDIE(Module, IMDie);
824 DIDescriptor Entity = Module.getEntity();
825 if (Entity.isNameSpace())
826 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
827 else if (Entity.isSubprogram())
828 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
829 else if (Entity.isType())
830 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
832 EntityDie = TheCU->getDIE(Entity);
833 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
834 Module.getContext().getDirectory(),
835 TheCU->getUniqueID());
836 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
837 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
838 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
840 StringRef Name = Module.getName();
842 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
843 Context->addChild(IMDie);
846 // Emit all Dwarf sections that should come prior to the content. Create
847 // global DIEs and emit initial debug info sections. This is invoked by
848 // the target AsmPrinter.
849 void DwarfDebug::beginModule() {
850 if (DisableDebugInfoPrinting)
853 const Module *M = MMI->getModule();
855 // If module has named metadata anchors then use them, otherwise scan the
856 // module using debug info finder to collect debug info.
857 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
861 // Emit initial sections so we can reference labels later.
864 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
865 DICompileUnit CUNode(CU_Nodes->getOperand(i));
866 CompileUnit *CU = constructCompileUnit(CUNode);
867 DIArray ImportedEntities = CUNode.getImportedEntities();
868 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
869 ScopesWithImportedEntities.push_back(std::make_pair(
870 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
871 ImportedEntities.getElement(i)));
872 std::sort(ScopesWithImportedEntities.begin(),
873 ScopesWithImportedEntities.end(), CompareFirst());
874 DIArray GVs = CUNode.getGlobalVariables();
875 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
876 CU->createGlobalVariableDIE(GVs.getElement(i));
877 DIArray SPs = CUNode.getSubprograms();
878 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
879 constructSubprogramDIE(CU, SPs.getElement(i));
880 DIArray EnumTypes = CUNode.getEnumTypes();
881 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
882 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
883 DIArray RetainedTypes = CUNode.getRetainedTypes();
884 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
885 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
886 // Emit imported_modules last so that the relevant context is already
888 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
889 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
890 // If we're splitting the dwarf out now that we've got the entire
891 // CU then construct a skeleton CU based upon it.
892 if (useSplitDwarf()) {
893 // This should be a unique identifier when we want to build .dwp files.
894 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
895 dwarf::DW_FORM_data8, 0);
896 // Now construct the skeleton CU associated.
897 constructSkeletonCU(CUNode);
901 // Tell MMI that we have debug info.
902 MMI->setDebugInfoAvailability(true);
904 // Prime section data.
905 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
908 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
909 void DwarfDebug::computeInlinedDIEs() {
910 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
911 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
912 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
914 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
916 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
917 AE = AbstractSPDies.end(); AI != AE; ++AI) {
918 DIE *ISP = AI->second;
919 if (InlinedSubprogramDIEs.count(ISP))
921 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
925 // Collect info for variables that were optimized out.
926 void DwarfDebug::collectDeadVariables() {
927 const Module *M = MMI->getModule();
928 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
930 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
931 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
932 DICompileUnit TheCU(CU_Nodes->getOperand(i));
933 DIArray Subprograms = TheCU.getSubprograms();
934 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
935 DISubprogram SP(Subprograms.getElement(i));
936 if (ProcessedSPNodes.count(SP) != 0) continue;
937 if (!SP.isSubprogram()) continue;
938 if (!SP.isDefinition()) continue;
939 DIArray Variables = SP.getVariables();
940 if (Variables.getNumElements() == 0) continue;
942 LexicalScope *Scope =
943 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
944 DeadFnScopeMap[SP] = Scope;
946 // Construct subprogram DIE and add variables DIEs.
947 CompileUnit *SPCU = CUMap.lookup(TheCU);
948 assert(SPCU && "Unable to find Compile Unit!");
949 constructSubprogramDIE(SPCU, SP);
950 DIE *ScopeDIE = SPCU->getDIE(SP);
951 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
952 DIVariable DV(Variables.getElement(vi));
953 if (!DV.isVariable()) continue;
954 DbgVariable *NewVar = new DbgVariable(DV, NULL);
955 if (DIE *VariableDIE =
956 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
957 ScopeDIE->addChild(VariableDIE);
962 DeleteContainerSeconds(DeadFnScopeMap);
965 void DwarfDebug::finalizeModuleInfo() {
966 // Collect info for variables that were optimized out.
967 collectDeadVariables();
969 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
970 computeInlinedDIEs();
972 // Emit DW_AT_containing_type attribute to connect types with their
973 // vtable holding type.
974 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
975 CUE = CUMap.end(); CUI != CUE; ++CUI) {
976 CompileUnit *TheCU = CUI->second;
977 TheCU->constructContainingTypeDIEs();
980 // Compute DIE offsets and sizes.
981 InfoHolder.computeSizeAndOffsets();
983 SkeletonHolder.computeSizeAndOffsets();
986 void DwarfDebug::endSections() {
987 // Standard sections final addresses.
988 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
989 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
990 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
991 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
993 // End text sections.
994 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
995 Asm->OutStreamer.SwitchSection(SectionMap[I]);
996 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1000 // Emit all Dwarf sections that should come after the content.
1001 void DwarfDebug::endModule() {
1003 if (!FirstCU) return;
1005 // End any existing sections.
1006 // TODO: Does this need to happen?
1009 // Finalize the debug info for the module.
1010 finalizeModuleInfo();
1012 if (!useSplitDwarf()) {
1013 // Emit all the DIEs into a debug info section.
1016 // Corresponding abbreviations into a abbrev section.
1017 emitAbbreviations();
1019 // Emit info into a debug loc section.
1022 // Emit info into a debug aranges section.
1025 // Emit info into a debug ranges section.
1028 // Emit info into a debug macinfo section.
1031 // Emit inline info.
1032 // TODO: When we don't need the option anymore we
1033 // can remove all of the code that this section
1035 if (useDarwinGDBCompat())
1036 emitDebugInlineInfo();
1038 // TODO: Fill this in for separated debug sections and separate
1039 // out information into new sections.
1041 // Emit the debug info section and compile units.
1045 // Corresponding abbreviations into a abbrev section.
1046 emitAbbreviations();
1047 emitDebugAbbrevDWO();
1049 // Emit info into a debug loc section.
1052 // Emit info into a debug aranges section.
1055 // Emit info into a debug ranges section.
1058 // Emit info into a debug macinfo section.
1061 // Emit DWO addresses.
1062 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1064 // Emit inline info.
1065 // TODO: When we don't need the option anymore we
1066 // can remove all of the code that this section
1068 if (useDarwinGDBCompat())
1069 emitDebugInlineInfo();
1072 // Emit info into the dwarf accelerator table sections.
1073 if (useDwarfAccelTables()) {
1076 emitAccelNamespaces();
1080 // Emit info into a debug pubnames section, if requested.
1081 if (GenerateDwarfPubNamesSection)
1082 emitDebugPubnames();
1084 // Emit info into a debug pubtypes section.
1085 // TODO: When we don't need the option anymore we can
1086 // remove all of the code that adds to the table.
1087 if (useDarwinGDBCompat())
1088 emitDebugPubTypes();
1090 // Finally emit string information into a string table.
1092 if (useSplitDwarf())
1097 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1098 E = CUMap.end(); I != E; ++I)
1101 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1102 E = SkeletonCUs.end(); I != E; ++I)
1105 // Reset these for the next Module if we have one.
1109 // Find abstract variable, if any, associated with Var.
1110 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1111 DebugLoc ScopeLoc) {
1112 LLVMContext &Ctx = DV->getContext();
1113 // More then one inlined variable corresponds to one abstract variable.
1114 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1115 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1117 return AbsDbgVariable;
1119 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1123 AbsDbgVariable = new DbgVariable(Var, NULL);
1124 addScopeVariable(Scope, AbsDbgVariable);
1125 AbstractVariables[Var] = AbsDbgVariable;
1126 return AbsDbgVariable;
1129 // If Var is a current function argument then add it to CurrentFnArguments list.
1130 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1131 DbgVariable *Var, LexicalScope *Scope) {
1132 if (!LScopes.isCurrentFunctionScope(Scope))
1134 DIVariable DV = Var->getVariable();
1135 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1137 unsigned ArgNo = DV.getArgNumber();
1141 size_t Size = CurrentFnArguments.size();
1143 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1144 // llvm::Function argument size is not good indicator of how many
1145 // arguments does the function have at source level.
1147 CurrentFnArguments.resize(ArgNo * 2);
1148 CurrentFnArguments[ArgNo - 1] = Var;
1152 // Collect variable information from side table maintained by MMI.
1154 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1155 SmallPtrSet<const MDNode *, 16> &Processed) {
1156 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1157 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1158 VE = VMap.end(); VI != VE; ++VI) {
1159 const MDNode *Var = VI->first;
1161 Processed.insert(Var);
1163 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1165 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1167 // If variable scope is not found then skip this variable.
1171 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1172 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1173 RegVar->setFrameIndex(VP.first);
1174 if (!addCurrentFnArgument(MF, RegVar, Scope))
1175 addScopeVariable(Scope, RegVar);
1177 AbsDbgVariable->setFrameIndex(VP.first);
1181 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1183 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1184 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1185 return MI->getNumOperands() == 3 &&
1186 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1187 (MI->getOperand(1).isImm() ||
1188 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1191 // Get .debug_loc entry for the instruction range starting at MI.
1192 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1193 const MCSymbol *FLabel,
1194 const MCSymbol *SLabel,
1195 const MachineInstr *MI) {
1196 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1198 assert(MI->getNumOperands() == 3);
1199 if (MI->getOperand(0).isReg()) {
1200 MachineLocation MLoc;
1201 // If the second operand is an immediate, this is a
1202 // register-indirect address.
1203 if (!MI->getOperand(1).isImm())
1204 MLoc.set(MI->getOperand(0).getReg());
1206 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1207 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1209 if (MI->getOperand(0).isImm())
1210 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1211 if (MI->getOperand(0).isFPImm())
1212 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1213 if (MI->getOperand(0).isCImm())
1214 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1216 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1219 // Find variables for each lexical scope.
1221 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1222 SmallPtrSet<const MDNode *, 16> &Processed) {
1224 // Grab the variable info that was squirreled away in the MMI side-table.
1225 collectVariableInfoFromMMITable(MF, Processed);
1227 for (SmallVectorImpl<const MDNode*>::const_iterator
1228 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1230 const MDNode *Var = *UVI;
1231 if (Processed.count(Var))
1234 // History contains relevant DBG_VALUE instructions for Var and instructions
1236 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1237 if (History.empty())
1239 const MachineInstr *MInsn = History.front();
1242 LexicalScope *Scope = NULL;
1243 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1244 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1245 Scope = LScopes.getCurrentFunctionScope();
1246 else if (MDNode *IA = DV.getInlinedAt())
1247 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1249 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1250 // If variable scope is not found then skip this variable.
1254 Processed.insert(DV);
1255 assert(MInsn->isDebugValue() && "History must begin with debug value");
1256 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1257 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1258 if (!addCurrentFnArgument(MF, RegVar, Scope))
1259 addScopeVariable(Scope, RegVar);
1261 AbsVar->setMInsn(MInsn);
1263 // Simplify ranges that are fully coalesced.
1264 if (History.size() <= 1 || (History.size() == 2 &&
1265 MInsn->isIdenticalTo(History.back()))) {
1266 RegVar->setMInsn(MInsn);
1270 // Handle multiple DBG_VALUE instructions describing one variable.
1271 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1273 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1274 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1275 const MachineInstr *Begin = *HI;
1276 assert(Begin->isDebugValue() && "Invalid History entry");
1278 // Check if DBG_VALUE is truncating a range.
1279 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1280 && !Begin->getOperand(0).getReg())
1283 // Compute the range for a register location.
1284 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1285 const MCSymbol *SLabel = 0;
1288 // If Begin is the last instruction in History then its value is valid
1289 // until the end of the function.
1290 SLabel = FunctionEndSym;
1292 const MachineInstr *End = HI[1];
1293 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1294 << "\t" << *Begin << "\t" << *End << "\n");
1295 if (End->isDebugValue())
1296 SLabel = getLabelBeforeInsn(End);
1298 // End is a normal instruction clobbering the range.
1299 SLabel = getLabelAfterInsn(End);
1300 assert(SLabel && "Forgot label after clobber instruction");
1305 // The value is valid until the next DBG_VALUE or clobber.
1306 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1309 DotDebugLocEntries.push_back(DotDebugLocEntry());
1312 // Collect info for variables that were optimized out.
1313 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1314 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1315 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1316 DIVariable DV(Variables.getElement(i));
1317 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1319 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1320 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1324 // Return Label preceding the instruction.
1325 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1326 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1327 assert(Label && "Didn't insert label before instruction");
1331 // Return Label immediately following the instruction.
1332 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1333 return LabelsAfterInsn.lookup(MI);
1336 // Process beginning of an instruction.
1337 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1338 // Check if source location changes, but ignore DBG_VALUE locations.
1339 if (!MI->isDebugValue()) {
1340 DebugLoc DL = MI->getDebugLoc();
1341 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1344 if (DL == PrologEndLoc) {
1345 Flags |= DWARF2_FLAG_PROLOGUE_END;
1346 PrologEndLoc = DebugLoc();
1348 if (PrologEndLoc.isUnknown())
1349 Flags |= DWARF2_FLAG_IS_STMT;
1351 if (!DL.isUnknown()) {
1352 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1353 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1355 recordSourceLine(0, 0, 0, 0);
1359 // Insert labels where requested.
1360 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1361 LabelsBeforeInsn.find(MI);
1364 if (I == LabelsBeforeInsn.end())
1367 // Label already assigned.
1372 PrevLabel = MMI->getContext().CreateTempSymbol();
1373 Asm->OutStreamer.EmitLabel(PrevLabel);
1375 I->second = PrevLabel;
1378 // Process end of an instruction.
1379 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1380 // Don't create a new label after DBG_VALUE instructions.
1381 // They don't generate code.
1382 if (!MI->isDebugValue())
1385 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1386 LabelsAfterInsn.find(MI);
1389 if (I == LabelsAfterInsn.end())
1392 // Label already assigned.
1396 // We need a label after this instruction.
1398 PrevLabel = MMI->getContext().CreateTempSymbol();
1399 Asm->OutStreamer.EmitLabel(PrevLabel);
1401 I->second = PrevLabel;
1404 // Each LexicalScope has first instruction and last instruction to mark
1405 // beginning and end of a scope respectively. Create an inverse map that list
1406 // scopes starts (and ends) with an instruction. One instruction may start (or
1407 // end) multiple scopes. Ignore scopes that are not reachable.
1408 void DwarfDebug::identifyScopeMarkers() {
1409 SmallVector<LexicalScope *, 4> WorkList;
1410 WorkList.push_back(LScopes.getCurrentFunctionScope());
1411 while (!WorkList.empty()) {
1412 LexicalScope *S = WorkList.pop_back_val();
1414 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1415 if (!Children.empty())
1416 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1417 SE = Children.end(); SI != SE; ++SI)
1418 WorkList.push_back(*SI);
1420 if (S->isAbstractScope())
1423 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1426 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1427 RE = Ranges.end(); RI != RE; ++RI) {
1428 assert(RI->first && "InsnRange does not have first instruction!");
1429 assert(RI->second && "InsnRange does not have second instruction!");
1430 requestLabelBeforeInsn(RI->first);
1431 requestLabelAfterInsn(RI->second);
1436 // Get MDNode for DebugLoc's scope.
1437 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1438 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1439 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1440 return DL.getScope(Ctx);
1443 // Walk up the scope chain of given debug loc and find line number info
1444 // for the function.
1445 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1446 const MDNode *Scope = getScopeNode(DL, Ctx);
1447 DISubprogram SP = getDISubprogram(Scope);
1448 if (SP.isSubprogram()) {
1449 // Check for number of operands since the compatibility is
1451 if (SP->getNumOperands() > 19)
1452 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1454 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1460 // Gather pre-function debug information. Assumes being called immediately
1461 // after the function entry point has been emitted.
1462 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1463 if (!MMI->hasDebugInfo()) return;
1464 LScopes.initialize(*MF);
1465 if (LScopes.empty()) return;
1466 identifyScopeMarkers();
1468 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1470 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1471 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1472 assert(TheCU && "Unable to find compile unit!");
1473 if (Asm->TM.hasMCUseLoc() &&
1474 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1475 // Use a single line table if we are using .loc and generating assembly.
1476 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1478 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1480 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1481 Asm->getFunctionNumber());
1482 // Assumes in correct section after the entry point.
1483 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1485 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1487 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1488 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1489 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1491 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1493 bool AtBlockEntry = true;
1494 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1496 const MachineInstr *MI = II;
1498 if (MI->isDebugValue()) {
1499 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1501 // Keep track of user variables.
1503 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1505 // Variable is in a register, we need to check for clobbers.
1506 if (isDbgValueInDefinedReg(MI))
1507 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1509 // Check the history of this variable.
1510 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1511 if (History.empty()) {
1512 UserVariables.push_back(Var);
1513 // The first mention of a function argument gets the FunctionBeginSym
1514 // label, so arguments are visible when breaking at function entry.
1516 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1517 DISubprogram(getDISubprogram(DV.getContext()))
1518 .describes(MF->getFunction()))
1519 LabelsBeforeInsn[MI] = FunctionBeginSym;
1521 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1522 const MachineInstr *Prev = History.back();
1523 if (Prev->isDebugValue()) {
1524 // Coalesce identical entries at the end of History.
1525 if (History.size() >= 2 &&
1526 Prev->isIdenticalTo(History[History.size() - 2])) {
1527 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1529 << "\t" << *History[History.size() - 2] << "\n");
1533 // Terminate old register assignments that don't reach MI;
1534 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1535 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1536 isDbgValueInDefinedReg(Prev)) {
1537 // Previous register assignment needs to terminate at the end of
1539 MachineBasicBlock::const_iterator LastMI =
1540 PrevMBB->getLastNonDebugInstr();
1541 if (LastMI == PrevMBB->end()) {
1542 // Drop DBG_VALUE for empty range.
1543 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1544 << "\t" << *Prev << "\n");
1546 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1547 // Terminate after LastMI.
1548 History.push_back(LastMI);
1552 History.push_back(MI);
1554 // Not a DBG_VALUE instruction.
1556 AtBlockEntry = false;
1558 // First known non-DBG_VALUE and non-frame setup location marks
1559 // the beginning of the function body.
1560 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1561 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1562 PrologEndLoc = MI->getDebugLoc();
1564 // Check if the instruction clobbers any registers with debug vars.
1565 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1566 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1567 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1569 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1570 AI.isValid(); ++AI) {
1572 const MDNode *Var = LiveUserVar[Reg];
1575 // Reg is now clobbered.
1576 LiveUserVar[Reg] = 0;
1578 // Was MD last defined by a DBG_VALUE referring to Reg?
1579 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1580 if (HistI == DbgValues.end())
1582 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1583 if (History.empty())
1585 const MachineInstr *Prev = History.back();
1586 // Sanity-check: Register assignments are terminated at the end of
1588 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1590 // Is the variable still in Reg?
1591 if (!isDbgValueInDefinedReg(Prev) ||
1592 Prev->getOperand(0).getReg() != Reg)
1594 // Var is clobbered. Make sure the next instruction gets a label.
1595 History.push_back(MI);
1602 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1604 SmallVectorImpl<const MachineInstr*> &History = I->second;
1605 if (History.empty())
1608 // Make sure the final register assignments are terminated.
1609 const MachineInstr *Prev = History.back();
1610 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1611 const MachineBasicBlock *PrevMBB = Prev->getParent();
1612 MachineBasicBlock::const_iterator LastMI =
1613 PrevMBB->getLastNonDebugInstr();
1614 if (LastMI == PrevMBB->end())
1615 // Drop DBG_VALUE for empty range.
1617 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1618 // Terminate after LastMI.
1619 History.push_back(LastMI);
1622 // Request labels for the full history.
1623 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1624 const MachineInstr *MI = History[i];
1625 if (MI->isDebugValue())
1626 requestLabelBeforeInsn(MI);
1628 requestLabelAfterInsn(MI);
1632 PrevInstLoc = DebugLoc();
1633 PrevLabel = FunctionBeginSym;
1635 // Record beginning of function.
1636 if (!PrologEndLoc.isUnknown()) {
1637 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1638 MF->getFunction()->getContext());
1639 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1640 FnStartDL.getScope(MF->getFunction()->getContext()),
1641 // We'd like to list the prologue as "not statements" but GDB behaves
1642 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1643 DWARF2_FLAG_IS_STMT);
1647 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1648 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1649 DIVariable DV = Var->getVariable();
1650 // Variables with positive arg numbers are parameters.
1651 if (unsigned ArgNum = DV.getArgNumber()) {
1652 // Keep all parameters in order at the start of the variable list to ensure
1653 // function types are correct (no out-of-order parameters)
1655 // This could be improved by only doing it for optimized builds (unoptimized
1656 // builds have the right order to begin with), searching from the back (this
1657 // would catch the unoptimized case quickly), or doing a binary search
1658 // rather than linear search.
1659 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1660 while (I != Vars.end()) {
1661 unsigned CurNum = (*I)->getVariable().getArgNumber();
1662 // A local (non-parameter) variable has been found, insert immediately
1666 // A later indexed parameter has been found, insert immediately before it.
1667 if (CurNum > ArgNum)
1671 Vars.insert(I, Var);
1675 Vars.push_back(Var);
1678 // Gather and emit post-function debug information.
1679 void DwarfDebug::endFunction(const MachineFunction *MF) {
1680 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1682 // Define end label for subprogram.
1683 FunctionEndSym = Asm->GetTempSymbol("func_end",
1684 Asm->getFunctionNumber());
1685 // Assumes in correct section after the entry point.
1686 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1687 // Set DwarfCompileUnitID in MCContext to default value.
1688 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1690 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1691 collectVariableInfo(MF, ProcessedVars);
1693 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1694 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1695 assert(TheCU && "Unable to find compile unit!");
1697 // Construct abstract scopes.
1698 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1699 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1700 LexicalScope *AScope = AList[i];
1701 DISubprogram SP(AScope->getScopeNode());
1702 if (SP.isSubprogram()) {
1703 // Collect info for variables that were optimized out.
1704 DIArray Variables = SP.getVariables();
1705 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1706 DIVariable DV(Variables.getElement(i));
1707 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1709 // Check that DbgVariable for DV wasn't created earlier, when
1710 // findAbstractVariable() was called for inlined instance of DV.
1711 LLVMContext &Ctx = DV->getContext();
1712 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1713 if (AbstractVariables.lookup(CleanDV))
1715 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1716 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1719 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1720 constructScopeDIE(TheCU, AScope);
1723 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1725 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1726 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1729 for (ScopeVariablesMap::iterator
1730 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1731 DeleteContainerPointers(I->second);
1732 ScopeVariables.clear();
1733 DeleteContainerPointers(CurrentFnArguments);
1734 UserVariables.clear();
1736 AbstractVariables.clear();
1737 LabelsBeforeInsn.clear();
1738 LabelsAfterInsn.clear();
1742 // Register a source line with debug info. Returns the unique label that was
1743 // emitted and which provides correspondence to the source line list.
1744 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1750 DIDescriptor Scope(S);
1752 if (Scope.isCompileUnit()) {
1753 DICompileUnit CU(S);
1754 Fn = CU.getFilename();
1755 Dir = CU.getDirectory();
1756 } else if (Scope.isFile()) {
1758 Fn = F.getFilename();
1759 Dir = F.getDirectory();
1760 } else if (Scope.isSubprogram()) {
1762 Fn = SP.getFilename();
1763 Dir = SP.getDirectory();
1764 } else if (Scope.isLexicalBlockFile()) {
1765 DILexicalBlockFile DBF(S);
1766 Fn = DBF.getFilename();
1767 Dir = DBF.getDirectory();
1768 } else if (Scope.isLexicalBlock()) {
1769 DILexicalBlock DB(S);
1770 Fn = DB.getFilename();
1771 Dir = DB.getDirectory();
1773 llvm_unreachable("Unexpected scope info");
1775 Src = getOrCreateSourceID(Fn, Dir,
1776 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1778 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1781 //===----------------------------------------------------------------------===//
1783 //===----------------------------------------------------------------------===//
1785 // Compute the size and offset of a DIE.
1787 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1788 // Get the children.
1789 const std::vector<DIE *> &Children = Die->getChildren();
1791 // Record the abbreviation.
1792 assignAbbrevNumber(Die->getAbbrev());
1794 // Get the abbreviation for this DIE.
1795 unsigned AbbrevNumber = Die->getAbbrevNumber();
1796 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1799 Die->setOffset(Offset);
1801 // Start the size with the size of abbreviation code.
1802 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1804 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1805 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1807 // Size the DIE attribute values.
1808 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1809 // Size attribute value.
1810 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1812 // Size the DIE children if any.
1813 if (!Children.empty()) {
1814 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1815 "Children flag not set");
1817 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1818 Offset = computeSizeAndOffset(Children[j], Offset);
1820 // End of children marker.
1821 Offset += sizeof(int8_t);
1824 Die->setSize(Offset - Die->getOffset());
1828 // Compute the size and offset of all the DIEs.
1829 void DwarfUnits::computeSizeAndOffsets() {
1830 // Offset from the beginning of debug info section.
1831 unsigned SecOffset = 0;
1832 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1833 E = CUs.end(); I != E; ++I) {
1834 (*I)->setDebugInfoOffset(SecOffset);
1836 sizeof(int32_t) + // Length of Compilation Unit Info
1837 sizeof(int16_t) + // DWARF version number
1838 sizeof(int32_t) + // Offset Into Abbrev. Section
1839 sizeof(int8_t); // Pointer Size (in bytes)
1841 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1842 SecOffset += EndOffset;
1846 // Emit initial Dwarf sections with a label at the start of each one.
1847 void DwarfDebug::emitSectionLabels() {
1848 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1850 // Dwarf sections base addresses.
1851 DwarfInfoSectionSym =
1852 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1853 DwarfAbbrevSectionSym =
1854 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1855 if (useSplitDwarf())
1856 DwarfAbbrevDWOSectionSym =
1857 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1858 "section_abbrev_dwo");
1859 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1861 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1862 emitSectionSym(Asm, MacroInfo);
1864 DwarfLineSectionSym =
1865 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1866 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1867 if (GenerateDwarfPubNamesSection)
1868 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1869 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1870 DwarfStrSectionSym =
1871 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1872 if (useSplitDwarf()) {
1873 DwarfStrDWOSectionSym =
1874 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1875 DwarfAddrSectionSym =
1876 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1878 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1881 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1882 "section_debug_loc");
1884 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1885 emitSectionSym(Asm, TLOF.getDataSection());
1888 // Recursively emits a debug information entry.
1889 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1890 // Get the abbreviation for this DIE.
1891 unsigned AbbrevNumber = Die->getAbbrevNumber();
1892 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1894 // Emit the code (index) for the abbreviation.
1895 if (Asm->isVerbose())
1896 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1897 Twine::utohexstr(Die->getOffset()) + ":0x" +
1898 Twine::utohexstr(Die->getSize()) + " " +
1899 dwarf::TagString(Abbrev->getTag()));
1900 Asm->EmitULEB128(AbbrevNumber);
1902 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1903 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1905 // Emit the DIE attribute values.
1906 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1907 unsigned Attr = AbbrevData[i].getAttribute();
1908 unsigned Form = AbbrevData[i].getForm();
1909 assert(Form && "Too many attributes for DIE (check abbreviation)");
1911 if (Asm->isVerbose())
1912 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1915 case dwarf::DW_AT_abstract_origin: {
1916 DIEEntry *E = cast<DIEEntry>(Values[i]);
1917 DIE *Origin = E->getEntry();
1918 unsigned Addr = Origin->getOffset();
1919 if (Form == dwarf::DW_FORM_ref_addr) {
1920 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1921 // section. Origin->getOffset() returns the offset from start of the
1923 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1924 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1926 Asm->OutStreamer.EmitIntValue(Addr,
1927 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1930 case dwarf::DW_AT_ranges: {
1931 // DW_AT_range Value encodes offset in debug_range section.
1932 DIEInteger *V = cast<DIEInteger>(Values[i]);
1934 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1935 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1939 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1941 DwarfDebugRangeSectionSym,
1946 case dwarf::DW_AT_location: {
1947 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1948 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1949 Asm->EmitLabelReference(L->getValue(), 4);
1951 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1953 Values[i]->EmitValue(Asm, Form);
1957 case dwarf::DW_AT_accessibility: {
1958 if (Asm->isVerbose()) {
1959 DIEInteger *V = cast<DIEInteger>(Values[i]);
1960 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1962 Values[i]->EmitValue(Asm, Form);
1966 // Emit an attribute using the defined form.
1967 Values[i]->EmitValue(Asm, Form);
1972 // Emit the DIE children if any.
1973 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1974 const std::vector<DIE *> &Children = Die->getChildren();
1976 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1977 emitDIE(Children[j], Abbrevs);
1979 if (Asm->isVerbose())
1980 Asm->OutStreamer.AddComment("End Of Children Mark");
1985 // Emit the various dwarf units to the unit section USection with
1986 // the abbreviations going into ASection.
1987 void DwarfUnits::emitUnits(DwarfDebug *DD,
1988 const MCSection *USection,
1989 const MCSection *ASection,
1990 const MCSymbol *ASectionSym) {
1991 Asm->OutStreamer.SwitchSection(USection);
1992 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1993 E = CUs.end(); I != E; ++I) {
1994 CompileUnit *TheCU = *I;
1995 DIE *Die = TheCU->getCUDie();
1997 // Emit the compile units header.
1999 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2000 TheCU->getUniqueID()));
2002 // Emit size of content not including length itself
2003 unsigned ContentSize = Die->getSize() +
2004 sizeof(int16_t) + // DWARF version number
2005 sizeof(int32_t) + // Offset Into Abbrev. Section
2006 sizeof(int8_t); // Pointer Size (in bytes)
2008 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2009 Asm->EmitInt32(ContentSize);
2010 Asm->OutStreamer.AddComment("DWARF version number");
2011 Asm->EmitInt16(DD->getDwarfVersion());
2012 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2013 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2015 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2016 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2018 DD->emitDIE(Die, Abbreviations);
2019 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2020 TheCU->getUniqueID()));
2024 /// For a given compile unit DIE, returns offset from beginning of debug info.
2025 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2026 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2027 "Input DIE should be compile unit in getCUOffset.");
2028 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2029 E = CUs.end(); I != E; ++I) {
2030 CompileUnit *TheCU = *I;
2031 if (TheCU->getCUDie() == Die)
2032 return TheCU->getDebugInfoOffset();
2034 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2037 // Emit the debug info section.
2038 void DwarfDebug::emitDebugInfo() {
2039 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2041 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2042 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2043 DwarfAbbrevSectionSym);
2046 // Emit the abbreviation section.
2047 void DwarfDebug::emitAbbreviations() {
2048 if (!useSplitDwarf())
2049 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2052 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2055 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2056 std::vector<DIEAbbrev *> *Abbrevs) {
2057 // Check to see if it is worth the effort.
2058 if (!Abbrevs->empty()) {
2059 // Start the debug abbrev section.
2060 Asm->OutStreamer.SwitchSection(Section);
2062 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2063 Asm->OutStreamer.EmitLabel(Begin);
2065 // For each abbrevation.
2066 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2067 // Get abbreviation data
2068 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2070 // Emit the abbrevations code (base 1 index.)
2071 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2073 // Emit the abbreviations data.
2077 // Mark end of abbreviations.
2078 Asm->EmitULEB128(0, "EOM(3)");
2080 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2081 Asm->OutStreamer.EmitLabel(End);
2085 // Emit the last address of the section and the end of the line matrix.
2086 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2087 // Define last address of section.
2088 Asm->OutStreamer.AddComment("Extended Op");
2091 Asm->OutStreamer.AddComment("Op size");
2092 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2093 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2094 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2096 Asm->OutStreamer.AddComment("Section end label");
2098 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2099 Asm->getDataLayout().getPointerSize());
2101 // Mark end of matrix.
2102 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2108 // Emit visible names into a hashed accelerator table section.
2109 void DwarfDebug::emitAccelNames() {
2110 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2111 dwarf::DW_FORM_data4));
2112 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2113 E = CUMap.end(); I != E; ++I) {
2114 CompileUnit *TheCU = I->second;
2115 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2116 for (StringMap<std::vector<DIE*> >::const_iterator
2117 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2118 StringRef Name = GI->getKey();
2119 const std::vector<DIE *> &Entities = GI->second;
2120 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2121 DE = Entities.end(); DI != DE; ++DI)
2122 AT.AddName(Name, (*DI));
2126 AT.FinalizeTable(Asm, "Names");
2127 Asm->OutStreamer.SwitchSection(
2128 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2129 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2130 Asm->OutStreamer.EmitLabel(SectionBegin);
2132 // Emit the full data.
2133 AT.Emit(Asm, SectionBegin, &InfoHolder);
2136 // Emit objective C classes and categories into a hashed accelerator table
2138 void DwarfDebug::emitAccelObjC() {
2139 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2140 dwarf::DW_FORM_data4));
2141 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2142 E = CUMap.end(); I != E; ++I) {
2143 CompileUnit *TheCU = I->second;
2144 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2145 for (StringMap<std::vector<DIE*> >::const_iterator
2146 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2147 StringRef Name = GI->getKey();
2148 const std::vector<DIE *> &Entities = GI->second;
2149 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2150 DE = Entities.end(); DI != DE; ++DI)
2151 AT.AddName(Name, (*DI));
2155 AT.FinalizeTable(Asm, "ObjC");
2156 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2157 .getDwarfAccelObjCSection());
2158 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2159 Asm->OutStreamer.EmitLabel(SectionBegin);
2161 // Emit the full data.
2162 AT.Emit(Asm, SectionBegin, &InfoHolder);
2165 // Emit namespace dies into a hashed accelerator table.
2166 void DwarfDebug::emitAccelNamespaces() {
2167 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2168 dwarf::DW_FORM_data4));
2169 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2170 E = CUMap.end(); I != E; ++I) {
2171 CompileUnit *TheCU = I->second;
2172 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2173 for (StringMap<std::vector<DIE*> >::const_iterator
2174 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2175 StringRef Name = GI->getKey();
2176 const std::vector<DIE *> &Entities = GI->second;
2177 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2178 DE = Entities.end(); DI != DE; ++DI)
2179 AT.AddName(Name, (*DI));
2183 AT.FinalizeTable(Asm, "namespac");
2184 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2185 .getDwarfAccelNamespaceSection());
2186 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2187 Asm->OutStreamer.EmitLabel(SectionBegin);
2189 // Emit the full data.
2190 AT.Emit(Asm, SectionBegin, &InfoHolder);
2193 // Emit type dies into a hashed accelerator table.
2194 void DwarfDebug::emitAccelTypes() {
2195 std::vector<DwarfAccelTable::Atom> Atoms;
2196 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2197 dwarf::DW_FORM_data4));
2198 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2199 dwarf::DW_FORM_data2));
2200 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2201 dwarf::DW_FORM_data1));
2202 DwarfAccelTable AT(Atoms);
2203 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2204 E = CUMap.end(); I != E; ++I) {
2205 CompileUnit *TheCU = I->second;
2206 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2207 = TheCU->getAccelTypes();
2208 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2209 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2210 StringRef Name = GI->getKey();
2211 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2212 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2213 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2214 AT.AddName(Name, (*DI).first, (*DI).second);
2218 AT.FinalizeTable(Asm, "types");
2219 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2220 .getDwarfAccelTypesSection());
2221 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2222 Asm->OutStreamer.EmitLabel(SectionBegin);
2224 // Emit the full data.
2225 AT.Emit(Asm, SectionBegin, &InfoHolder);
2228 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2230 void DwarfDebug::emitDebugPubnames() {
2231 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2233 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2234 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2235 CompileUnit *TheCU = I->second;
2236 unsigned ID = TheCU->getUniqueID();
2238 if (TheCU->getGlobalNames().empty())
2241 // Start the dwarf pubnames section.
2242 Asm->OutStreamer.SwitchSection(
2243 Asm->getObjFileLowering().getDwarfPubNamesSection());
2245 Asm->OutStreamer.AddComment("Length of Public Names Info");
2246 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2247 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2249 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2251 Asm->OutStreamer.AddComment("DWARF Version");
2252 Asm->EmitInt16(DwarfVersion);
2254 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2255 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2256 DwarfInfoSectionSym);
2258 Asm->OutStreamer.AddComment("Compilation Unit Length");
2259 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2260 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2263 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2264 for (StringMap<DIE*>::const_iterator
2265 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2266 const char *Name = GI->getKeyData();
2267 const DIE *Entity = GI->second;
2269 Asm->OutStreamer.AddComment("DIE offset");
2270 Asm->EmitInt32(Entity->getOffset());
2272 if (Asm->isVerbose())
2273 Asm->OutStreamer.AddComment("External Name");
2274 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2277 Asm->OutStreamer.AddComment("End Mark");
2279 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2283 void DwarfDebug::emitDebugPubTypes() {
2284 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2285 E = CUMap.end(); I != E; ++I) {
2286 CompileUnit *TheCU = I->second;
2287 // Start the dwarf pubtypes section.
2288 Asm->OutStreamer.SwitchSection(
2289 Asm->getObjFileLowering().getDwarfPubTypesSection());
2290 Asm->OutStreamer.AddComment("Length of Public Types Info");
2291 Asm->EmitLabelDifference(
2292 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2293 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2295 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2296 TheCU->getUniqueID()));
2298 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2299 Asm->EmitInt16(DwarfVersion);
2301 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2302 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2303 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2304 TheCU->getUniqueID()),
2305 DwarfInfoSectionSym);
2307 Asm->OutStreamer.AddComment("Compilation Unit Length");
2308 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2309 TheCU->getUniqueID()),
2310 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2311 TheCU->getUniqueID()),
2314 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2315 for (StringMap<DIE*>::const_iterator
2316 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2317 const char *Name = GI->getKeyData();
2318 DIE *Entity = GI->second;
2320 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2321 Asm->EmitInt32(Entity->getOffset());
2323 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2324 // Emit the name with a terminating null byte.
2325 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2328 Asm->OutStreamer.AddComment("End Mark");
2330 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2331 TheCU->getUniqueID()));
2335 // Emit strings into a string section.
2336 void DwarfUnits::emitStrings(const MCSection *StrSection,
2337 const MCSection *OffsetSection = NULL,
2338 const MCSymbol *StrSecSym = NULL) {
2340 if (StringPool.empty()) return;
2342 // Start the dwarf str section.
2343 Asm->OutStreamer.SwitchSection(StrSection);
2345 // Get all of the string pool entries and put them in an array by their ID so
2346 // we can sort them.
2347 SmallVector<std::pair<unsigned,
2348 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2350 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2351 I = StringPool.begin(), E = StringPool.end();
2353 Entries.push_back(std::make_pair(I->second.second, &*I));
2355 array_pod_sort(Entries.begin(), Entries.end());
2357 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2358 // Emit a label for reference from debug information entries.
2359 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2361 // Emit the string itself with a terminating null byte.
2362 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2363 Entries[i].second->getKeyLength()+1));
2366 // If we've got an offset section go ahead and emit that now as well.
2367 if (OffsetSection) {
2368 Asm->OutStreamer.SwitchSection(OffsetSection);
2369 unsigned offset = 0;
2370 unsigned size = 4; // FIXME: DWARF64 is 8.
2371 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2372 Asm->OutStreamer.EmitIntValue(offset, size);
2373 offset += Entries[i].second->getKeyLength() + 1;
2378 // Emit strings into a string section.
2379 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2381 if (AddressPool.empty()) return;
2383 // Start the dwarf addr section.
2384 Asm->OutStreamer.SwitchSection(AddrSection);
2386 // Order the address pool entries by ID
2387 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2389 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2390 E = AddressPool.end();
2392 Entries[I->second] = I->first;
2394 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2395 // Emit an expression for reference from debug information entries.
2396 if (const MCExpr *Expr = Entries[i])
2397 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2399 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2404 // Emit visible names into a debug str section.
2405 void DwarfDebug::emitDebugStr() {
2406 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2407 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2410 // Emit locations into the debug loc section.
2411 void DwarfDebug::emitDebugLoc() {
2412 if (DotDebugLocEntries.empty())
2415 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2416 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2418 DotDebugLocEntry &Entry = *I;
2419 if (I + 1 != DotDebugLocEntries.end())
2423 // Start the dwarf loc section.
2424 Asm->OutStreamer.SwitchSection(
2425 Asm->getObjFileLowering().getDwarfLocSection());
2426 unsigned char Size = Asm->getDataLayout().getPointerSize();
2427 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2429 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2430 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2431 I != E; ++I, ++index) {
2432 DotDebugLocEntry &Entry = *I;
2433 if (Entry.isMerged()) continue;
2434 if (Entry.isEmpty()) {
2435 Asm->OutStreamer.EmitIntValue(0, Size);
2436 Asm->OutStreamer.EmitIntValue(0, Size);
2437 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2439 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2440 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2441 DIVariable DV(Entry.getVariable());
2442 Asm->OutStreamer.AddComment("Loc expr size");
2443 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2444 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2445 Asm->EmitLabelDifference(end, begin, 2);
2446 Asm->OutStreamer.EmitLabel(begin);
2447 if (Entry.isInt()) {
2448 DIBasicType BTy(DV.getType());
2450 (BTy.getEncoding() == dwarf::DW_ATE_signed
2451 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2452 Asm->OutStreamer.AddComment("DW_OP_consts");
2453 Asm->EmitInt8(dwarf::DW_OP_consts);
2454 Asm->EmitSLEB128(Entry.getInt());
2456 Asm->OutStreamer.AddComment("DW_OP_constu");
2457 Asm->EmitInt8(dwarf::DW_OP_constu);
2458 Asm->EmitULEB128(Entry.getInt());
2460 } else if (Entry.isLocation()) {
2461 MachineLocation Loc = Entry.getLoc();
2462 if (!DV.hasComplexAddress())
2464 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2466 // Complex address entry.
2467 unsigned N = DV.getNumAddrElements();
2469 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2470 if (Loc.getOffset()) {
2472 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2473 Asm->OutStreamer.AddComment("DW_OP_deref");
2474 Asm->EmitInt8(dwarf::DW_OP_deref);
2475 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2476 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2477 Asm->EmitSLEB128(DV.getAddrElement(1));
2479 // If first address element is OpPlus then emit
2480 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2481 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2482 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2486 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2489 // Emit remaining complex address elements.
2490 for (; i < N; ++i) {
2491 uint64_t Element = DV.getAddrElement(i);
2492 if (Element == DIBuilder::OpPlus) {
2493 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2494 Asm->EmitULEB128(DV.getAddrElement(++i));
2495 } else if (Element == DIBuilder::OpDeref) {
2497 Asm->EmitInt8(dwarf::DW_OP_deref);
2499 llvm_unreachable("unknown Opcode found in complex address");
2503 // else ... ignore constant fp. There is not any good way to
2504 // to represent them here in dwarf.
2505 Asm->OutStreamer.EmitLabel(end);
2510 // Emit visible names into a debug aranges section.
2511 void DwarfDebug::emitDebugARanges() {
2512 // Start the dwarf aranges section.
2513 Asm->OutStreamer.SwitchSection(
2514 Asm->getObjFileLowering().getDwarfARangesSection());
2517 // Emit visible names into a debug ranges section.
2518 void DwarfDebug::emitDebugRanges() {
2519 // Start the dwarf ranges section.
2520 Asm->OutStreamer.SwitchSection(
2521 Asm->getObjFileLowering().getDwarfRangesSection());
2522 unsigned char Size = Asm->getDataLayout().getPointerSize();
2523 for (SmallVectorImpl<const MCSymbol *>::iterator
2524 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2527 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2529 Asm->OutStreamer.EmitIntValue(0, Size);
2533 // Emit visible names into a debug macinfo section.
2534 void DwarfDebug::emitDebugMacInfo() {
2535 if (const MCSection *LineInfo =
2536 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2537 // Start the dwarf macinfo section.
2538 Asm->OutStreamer.SwitchSection(LineInfo);
2542 // Emit inline info using following format.
2544 // 1. length of section
2545 // 2. Dwarf version number
2548 // Entries (one "entry" for each function that was inlined):
2550 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2551 // otherwise offset into __debug_str for regular function name.
2552 // 2. offset into __debug_str section for regular function name.
2553 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2554 // instances for the function.
2556 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2557 // inlined instance; the die_offset points to the inlined_subroutine die in the
2558 // __debug_info section, and the low_pc is the starting address for the
2559 // inlining instance.
2560 void DwarfDebug::emitDebugInlineInfo() {
2561 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2567 Asm->OutStreamer.SwitchSection(
2568 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2570 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2571 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2572 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2574 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2576 Asm->OutStreamer.AddComment("Dwarf Version");
2577 Asm->EmitInt16(DwarfVersion);
2578 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2579 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2581 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2582 E = InlinedSPNodes.end(); I != E; ++I) {
2584 const MDNode *Node = *I;
2585 InlineInfoMap::iterator II = InlineInfo.find(Node);
2586 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2587 DISubprogram SP(Node);
2588 StringRef LName = SP.getLinkageName();
2589 StringRef Name = SP.getName();
2591 Asm->OutStreamer.AddComment("MIPS linkage name");
2593 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2594 DwarfStrSectionSym);
2596 Asm->EmitSectionOffset(
2597 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2598 DwarfStrSectionSym);
2600 Asm->OutStreamer.AddComment("Function name");
2601 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2602 DwarfStrSectionSym);
2603 Asm->EmitULEB128(Labels.size(), "Inline count");
2605 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2606 LE = Labels.end(); LI != LE; ++LI) {
2607 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2608 Asm->EmitInt32(LI->second->getOffset());
2610 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2611 Asm->OutStreamer.EmitSymbolValue(LI->first,
2612 Asm->getDataLayout().getPointerSize());
2616 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2619 // DWARF5 Experimental Separate Dwarf emitters.
2621 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2622 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2623 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2624 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2625 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2626 DICompileUnit DIUnit(N);
2627 CompilationDir = DIUnit.getDirectory();
2629 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2630 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2631 DIUnit.getLanguage(), Die, N, Asm,
2632 this, &SkeletonHolder);
2634 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2635 DIUnit.getSplitDebugFilename());
2637 // This should be a unique identifier when we want to build .dwp files.
2638 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2640 // Relocate to the beginning of the addr_base section, else 0 for the
2641 // beginning of the one for this compile unit.
2642 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2643 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2644 DwarfAddrSectionSym);
2646 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2647 dwarf::DW_FORM_sec_offset, 0);
2649 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2650 // into an entity. We're using 0, or a NULL label for this.
2651 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2653 // DW_AT_stmt_list is a offset of line number information for this
2654 // compile unit in debug_line section.
2655 // FIXME: Should handle multiple compile units.
2656 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2657 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2658 DwarfLineSectionSym);
2660 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2662 if (!CompilationDir.empty())
2663 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2665 SkeletonHolder.addUnit(NewCU);
2666 SkeletonCUs.push_back(NewCU);
2671 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2672 assert(useSplitDwarf() && "No split dwarf debug info?");
2673 emitAbbrevs(Section, &SkeletonAbbrevs);
2676 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2677 // compile units that would normally be in debug_info.
2678 void DwarfDebug::emitDebugInfoDWO() {
2679 assert(useSplitDwarf() && "No split dwarf debug info?");
2680 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2681 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2682 DwarfAbbrevDWOSectionSym);
2685 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2686 // abbreviations for the .debug_info.dwo section.
2687 void DwarfDebug::emitDebugAbbrevDWO() {
2688 assert(useSplitDwarf() && "No split dwarf?");
2689 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2693 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2694 // string section and is identical in format to traditional .debug_str
2696 void DwarfDebug::emitDebugStrDWO() {
2697 assert(useSplitDwarf() && "No split dwarf?");
2698 const MCSection *OffSec = Asm->getObjFileLowering()
2699 .getDwarfStrOffDWOSection();
2700 const MCSymbol *StrSym = DwarfStrSectionSym;
2701 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),