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/Constants.h"
20 #include "llvm/DebugInfo.h"
21 #include "llvm/DIBuilder.h"
22 #include "llvm/Module.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/Path.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."),
59 Default, Enable, Disable
63 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
64 cl::desc("Output prototype dwarf accelerator tables."),
66 clEnumVal(Default, "Default for platform"),
67 clEnumVal(Enable, "Enabled"),
68 clEnumVal(Disable, "Disabled"),
72 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
73 cl::desc("Compatibility with Darwin gdb."),
75 clEnumVal(Default, "Default for platform"),
76 clEnumVal(Enable, "Enabled"),
77 clEnumVal(Disable, "Disabled"),
82 const char *DWARFGroupName = "DWARF Emission";
83 const char *DbgTimerName = "DWARF Debug Writer";
84 } // end anonymous namespace
86 //===----------------------------------------------------------------------===//
88 /// Configuration values for initial hash set sizes (log2).
90 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
94 DIType DbgVariable::getType() const {
95 DIType Ty = Var.getType();
96 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
98 if (Var.isBlockByrefVariable()) {
99 /* Byref variables, in Blocks, are declared by the programmer as
100 "SomeType VarName;", but the compiler creates a
101 __Block_byref_x_VarName struct, and gives the variable VarName
102 either the struct, or a pointer to the struct, as its type. This
103 is necessary for various behind-the-scenes things the compiler
104 needs to do with by-reference variables in blocks.
106 However, as far as the original *programmer* is concerned, the
107 variable should still have type 'SomeType', as originally declared.
109 The following function dives into the __Block_byref_x_VarName
110 struct to find the original type of the variable. This will be
111 passed back to the code generating the type for the Debug
112 Information Entry for the variable 'VarName'. 'VarName' will then
113 have the original type 'SomeType' in its debug information.
115 The original type 'SomeType' will be the type of the field named
116 'VarName' inside the __Block_byref_x_VarName struct.
118 NOTE: In order for this to not completely fail on the debugger
119 side, the Debug Information Entry for the variable VarName needs to
120 have a DW_AT_location that tells the debugger how to unwind through
121 the pointers and __Block_byref_x_VarName struct to find the actual
122 value of the variable. The function addBlockByrefType does this. */
124 unsigned tag = Ty.getTag();
126 if (tag == dwarf::DW_TAG_pointer_type) {
127 DIDerivedType DTy = DIDerivedType(Ty);
128 subType = DTy.getTypeDerivedFrom();
131 DICompositeType blockStruct = DICompositeType(subType);
132 DIArray Elements = blockStruct.getTypeArray();
134 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
135 DIDescriptor Element = Elements.getElement(i);
136 DIDerivedType DT = DIDerivedType(Element);
137 if (getName() == DT.getName())
138 return (DT.getTypeDerivedFrom());
144 } // end llvm namespace
146 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
147 : Asm(A), MMI(Asm->MMI), FirstCU(0),
148 AbbreviationsSet(InitAbbreviationsSetSize),
149 SourceIdMap(DIEValueAllocator), StringPool(DIEValueAllocator),
151 NextStringPoolNumber = 0;
153 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
154 DwarfStrSectionSym = TextSectionSym = 0;
155 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
156 FunctionBeginSym = FunctionEndSym = 0;
158 // Turn on accelerator tables and older gdb compatibility
160 bool isDarwin = Triple(M->getTargetTriple()).isOSDarwin();
161 if (DarwinGDBCompat == Default) {
163 isDarwinGDBCompat = true;
165 isDarwinGDBCompat = false;
167 isDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
169 if (DwarfAccelTables == Default) {
171 hasDwarfAccelTables = true;
173 hasDwarfAccelTables = false;
175 hasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
178 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
182 DwarfDebug::~DwarfDebug() {
185 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
186 /// temporary label to it if SymbolStem is specified.
187 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
188 const char *SymbolStem = 0) {
189 Asm->OutStreamer.SwitchSection(Section);
190 if (!SymbolStem) return 0;
192 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
193 Asm->OutStreamer.EmitLabel(TmpSym);
197 MCSymbol *DwarfDebug::getStringPool() {
198 return Asm->GetTempSymbol("section_str");
201 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
202 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
203 if (Entry.first) return Entry.first;
205 Entry.second = NextStringPoolNumber++;
206 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
209 /// assignAbbrevNumber - Define a unique number for the abbreviation.
211 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
212 // Profile the node so that we can make it unique.
216 // Check the set for priors.
217 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
219 // If it's newly added.
220 if (InSet == &Abbrev) {
221 // Add to abbreviation list.
222 Abbreviations.push_back(&Abbrev);
224 // Assign the vector position + 1 as its number.
225 Abbrev.setNumber(Abbreviations.size());
227 // Assign existing abbreviation number.
228 Abbrev.setNumber(InSet->getNumber());
232 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
233 /// printer to not emit usual symbol prefix before the symbol name is used then
234 /// return linkage name after skipping this special LLVM prefix.
235 static StringRef getRealLinkageName(StringRef LinkageName) {
237 if (LinkageName.startswith(StringRef(&One, 1)))
238 return LinkageName.substr(1);
242 static bool isObjCClass(StringRef Name) {
243 return Name.startswith("+") || Name.startswith("-");
246 static bool hasObjCCategory(StringRef Name) {
247 if (!isObjCClass(Name)) return false;
249 size_t pos = Name.find(')');
250 if (pos != std::string::npos) {
251 if (Name[pos+1] != ' ') return false;
257 static void getObjCClassCategory(StringRef In, StringRef &Class,
258 StringRef &Category) {
259 if (!hasObjCCategory(In)) {
260 Class = In.slice(In.find('[') + 1, In.find(' '));
265 Class = In.slice(In.find('[') + 1, In.find('('));
266 Category = In.slice(In.find('[') + 1, In.find(' '));
270 static StringRef getObjCMethodName(StringRef In) {
271 return In.slice(In.find(' ') + 1, In.find(']'));
274 // Add the various names to the Dwarf accelerator table names.
275 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
277 if (!SP.isDefinition()) return;
279 TheCU->addAccelName(SP.getName(), Die);
281 // If the linkage name is different than the name, go ahead and output
282 // that as well into the name table.
283 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284 TheCU->addAccelName(SP.getLinkageName(), Die);
286 // If this is an Objective-C selector name add it to the ObjC accelerator
288 if (isObjCClass(SP.getName())) {
289 StringRef Class, Category;
290 getObjCClassCategory(SP.getName(), Class, Category);
291 TheCU->addAccelObjC(Class, Die);
293 TheCU->addAccelObjC(Category, Die);
294 // Also add the base method name to the name table.
295 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
299 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
300 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
301 /// If there are global variables in this scope then create and insert
302 /// DIEs for these variables.
303 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
304 const MDNode *SPNode) {
305 DIE *SPDie = SPCU->getDIE(SPNode);
307 assert(SPDie && "Unable to find subprogram DIE!");
308 DISubprogram SP(SPNode);
310 DISubprogram SPDecl = SP.getFunctionDeclaration();
311 if (!SPDecl.isSubprogram()) {
312 // There is not any need to generate specification DIE for a function
313 // defined at compile unit level. If a function is defined inside another
314 // function then gdb prefers the definition at top level and but does not
315 // expect specification DIE in parent function. So avoid creating
316 // specification DIE for a function defined inside a function.
317 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
318 !SP.getContext().isFile() &&
319 !isSubprogramContext(SP.getContext())) {
320 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
323 DICompositeType SPTy = SP.getType();
324 DIArray Args = SPTy.getTypeArray();
325 unsigned SPTag = SPTy.getTag();
326 if (SPTag == dwarf::DW_TAG_subroutine_type)
327 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
328 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
329 DIType ATy = DIType(Args.getElement(i));
330 SPCU->addType(Arg, ATy);
331 if (ATy.isArtificial())
332 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
333 if (ATy.isObjectPointer())
334 SPCU->addFlag(Arg, dwarf::DW_AT_object_pointer);
335 SPDie->addChild(Arg);
337 DIE *SPDeclDie = SPDie;
338 SPDie = new DIE(dwarf::DW_TAG_subprogram);
339 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
344 // Pick up abstract subprogram DIE.
345 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
346 SPDie = new DIE(dwarf::DW_TAG_subprogram);
347 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
348 dwarf::DW_FORM_ref4, AbsSPDIE);
352 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
353 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
354 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
355 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
356 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
357 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
358 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
360 // Add name to the name table, we do this here because we're guaranteed
361 // to have concrete versions of our DW_TAG_subprogram nodes.
362 addSubprogramNames(SPCU, SP, SPDie);
367 /// constructLexicalScope - Construct new DW_TAG_lexical_block
368 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
369 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
370 LexicalScope *Scope) {
371 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
372 if (Scope->isAbstractScope())
375 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
379 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
380 if (Ranges.size() > 1) {
381 // .debug_range section has not been laid out yet. Emit offset in
382 // .debug_range as a uint, size 4, for now. emitDIE will handle
383 // DW_AT_ranges appropriately.
384 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
385 DebugRangeSymbols.size()
386 * Asm->getTargetData().getPointerSize());
387 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
388 RE = Ranges.end(); RI != RE; ++RI) {
389 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
390 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
392 DebugRangeSymbols.push_back(NULL);
393 DebugRangeSymbols.push_back(NULL);
397 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
398 const MCSymbol *End = getLabelAfterInsn(RI->second);
400 if (End == 0) return 0;
402 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
403 assert(End->isDefined() && "Invalid end label for an inlined scope!");
405 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
406 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
411 /// constructInlinedScopeDIE - This scope represents inlined body of
412 /// a function. Construct DIE to represent this concrete inlined copy
414 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
415 LexicalScope *Scope) {
416 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
417 assert(Ranges.empty() == false &&
418 "LexicalScope does not have instruction markers!");
420 if (!Scope->getScopeNode())
422 DIScope DS(Scope->getScopeNode());
423 DISubprogram InlinedSP = getDISubprogram(DS);
424 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
426 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
430 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
431 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
432 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
434 if (StartLabel == 0 || EndLabel == 0) {
435 llvm_unreachable("Unexpected Start and End labels for a inlined scope!");
437 assert(StartLabel->isDefined() &&
438 "Invalid starting label for an inlined scope!");
439 assert(EndLabel->isDefined() &&
440 "Invalid end label for an inlined scope!");
442 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
443 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
444 dwarf::DW_FORM_ref4, OriginDIE);
446 if (Ranges.size() > 1) {
447 // .debug_range section has not been laid out yet. Emit offset in
448 // .debug_range as a uint, size 4, for now. emitDIE will handle
449 // DW_AT_ranges appropriately.
450 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
451 DebugRangeSymbols.size()
452 * Asm->getTargetData().getPointerSize());
453 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
454 RE = Ranges.end(); RI != RE; ++RI) {
455 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
456 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
458 DebugRangeSymbols.push_back(NULL);
459 DebugRangeSymbols.push_back(NULL);
461 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
463 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
467 InlinedSubprogramDIEs.insert(OriginDIE);
469 // Track the start label for this inlined function.
470 //.debug_inlined section specification does not clearly state how
471 // to emit inlined scope that is split into multiple instruction ranges.
472 // For now, use first instruction range and emit low_pc/high_pc pair and
473 // corresponding .debug_inlined section entry for this pair.
474 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
475 I = InlineInfo.find(InlinedSP);
477 if (I == InlineInfo.end()) {
478 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
479 InlinedSPNodes.push_back(InlinedSP);
481 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
483 DILocation DL(Scope->getInlinedAt());
484 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
485 GetOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
486 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
488 // Add name to the name table, we do this here because we're guaranteed
489 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
490 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
495 /// constructScopeDIE - Construct a DIE for this scope.
496 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
497 if (!Scope || !Scope->getScopeNode())
500 SmallVector<DIE *, 8> Children;
502 // Collect arguments for current function.
503 if (LScopes.isCurrentFunctionScope(Scope))
504 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
505 if (DbgVariable *ArgDV = CurrentFnArguments[i])
507 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
508 Children.push_back(Arg);
510 // Collect lexical scope children first.
511 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
512 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
514 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
515 Children.push_back(Variable);
516 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
517 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
518 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
519 Children.push_back(Nested);
520 DIScope DS(Scope->getScopeNode());
521 DIE *ScopeDIE = NULL;
522 if (Scope->getInlinedAt())
523 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
524 else if (DS.isSubprogram()) {
525 ProcessedSPNodes.insert(DS);
526 if (Scope->isAbstractScope()) {
527 ScopeDIE = TheCU->getDIE(DS);
528 // Note down abstract DIE.
530 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
533 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
536 // There is no need to emit empty lexical block DIE.
537 if (Children.empty())
539 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
542 if (!ScopeDIE) return NULL;
545 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
546 E = Children.end(); I != E; ++I)
547 ScopeDIE->addChild(*I);
549 if (DS.isSubprogram())
550 TheCU->addPubTypes(DISubprogram(DS));
555 /// GetOrCreateSourceID - Look up the source id with the given directory and
556 /// source file names. If none currently exists, create a new id and insert it
557 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
559 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
561 // If FE did not provide a file name, then assume stdin.
562 if (FileName.empty())
563 return GetOrCreateSourceID("<stdin>", StringRef());
565 // TODO: this might not belong here. See if we can factor this better.
566 if (DirName == CompilationDir)
569 unsigned SrcId = SourceIdMap.size()+1;
571 // We look up the file/dir pair by concatenating them with a zero byte.
572 SmallString<128> NamePair;
574 NamePair += '\0'; // Zero bytes are not allowed in paths.
575 NamePair += FileName;
577 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
578 if (Ent.getValue() != SrcId)
579 return Ent.getValue();
581 // Print out a .file directive to specify files for .loc directives.
582 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
587 /// constructCompileUnit - Create new CompileUnit for the given
588 /// metadata node with tag DW_TAG_compile_unit.
589 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
590 DICompileUnit DIUnit(N);
591 StringRef FN = DIUnit.getFilename();
592 CompilationDir = DIUnit.getDirectory();
593 unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
595 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
596 CompileUnit *NewCU = new CompileUnit(ID, DIUnit.getLanguage(), Die,
598 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
599 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
600 DIUnit.getLanguage());
601 NewCU->addString(Die, dwarf::DW_AT_name, FN);
602 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
604 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
605 // DW_AT_stmt_list is a offset of line number information for this
606 // compile unit in debug_line section.
607 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
608 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
609 Asm->GetTempSymbol("section_line"));
611 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
613 if (!CompilationDir.empty())
614 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
615 if (DIUnit.isOptimized())
616 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
618 StringRef Flags = DIUnit.getFlags();
620 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
622 if (unsigned RVer = DIUnit.getRunTimeVersion())
623 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
624 dwarf::DW_FORM_data1, RVer);
628 CUMap.insert(std::make_pair(N, NewCU));
632 /// construct SubprogramDIE - Construct subprogram DIE.
633 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
635 CompileUnit *&CURef = SPMap[N];
641 if (!SP.isDefinition())
642 // This is a method declaration which will be handled while constructing
646 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
649 TheCU->insertDIE(N, SubprogramDie);
651 // Add to context owner.
652 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
657 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
658 /// as llvm.dbg.enum and llvm.dbg.ty
659 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
660 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
661 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
662 const MDNode *N = NMD->getOperand(i);
663 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
664 constructSubprogramDIE(CU, N);
667 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
668 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
669 const MDNode *N = NMD->getOperand(i);
670 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
671 CU->createGlobalVariableDIE(N);
674 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
675 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
676 DIType Ty(NMD->getOperand(i));
677 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
678 CU->getOrCreateTypeDIE(Ty);
681 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
682 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
683 DIType Ty(NMD->getOperand(i));
684 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
685 CU->getOrCreateTypeDIE(Ty);
689 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
690 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
691 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
692 DebugInfoFinder DbgFinder;
693 DbgFinder.processModule(*M);
695 bool HasDebugInfo = false;
696 // Scan all the compile-units to see if there are any marked as the main
697 // unit. If not, we do not generate debug info.
698 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
699 E = DbgFinder.compile_unit_end(); I != E; ++I) {
700 if (DICompileUnit(*I).isMain()) {
705 if (!HasDebugInfo) return false;
707 // Create all the compile unit DIEs.
708 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
709 E = DbgFinder.compile_unit_end(); I != E; ++I)
710 constructCompileUnit(*I);
712 // Create DIEs for each global variable.
713 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
714 E = DbgFinder.global_variable_end(); I != E; ++I) {
715 const MDNode *N = *I;
716 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
717 CU->createGlobalVariableDIE(N);
720 // Create DIEs for each subprogram.
721 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
722 E = DbgFinder.subprogram_end(); I != E; ++I) {
723 const MDNode *N = *I;
724 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
725 constructSubprogramDIE(CU, N);
731 /// beginModule - Emit all Dwarf sections that should come prior to the
732 /// content. Create global DIEs and emit initial debug info sections.
733 /// This is invoked by the target AsmPrinter.
734 void DwarfDebug::beginModule(Module *M) {
735 if (DisableDebugInfoPrinting)
738 // If module has named metadata anchors then use them, otherwise scan the
739 // module using debug info finder to collect debug info.
740 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
742 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
743 DICompileUnit CUNode(CU_Nodes->getOperand(i));
744 CompileUnit *CU = constructCompileUnit(CUNode);
745 DIArray GVs = CUNode.getGlobalVariables();
746 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
747 CU->createGlobalVariableDIE(GVs.getElement(i));
748 DIArray SPs = CUNode.getSubprograms();
749 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
750 constructSubprogramDIE(CU, SPs.getElement(i));
751 DIArray EnumTypes = CUNode.getEnumTypes();
752 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
753 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
754 DIArray RetainedTypes = CUNode.getRetainedTypes();
755 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
756 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
758 } else if (!collectLegacyDebugInfo(M))
761 collectInfoFromNamedMDNodes(M);
763 // Tell MMI that we have debug info.
764 MMI->setDebugInfoAvailability(true);
766 // Emit initial sections.
769 // Prime section data.
770 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
773 /// endModule - Emit all Dwarf sections that should come after the content.
775 void DwarfDebug::endModule() {
776 if (!FirstCU) return;
777 const Module *M = MMI->getModule();
778 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
780 // Collect info for variables that were optimized out.
781 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
782 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
783 DICompileUnit TheCU(CU_Nodes->getOperand(i));
784 DIArray Subprograms = TheCU.getSubprograms();
785 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
786 DISubprogram SP(Subprograms.getElement(i));
787 if (ProcessedSPNodes.count(SP) != 0) continue;
788 if (!SP.Verify()) continue;
789 if (!SP.isDefinition()) continue;
790 DIArray Variables = SP.getVariables();
791 if (Variables.getNumElements() == 0) continue;
793 LexicalScope *Scope =
794 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
795 DeadFnScopeMap[SP] = Scope;
797 // Construct subprogram DIE and add variables DIEs.
798 CompileUnit *SPCU = CUMap.lookup(TheCU);
799 assert(SPCU && "Unable to find Compile Unit!");
800 constructSubprogramDIE(SPCU, SP);
801 DIE *ScopeDIE = SPCU->getDIE(SP);
802 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
803 DIVariable DV(Variables.getElement(vi));
804 if (!DV.Verify()) continue;
805 DbgVariable *NewVar = new DbgVariable(DV, NULL);
806 if (DIE *VariableDIE =
807 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
808 ScopeDIE->addChild(VariableDIE);
814 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
815 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
816 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
818 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
820 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
821 AE = AbstractSPDies.end(); AI != AE; ++AI) {
822 DIE *ISP = AI->second;
823 if (InlinedSubprogramDIEs.count(ISP))
825 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
828 // Emit DW_AT_containing_type attribute to connect types with their
829 // vtable holding type.
830 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
831 CUE = CUMap.end(); CUI != CUE; ++CUI) {
832 CompileUnit *TheCU = CUI->second;
833 TheCU->constructContainingTypeDIEs();
836 // Standard sections final addresses.
837 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
838 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
839 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
840 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
842 // End text sections.
843 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
844 Asm->OutStreamer.SwitchSection(SectionMap[i]);
845 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
848 // Compute DIE offsets and sizes.
849 computeSizeAndOffsets();
851 // Emit all the DIEs into a debug info section
854 // Corresponding abbreviations into a abbrev section.
857 // Emit info into the dwarf accelerator table sections.
858 if (useDwarfAccelTables()) {
861 emitAccelNamespaces();
865 // Emit info into a debug pubtypes section.
866 // TODO: When we don't need the option anymore we can
867 // remove all of the code that adds to the table.
868 if (useDarwinGDBCompat())
871 // Emit info into a debug loc section.
874 // Emit info into a debug aranges section.
877 // Emit info into a debug ranges section.
880 // Emit info into a debug macinfo section.
884 // TODO: When we don't need the option anymore we
885 // can remove all of the code that this section
887 if (useDarwinGDBCompat())
888 emitDebugInlineInfo();
890 // Emit info into a debug str section.
894 DeleteContainerSeconds(DeadFnScopeMap);
896 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
897 E = CUMap.end(); I != E; ++I)
899 FirstCU = NULL; // Reset for the next Module, if any.
902 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
903 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
905 LLVMContext &Ctx = DV->getContext();
906 // More then one inlined variable corresponds to one abstract variable.
907 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
908 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
910 return AbsDbgVariable;
912 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
916 AbsDbgVariable = new DbgVariable(Var, NULL);
917 addScopeVariable(Scope, AbsDbgVariable);
918 AbstractVariables[Var] = AbsDbgVariable;
919 return AbsDbgVariable;
922 /// addCurrentFnArgument - If Var is a current function argument then add
923 /// it to CurrentFnArguments list.
924 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
925 DbgVariable *Var, LexicalScope *Scope) {
926 if (!LScopes.isCurrentFunctionScope(Scope))
928 DIVariable DV = Var->getVariable();
929 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
931 unsigned ArgNo = DV.getArgNumber();
935 size_t Size = CurrentFnArguments.size();
937 CurrentFnArguments.resize(MF->getFunction()->arg_size());
938 // llvm::Function argument size is not good indicator of how many
939 // arguments does the function have at source level.
941 CurrentFnArguments.resize(ArgNo * 2);
942 CurrentFnArguments[ArgNo - 1] = Var;
946 /// collectVariableInfoFromMMITable - Collect variable information from
947 /// side table maintained by MMI.
949 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
950 SmallPtrSet<const MDNode *, 16> &Processed) {
951 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
952 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
953 VE = VMap.end(); VI != VE; ++VI) {
954 const MDNode *Var = VI->first;
956 Processed.insert(Var);
958 const std::pair<unsigned, DebugLoc> &VP = VI->second;
960 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
962 // If variable scope is not found then skip this variable.
966 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
967 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
968 RegVar->setFrameIndex(VP.first);
969 if (!addCurrentFnArgument(MF, RegVar, Scope))
970 addScopeVariable(Scope, RegVar);
972 AbsDbgVariable->setFrameIndex(VP.first);
976 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
977 /// DBG_VALUE instruction, is in a defined reg.
978 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
979 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
980 return MI->getNumOperands() == 3 &&
981 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
982 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
985 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
987 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
988 const MCSymbol *FLabel,
989 const MCSymbol *SLabel,
990 const MachineInstr *MI) {
991 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
993 if (MI->getNumOperands() != 3) {
994 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
995 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
997 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
998 MachineLocation MLoc;
999 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1000 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1002 if (MI->getOperand(0).isImm())
1003 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1004 if (MI->getOperand(0).isFPImm())
1005 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1006 if (MI->getOperand(0).isCImm())
1007 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1009 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1012 /// collectVariableInfo - Find variables for each lexical scope.
1014 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1015 SmallPtrSet<const MDNode *, 16> &Processed) {
1017 /// collection info from MMI table.
1018 collectVariableInfoFromMMITable(MF, Processed);
1020 for (SmallVectorImpl<const MDNode*>::const_iterator
1021 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1023 const MDNode *Var = *UVI;
1024 if (Processed.count(Var))
1027 // History contains relevant DBG_VALUE instructions for Var and instructions
1029 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1030 if (History.empty())
1032 const MachineInstr *MInsn = History.front();
1035 LexicalScope *Scope = NULL;
1036 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1037 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1038 Scope = LScopes.getCurrentFunctionScope();
1040 if (DV.getVersion() <= LLVMDebugVersion9)
1041 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1043 if (MDNode *IA = DV.getInlinedAt())
1044 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1046 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1049 // If variable scope is not found then skip this variable.
1053 Processed.insert(DV);
1054 assert(MInsn->isDebugValue() && "History must begin with debug value");
1055 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1056 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1057 if (!addCurrentFnArgument(MF, RegVar, Scope))
1058 addScopeVariable(Scope, RegVar);
1060 AbsVar->setMInsn(MInsn);
1062 // Simple ranges that are fully coalesced.
1063 if (History.size() <= 1 || (History.size() == 2 &&
1064 MInsn->isIdenticalTo(History.back()))) {
1065 RegVar->setMInsn(MInsn);
1069 // handle multiple DBG_VALUE instructions describing one variable.
1070 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1072 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1073 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1074 const MachineInstr *Begin = *HI;
1075 assert(Begin->isDebugValue() && "Invalid History entry");
1077 // Check if DBG_VALUE is truncating a range.
1078 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1079 && !Begin->getOperand(0).getReg())
1082 // Compute the range for a register location.
1083 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1084 const MCSymbol *SLabel = 0;
1087 // If Begin is the last instruction in History then its value is valid
1088 // until the end of the function.
1089 SLabel = FunctionEndSym;
1091 const MachineInstr *End = HI[1];
1092 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1093 << "\t" << *Begin << "\t" << *End << "\n");
1094 if (End->isDebugValue())
1095 SLabel = getLabelBeforeInsn(End);
1097 // End is a normal instruction clobbering the range.
1098 SLabel = getLabelAfterInsn(End);
1099 assert(SLabel && "Forgot label after clobber instruction");
1104 // The value is valid until the next DBG_VALUE or clobber.
1105 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1108 DotDebugLocEntries.push_back(DotDebugLocEntry());
1111 // Collect info for variables that were optimized out.
1112 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1113 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1114 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1115 DIVariable DV(Variables.getElement(i));
1116 if (!DV || !DV.Verify() || !Processed.insert(DV))
1118 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1119 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1123 /// getLabelBeforeInsn - Return Label preceding the instruction.
1124 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1125 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1126 assert(Label && "Didn't insert label before instruction");
1130 /// getLabelAfterInsn - Return Label immediately following the instruction.
1131 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1132 return LabelsAfterInsn.lookup(MI);
1135 /// beginInstruction - Process beginning of an instruction.
1136 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1137 // Check if source location changes, but ignore DBG_VALUE locations.
1138 if (!MI->isDebugValue()) {
1139 DebugLoc DL = MI->getDebugLoc();
1140 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1143 if (DL == PrologEndLoc) {
1144 Flags |= DWARF2_FLAG_PROLOGUE_END;
1145 PrologEndLoc = DebugLoc();
1147 if (PrologEndLoc.isUnknown())
1148 Flags |= DWARF2_FLAG_IS_STMT;
1150 if (!DL.isUnknown()) {
1151 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1152 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1154 recordSourceLine(0, 0, 0, 0);
1158 // Insert labels where requested.
1159 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1160 LabelsBeforeInsn.find(MI);
1163 if (I == LabelsBeforeInsn.end())
1166 // Label already assigned.
1171 PrevLabel = MMI->getContext().CreateTempSymbol();
1172 Asm->OutStreamer.EmitLabel(PrevLabel);
1174 I->second = PrevLabel;
1177 /// endInstruction - Process end of an instruction.
1178 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1179 // Don't create a new label after DBG_VALUE instructions.
1180 // They don't generate code.
1181 if (!MI->isDebugValue())
1184 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1185 LabelsAfterInsn.find(MI);
1188 if (I == LabelsAfterInsn.end())
1191 // Label already assigned.
1195 // We need a label after this instruction.
1197 PrevLabel = MMI->getContext().CreateTempSymbol();
1198 Asm->OutStreamer.EmitLabel(PrevLabel);
1200 I->second = PrevLabel;
1203 /// identifyScopeMarkers() -
1204 /// Each LexicalScope has first instruction and last instruction to mark
1205 /// beginning and end of a scope respectively. Create an inverse map that list
1206 /// scopes starts (and ends) with an instruction. One instruction may start (or
1207 /// end) multiple scopes. Ignore scopes that are not reachable.
1208 void DwarfDebug::identifyScopeMarkers() {
1209 SmallVector<LexicalScope *, 4> WorkList;
1210 WorkList.push_back(LScopes.getCurrentFunctionScope());
1211 while (!WorkList.empty()) {
1212 LexicalScope *S = WorkList.pop_back_val();
1214 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1215 if (!Children.empty())
1216 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1217 SE = Children.end(); SI != SE; ++SI)
1218 WorkList.push_back(*SI);
1220 if (S->isAbstractScope())
1223 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1226 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1227 RE = Ranges.end(); RI != RE; ++RI) {
1228 assert(RI->first && "InsnRange does not have first instruction!");
1229 assert(RI->second && "InsnRange does not have second instruction!");
1230 requestLabelBeforeInsn(RI->first);
1231 requestLabelAfterInsn(RI->second);
1236 /// getScopeNode - Get MDNode for DebugLoc's scope.
1237 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1238 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1239 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1240 return DL.getScope(Ctx);
1243 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1244 /// line number info for the function.
1245 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1246 const MDNode *Scope = getScopeNode(DL, Ctx);
1247 DISubprogram SP = getDISubprogram(Scope);
1249 // Check for number of operands since the compatibility is
1251 if (SP->getNumOperands() > 19)
1252 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1254 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1260 /// beginFunction - Gather pre-function debug information. Assumes being
1261 /// emitted immediately after the function entry point.
1262 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1263 if (!MMI->hasDebugInfo()) return;
1264 LScopes.initialize(*MF);
1265 if (LScopes.empty()) return;
1266 identifyScopeMarkers();
1268 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1269 Asm->getFunctionNumber());
1270 // Assumes in correct section after the entry point.
1271 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1273 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1275 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1276 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1277 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1279 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1281 bool AtBlockEntry = true;
1282 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1284 const MachineInstr *MI = II;
1286 if (MI->isDebugValue()) {
1287 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1289 // Keep track of user variables.
1291 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1293 // Variable is in a register, we need to check for clobbers.
1294 if (isDbgValueInDefinedReg(MI))
1295 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1297 // Check the history of this variable.
1298 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1299 if (History.empty()) {
1300 UserVariables.push_back(Var);
1301 // The first mention of a function argument gets the FunctionBeginSym
1302 // label, so arguments are visible when breaking at function entry.
1304 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1305 DISubprogram(getDISubprogram(DV.getContext()))
1306 .describes(MF->getFunction()))
1307 LabelsBeforeInsn[MI] = FunctionBeginSym;
1309 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1310 const MachineInstr *Prev = History.back();
1311 if (Prev->isDebugValue()) {
1312 // Coalesce identical entries at the end of History.
1313 if (History.size() >= 2 &&
1314 Prev->isIdenticalTo(History[History.size() - 2])) {
1315 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1317 << "\t" << *History[History.size() - 2] << "\n");
1321 // Terminate old register assignments that don't reach MI;
1322 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1323 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1324 isDbgValueInDefinedReg(Prev)) {
1325 // Previous register assignment needs to terminate at the end of
1327 MachineBasicBlock::const_iterator LastMI =
1328 PrevMBB->getLastNonDebugInstr();
1329 if (LastMI == PrevMBB->end()) {
1330 // Drop DBG_VALUE for empty range.
1331 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1332 << "\t" << *Prev << "\n");
1336 // Terminate after LastMI.
1337 History.push_back(LastMI);
1342 History.push_back(MI);
1344 // Not a DBG_VALUE instruction.
1346 AtBlockEntry = false;
1348 // First known non DBG_VALUE location marks beginning of function
1350 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1351 PrologEndLoc = MI->getDebugLoc();
1353 // Check if the instruction clobbers any registers with debug vars.
1354 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1355 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1356 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1358 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1359 AI.isValid(); ++AI) {
1361 const MDNode *Var = LiveUserVar[Reg];
1364 // Reg is now clobbered.
1365 LiveUserVar[Reg] = 0;
1367 // Was MD last defined by a DBG_VALUE referring to Reg?
1368 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1369 if (HistI == DbgValues.end())
1371 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1372 if (History.empty())
1374 const MachineInstr *Prev = History.back();
1375 // Sanity-check: Register assignments are terminated at the end of
1377 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1379 // Is the variable still in Reg?
1380 if (!isDbgValueInDefinedReg(Prev) ||
1381 Prev->getOperand(0).getReg() != Reg)
1383 // Var is clobbered. Make sure the next instruction gets a label.
1384 History.push_back(MI);
1391 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1393 SmallVectorImpl<const MachineInstr*> &History = I->second;
1394 if (History.empty())
1397 // Make sure the final register assignments are terminated.
1398 const MachineInstr *Prev = History.back();
1399 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1400 const MachineBasicBlock *PrevMBB = Prev->getParent();
1401 MachineBasicBlock::const_iterator LastMI =
1402 PrevMBB->getLastNonDebugInstr();
1403 if (LastMI == PrevMBB->end())
1404 // Drop DBG_VALUE for empty range.
1407 // Terminate after LastMI.
1408 History.push_back(LastMI);
1411 // Request labels for the full history.
1412 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1413 const MachineInstr *MI = History[i];
1414 if (MI->isDebugValue())
1415 requestLabelBeforeInsn(MI);
1417 requestLabelAfterInsn(MI);
1421 PrevInstLoc = DebugLoc();
1422 PrevLabel = FunctionBeginSym;
1424 // Record beginning of function.
1425 if (!PrologEndLoc.isUnknown()) {
1426 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1427 MF->getFunction()->getContext());
1428 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1429 FnStartDL.getScope(MF->getFunction()->getContext()),
1434 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1435 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1436 ScopeVariables[LS].push_back(Var);
1437 // Vars.push_back(Var);
1440 /// endFunction - Gather and emit post-function debug information.
1442 void DwarfDebug::endFunction(const MachineFunction *MF) {
1443 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1445 // Define end label for subprogram.
1446 FunctionEndSym = Asm->GetTempSymbol("func_end",
1447 Asm->getFunctionNumber());
1448 // Assumes in correct section after the entry point.
1449 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1451 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1452 collectVariableInfo(MF, ProcessedVars);
1454 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1455 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1456 assert(TheCU && "Unable to find compile unit!");
1458 // Construct abstract scopes.
1459 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1460 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1461 LexicalScope *AScope = AList[i];
1462 DISubprogram SP(AScope->getScopeNode());
1464 // Collect info for variables that were optimized out.
1465 DIArray Variables = SP.getVariables();
1466 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1467 DIVariable DV(Variables.getElement(i));
1468 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1470 // Check that DbgVariable for DV wasn't created earlier, when
1471 // findAbstractVariable() was called for inlined instance of DV.
1472 LLVMContext &Ctx = DV->getContext();
1473 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1474 if (AbstractVariables.lookup(CleanDV))
1476 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1477 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1480 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1481 constructScopeDIE(TheCU, AScope);
1484 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1486 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1487 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1489 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1490 MMI->getFrameMoves()));
1493 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1494 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1495 DeleteContainerPointers(I->second);
1496 ScopeVariables.clear();
1497 DeleteContainerPointers(CurrentFnArguments);
1498 UserVariables.clear();
1500 AbstractVariables.clear();
1501 LabelsBeforeInsn.clear();
1502 LabelsAfterInsn.clear();
1506 /// recordSourceLine - Register a source line with debug info. Returns the
1507 /// unique label that was emitted and which provides correspondence to
1508 /// the source line list.
1509 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1515 DIDescriptor Scope(S);
1517 if (Scope.isCompileUnit()) {
1518 DICompileUnit CU(S);
1519 Fn = CU.getFilename();
1520 Dir = CU.getDirectory();
1521 } else if (Scope.isFile()) {
1523 Fn = F.getFilename();
1524 Dir = F.getDirectory();
1525 } else if (Scope.isSubprogram()) {
1527 Fn = SP.getFilename();
1528 Dir = SP.getDirectory();
1529 } else if (Scope.isLexicalBlockFile()) {
1530 DILexicalBlockFile DBF(S);
1531 Fn = DBF.getFilename();
1532 Dir = DBF.getDirectory();
1533 } else if (Scope.isLexicalBlock()) {
1534 DILexicalBlock DB(S);
1535 Fn = DB.getFilename();
1536 Dir = DB.getDirectory();
1538 llvm_unreachable("Unexpected scope info");
1540 Src = GetOrCreateSourceID(Fn, Dir);
1542 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1545 //===----------------------------------------------------------------------===//
1547 //===----------------------------------------------------------------------===//
1549 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1552 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1553 // Get the children.
1554 const std::vector<DIE *> &Children = Die->getChildren();
1556 // Record the abbreviation.
1557 assignAbbrevNumber(Die->getAbbrev());
1559 // Get the abbreviation for this DIE.
1560 unsigned AbbrevNumber = Die->getAbbrevNumber();
1561 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1564 Die->setOffset(Offset);
1566 // Start the size with the size of abbreviation code.
1567 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1569 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1570 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1572 // Size the DIE attribute values.
1573 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1574 // Size attribute value.
1575 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1577 // Size the DIE children if any.
1578 if (!Children.empty()) {
1579 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1580 "Children flag not set");
1582 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1583 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1585 // End of children marker.
1586 Offset += sizeof(int8_t);
1589 Die->setSize(Offset - Die->getOffset());
1593 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1595 void DwarfDebug::computeSizeAndOffsets() {
1596 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1597 E = CUMap.end(); I != E; ++I) {
1598 // Compute size of compile unit header.
1600 sizeof(int32_t) + // Length of Compilation Unit Info
1601 sizeof(int16_t) + // DWARF version number
1602 sizeof(int32_t) + // Offset Into Abbrev. Section
1603 sizeof(int8_t); // Pointer Size (in bytes)
1604 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1608 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1609 /// the start of each one.
1610 void DwarfDebug::EmitSectionLabels() {
1611 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1613 // Dwarf sections base addresses.
1614 DwarfInfoSectionSym =
1615 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1616 DwarfAbbrevSectionSym =
1617 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1618 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1620 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1621 EmitSectionSym(Asm, MacroInfo);
1623 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1624 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1625 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1626 DwarfStrSectionSym =
1627 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1628 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1631 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1632 "section_debug_loc");
1634 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1635 EmitSectionSym(Asm, TLOF.getDataSection());
1638 /// emitDIE - Recursively emits a debug information entry.
1640 void DwarfDebug::emitDIE(DIE *Die) {
1641 // Get the abbreviation for this DIE.
1642 unsigned AbbrevNumber = Die->getAbbrevNumber();
1643 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1645 // Emit the code (index) for the abbreviation.
1646 if (Asm->isVerbose())
1647 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1648 Twine::utohexstr(Die->getOffset()) + ":0x" +
1649 Twine::utohexstr(Die->getSize()) + " " +
1650 dwarf::TagString(Abbrev->getTag()));
1651 Asm->EmitULEB128(AbbrevNumber);
1653 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1654 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1656 // Emit the DIE attribute values.
1657 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1658 unsigned Attr = AbbrevData[i].getAttribute();
1659 unsigned Form = AbbrevData[i].getForm();
1660 assert(Form && "Too many attributes for DIE (check abbreviation)");
1662 if (Asm->isVerbose())
1663 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1666 case dwarf::DW_AT_abstract_origin: {
1667 DIEEntry *E = cast<DIEEntry>(Values[i]);
1668 DIE *Origin = E->getEntry();
1669 unsigned Addr = Origin->getOffset();
1670 Asm->EmitInt32(Addr);
1673 case dwarf::DW_AT_ranges: {
1674 // DW_AT_range Value encodes offset in debug_range section.
1675 DIEInteger *V = cast<DIEInteger>(Values[i]);
1677 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1678 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1682 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1684 DwarfDebugRangeSectionSym,
1689 case dwarf::DW_AT_location: {
1690 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1691 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1692 Asm->EmitLabelReference(L->getValue(), 4);
1694 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1696 Values[i]->EmitValue(Asm, Form);
1700 case dwarf::DW_AT_accessibility: {
1701 if (Asm->isVerbose()) {
1702 DIEInteger *V = cast<DIEInteger>(Values[i]);
1703 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1705 Values[i]->EmitValue(Asm, Form);
1709 // Emit an attribute using the defined form.
1710 Values[i]->EmitValue(Asm, Form);
1715 // Emit the DIE children if any.
1716 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1717 const std::vector<DIE *> &Children = Die->getChildren();
1719 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1720 emitDIE(Children[j]);
1722 if (Asm->isVerbose())
1723 Asm->OutStreamer.AddComment("End Of Children Mark");
1728 /// emitDebugInfo - Emit the debug info section.
1730 void DwarfDebug::emitDebugInfo() {
1731 // Start debug info section.
1732 Asm->OutStreamer.SwitchSection(
1733 Asm->getObjFileLowering().getDwarfInfoSection());
1734 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1735 E = CUMap.end(); I != E; ++I) {
1736 CompileUnit *TheCU = I->second;
1737 DIE *Die = TheCU->getCUDie();
1739 // Emit the compile units header.
1740 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1743 // Emit size of content not including length itself
1744 unsigned ContentSize = Die->getSize() +
1745 sizeof(int16_t) + // DWARF version number
1746 sizeof(int32_t) + // Offset Into Abbrev. Section
1747 sizeof(int8_t); // Pointer Size (in bytes)
1749 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1750 Asm->EmitInt32(ContentSize);
1751 Asm->OutStreamer.AddComment("DWARF version number");
1752 Asm->EmitInt16(dwarf::DWARF_VERSION);
1753 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1754 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1755 DwarfAbbrevSectionSym);
1756 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1757 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1760 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1764 /// emitAbbreviations - Emit the abbreviation section.
1766 void DwarfDebug::emitAbbreviations() const {
1767 // Check to see if it is worth the effort.
1768 if (!Abbreviations.empty()) {
1769 // Start the debug abbrev section.
1770 Asm->OutStreamer.SwitchSection(
1771 Asm->getObjFileLowering().getDwarfAbbrevSection());
1773 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1775 // For each abbrevation.
1776 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1777 // Get abbreviation data
1778 const DIEAbbrev *Abbrev = Abbreviations[i];
1780 // Emit the abbrevations code (base 1 index.)
1781 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1783 // Emit the abbreviations data.
1787 // Mark end of abbreviations.
1788 Asm->EmitULEB128(0, "EOM(3)");
1790 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1794 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1795 /// the line matrix.
1797 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1798 // Define last address of section.
1799 Asm->OutStreamer.AddComment("Extended Op");
1802 Asm->OutStreamer.AddComment("Op size");
1803 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1804 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1805 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1807 Asm->OutStreamer.AddComment("Section end label");
1809 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1810 Asm->getTargetData().getPointerSize(),
1813 // Mark end of matrix.
1814 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1820 /// emitAccelNames - Emit visible names into a hashed accelerator table
1822 void DwarfDebug::emitAccelNames() {
1823 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1824 dwarf::DW_FORM_data4));
1825 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1826 E = CUMap.end(); I != E; ++I) {
1827 CompileUnit *TheCU = I->second;
1828 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1829 for (StringMap<std::vector<DIE*> >::const_iterator
1830 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1831 const char *Name = GI->getKeyData();
1832 const std::vector<DIE *> &Entities = GI->second;
1833 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1834 DE = Entities.end(); DI != DE; ++DI)
1835 AT.AddName(Name, (*DI));
1839 AT.FinalizeTable(Asm, "Names");
1840 Asm->OutStreamer.SwitchSection(
1841 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1842 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1843 Asm->OutStreamer.EmitLabel(SectionBegin);
1845 // Emit the full data.
1846 AT.Emit(Asm, SectionBegin, this);
1849 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1850 /// accelerator table section.
1851 void DwarfDebug::emitAccelObjC() {
1852 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1853 dwarf::DW_FORM_data4));
1854 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1855 E = CUMap.end(); I != E; ++I) {
1856 CompileUnit *TheCU = I->second;
1857 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1858 for (StringMap<std::vector<DIE*> >::const_iterator
1859 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1860 const char *Name = GI->getKeyData();
1861 const std::vector<DIE *> &Entities = GI->second;
1862 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1863 DE = Entities.end(); DI != DE; ++DI)
1864 AT.AddName(Name, (*DI));
1868 AT.FinalizeTable(Asm, "ObjC");
1869 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1870 .getDwarfAccelObjCSection());
1871 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1872 Asm->OutStreamer.EmitLabel(SectionBegin);
1874 // Emit the full data.
1875 AT.Emit(Asm, SectionBegin, this);
1878 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1880 void DwarfDebug::emitAccelNamespaces() {
1881 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1882 dwarf::DW_FORM_data4));
1883 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1884 E = CUMap.end(); I != E; ++I) {
1885 CompileUnit *TheCU = I->second;
1886 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
1887 for (StringMap<std::vector<DIE*> >::const_iterator
1888 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1889 const char *Name = GI->getKeyData();
1890 const std::vector<DIE *> &Entities = GI->second;
1891 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1892 DE = Entities.end(); DI != DE; ++DI)
1893 AT.AddName(Name, (*DI));
1897 AT.FinalizeTable(Asm, "namespac");
1898 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1899 .getDwarfAccelNamespaceSection());
1900 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1901 Asm->OutStreamer.EmitLabel(SectionBegin);
1903 // Emit the full data.
1904 AT.Emit(Asm, SectionBegin, this);
1907 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1908 void DwarfDebug::emitAccelTypes() {
1909 std::vector<DwarfAccelTable::Atom> Atoms;
1910 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1911 dwarf::DW_FORM_data4));
1912 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
1913 dwarf::DW_FORM_data2));
1914 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
1915 dwarf::DW_FORM_data1));
1916 DwarfAccelTable AT(Atoms);
1917 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1918 E = CUMap.end(); I != E; ++I) {
1919 CompileUnit *TheCU = I->second;
1920 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
1921 = TheCU->getAccelTypes();
1922 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
1923 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1924 const char *Name = GI->getKeyData();
1925 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
1926 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
1927 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
1928 AT.AddName(Name, (*DI).first, (*DI).second);
1932 AT.FinalizeTable(Asm, "types");
1933 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1934 .getDwarfAccelTypesSection());
1935 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1936 Asm->OutStreamer.EmitLabel(SectionBegin);
1938 // Emit the full data.
1939 AT.Emit(Asm, SectionBegin, this);
1942 void DwarfDebug::emitDebugPubTypes() {
1943 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1944 E = CUMap.end(); I != E; ++I) {
1945 CompileUnit *TheCU = I->second;
1946 // Start the dwarf pubtypes section.
1947 Asm->OutStreamer.SwitchSection(
1948 Asm->getObjFileLowering().getDwarfPubTypesSection());
1949 Asm->OutStreamer.AddComment("Length of Public Types Info");
1950 Asm->EmitLabelDifference(
1951 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1952 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1954 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1957 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1958 Asm->EmitInt16(dwarf::DWARF_VERSION);
1960 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1961 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1962 DwarfInfoSectionSym);
1964 Asm->OutStreamer.AddComment("Compilation Unit Length");
1965 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1966 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1969 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1970 for (StringMap<DIE*>::const_iterator
1971 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1972 const char *Name = GI->getKeyData();
1973 DIE *Entity = GI->second;
1975 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1976 Asm->EmitInt32(Entity->getOffset());
1978 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1979 // Emit the name with a terminating null byte.
1980 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1983 Asm->OutStreamer.AddComment("End Mark");
1985 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1990 /// emitDebugStr - Emit visible names into a debug str section.
1992 void DwarfDebug::emitDebugStr() {
1993 // Check to see if it is worth the effort.
1994 if (StringPool.empty()) return;
1996 // Start the dwarf str section.
1997 Asm->OutStreamer.SwitchSection(
1998 Asm->getObjFileLowering().getDwarfStrSection());
2000 // Get all of the string pool entries and put them in an array by their ID so
2001 // we can sort them.
2002 SmallVector<std::pair<unsigned,
2003 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2005 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2006 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2007 Entries.push_back(std::make_pair(I->second.second, &*I));
2009 array_pod_sort(Entries.begin(), Entries.end());
2011 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2012 // Emit a label for reference from debug information entries.
2013 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2015 // Emit the string itself with a terminating null byte.
2016 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2017 Entries[i].second->getKeyLength()+1),
2022 /// emitDebugLoc - Emit visible names into a debug loc section.
2024 void DwarfDebug::emitDebugLoc() {
2025 if (DotDebugLocEntries.empty())
2028 for (SmallVector<DotDebugLocEntry, 4>::iterator
2029 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2031 DotDebugLocEntry &Entry = *I;
2032 if (I + 1 != DotDebugLocEntries.end())
2036 // Start the dwarf loc section.
2037 Asm->OutStreamer.SwitchSection(
2038 Asm->getObjFileLowering().getDwarfLocSection());
2039 unsigned char Size = Asm->getTargetData().getPointerSize();
2040 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2042 for (SmallVector<DotDebugLocEntry, 4>::iterator
2043 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2044 I != E; ++I, ++index) {
2045 DotDebugLocEntry &Entry = *I;
2046 if (Entry.isMerged()) continue;
2047 if (Entry.isEmpty()) {
2048 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2049 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2050 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2052 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2053 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2054 DIVariable DV(Entry.Variable);
2055 Asm->OutStreamer.AddComment("Loc expr size");
2056 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2057 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2058 Asm->EmitLabelDifference(end, begin, 2);
2059 Asm->OutStreamer.EmitLabel(begin);
2060 if (Entry.isInt()) {
2061 DIBasicType BTy(DV.getType());
2063 (BTy.getEncoding() == dwarf::DW_ATE_signed
2064 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2065 Asm->OutStreamer.AddComment("DW_OP_consts");
2066 Asm->EmitInt8(dwarf::DW_OP_consts);
2067 Asm->EmitSLEB128(Entry.getInt());
2069 Asm->OutStreamer.AddComment("DW_OP_constu");
2070 Asm->EmitInt8(dwarf::DW_OP_constu);
2071 Asm->EmitULEB128(Entry.getInt());
2073 } else if (Entry.isLocation()) {
2074 if (!DV.hasComplexAddress())
2076 Asm->EmitDwarfRegOp(Entry.Loc);
2078 // Complex address entry.
2079 unsigned N = DV.getNumAddrElements();
2081 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2082 if (Entry.Loc.getOffset()) {
2084 Asm->EmitDwarfRegOp(Entry.Loc);
2085 Asm->OutStreamer.AddComment("DW_OP_deref");
2086 Asm->EmitInt8(dwarf::DW_OP_deref);
2087 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2088 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2089 Asm->EmitSLEB128(DV.getAddrElement(1));
2091 // If first address element is OpPlus then emit
2092 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2093 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2094 Asm->EmitDwarfRegOp(Loc);
2098 Asm->EmitDwarfRegOp(Entry.Loc);
2101 // Emit remaining complex address elements.
2102 for (; i < N; ++i) {
2103 uint64_t Element = DV.getAddrElement(i);
2104 if (Element == DIBuilder::OpPlus) {
2105 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2106 Asm->EmitULEB128(DV.getAddrElement(++i));
2107 } else if (Element == DIBuilder::OpDeref) {
2108 if (!Entry.Loc.isReg())
2109 Asm->EmitInt8(dwarf::DW_OP_deref);
2111 llvm_unreachable("unknown Opcode found in complex address");
2115 // else ... ignore constant fp. There is not any good way to
2116 // to represent them here in dwarf.
2117 Asm->OutStreamer.EmitLabel(end);
2122 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2124 void DwarfDebug::EmitDebugARanges() {
2125 // Start the dwarf aranges section.
2126 Asm->OutStreamer.SwitchSection(
2127 Asm->getObjFileLowering().getDwarfARangesSection());
2130 /// emitDebugRanges - Emit visible names into a debug ranges section.
2132 void DwarfDebug::emitDebugRanges() {
2133 // Start the dwarf ranges section.
2134 Asm->OutStreamer.SwitchSection(
2135 Asm->getObjFileLowering().getDwarfRangesSection());
2136 unsigned char Size = Asm->getTargetData().getPointerSize();
2137 for (SmallVector<const MCSymbol *, 8>::iterator
2138 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2141 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2143 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2147 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2149 void DwarfDebug::emitDebugMacInfo() {
2150 if (const MCSection *LineInfo =
2151 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2152 // Start the dwarf macinfo section.
2153 Asm->OutStreamer.SwitchSection(LineInfo);
2157 /// emitDebugInlineInfo - Emit inline info using following format.
2159 /// 1. length of section
2160 /// 2. Dwarf version number
2161 /// 3. address size.
2163 /// Entries (one "entry" for each function that was inlined):
2165 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2166 /// otherwise offset into __debug_str for regular function name.
2167 /// 2. offset into __debug_str section for regular function name.
2168 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2169 /// instances for the function.
2171 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2172 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2173 /// __debug_info section, and the low_pc is the starting address for the
2174 /// inlining instance.
2175 void DwarfDebug::emitDebugInlineInfo() {
2176 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2182 Asm->OutStreamer.SwitchSection(
2183 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2185 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2186 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2187 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2189 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2191 Asm->OutStreamer.AddComment("Dwarf Version");
2192 Asm->EmitInt16(dwarf::DWARF_VERSION);
2193 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2194 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2196 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2197 E = InlinedSPNodes.end(); I != E; ++I) {
2199 const MDNode *Node = *I;
2200 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2201 = InlineInfo.find(Node);
2202 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2203 DISubprogram SP(Node);
2204 StringRef LName = SP.getLinkageName();
2205 StringRef Name = SP.getName();
2207 Asm->OutStreamer.AddComment("MIPS linkage name");
2209 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2211 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2212 DwarfStrSectionSym);
2214 Asm->OutStreamer.AddComment("Function name");
2215 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2216 Asm->EmitULEB128(Labels.size(), "Inline count");
2218 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2219 LE = Labels.end(); LI != LE; ++LI) {
2220 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2221 Asm->EmitInt32(LI->second->getOffset());
2223 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2224 Asm->OutStreamer.EmitSymbolValue(LI->first,
2225 Asm->getTargetData().getPointerSize(),0);
2229 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));