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 "DwarfCompileUnit.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Analysis/DIBuilder.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/Path.h"
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
49 cl::desc("Disable debug info printing"));
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52 cl::desc("Make an absence of debug location information explicit."),
56 const char *DWARFGroupName = "DWARF Emission";
57 const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
60 //===----------------------------------------------------------------------===//
62 /// Configuration values for initial hash set sizes (log2).
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
68 DIType DbgVariable::getType() const {
69 DIType Ty = Var.getType();
70 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
72 if (Var.isBlockByrefVariable()) {
73 /* Byref variables, in Blocks, are declared by the programmer as
74 "SomeType VarName;", but the compiler creates a
75 __Block_byref_x_VarName struct, and gives the variable VarName
76 either the struct, or a pointer to the struct, as its type. This
77 is necessary for various behind-the-scenes things the compiler
78 needs to do with by-reference variables in blocks.
80 However, as far as the original *programmer* is concerned, the
81 variable should still have type 'SomeType', as originally declared.
83 The following function dives into the __Block_byref_x_VarName
84 struct to find the original type of the variable. This will be
85 passed back to the code generating the type for the Debug
86 Information Entry for the variable 'VarName'. 'VarName' will then
87 have the original type 'SomeType' in its debug information.
89 The original type 'SomeType' will be the type of the field named
90 'VarName' inside the __Block_byref_x_VarName struct.
92 NOTE: In order for this to not completely fail on the debugger
93 side, the Debug Information Entry for the variable VarName needs to
94 have a DW_AT_location that tells the debugger how to unwind through
95 the pointers and __Block_byref_x_VarName struct to find the actual
96 value of the variable. The function addBlockByrefType does this. */
98 unsigned tag = Ty.getTag();
100 if (tag == dwarf::DW_TAG_pointer_type) {
101 DIDerivedType DTy = DIDerivedType(Ty);
102 subType = DTy.getTypeDerivedFrom();
105 DICompositeType blockStruct = DICompositeType(subType);
106 DIArray Elements = blockStruct.getTypeArray();
108 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
109 DIDescriptor Element = Elements.getElement(i);
110 DIDerivedType DT = DIDerivedType(Element);
111 if (getName() == DT.getName())
112 return (DT.getTypeDerivedFrom());
119 } // end llvm namespace
121 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
122 : Asm(A), MMI(Asm->MMI), FirstCU(0),
123 AbbreviationsSet(InitAbbreviationsSetSize),
125 NextStringPoolNumber = 0;
127 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
128 DwarfStrSectionSym = TextSectionSym = 0;
129 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
130 FunctionBeginSym = FunctionEndSym = 0;
132 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
136 DwarfDebug::~DwarfDebug() {
139 MCSymbol *DwarfDebug::getStringPool() {
140 return Asm->GetTempSymbol("section_str");
143 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
144 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
145 if (Entry.first) return Entry.first;
147 Entry.second = NextStringPoolNumber++;
148 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
152 /// assignAbbrevNumber - Define a unique number for the abbreviation.
154 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
155 // Profile the node so that we can make it unique.
159 // Check the set for priors.
160 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
162 // If it's newly added.
163 if (InSet == &Abbrev) {
164 // Add to abbreviation list.
165 Abbreviations.push_back(&Abbrev);
167 // Assign the vector position + 1 as its number.
168 Abbrev.setNumber(Abbreviations.size());
170 // Assign existing abbreviation number.
171 Abbrev.setNumber(InSet->getNumber());
175 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
176 /// printer to not emit usual symbol prefix before the symbol name is used then
177 /// return linkage name after skipping this special LLVM prefix.
178 static StringRef getRealLinkageName(StringRef LinkageName) {
180 if (LinkageName.startswith(StringRef(&One, 1)))
181 return LinkageName.substr(1);
185 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
186 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
187 /// If there are global variables in this scope then create and insert
188 /// DIEs for these variables.
189 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
190 const MDNode *SPNode) {
191 DIE *SPDie = SPCU->getDIE(SPNode);
193 assert(SPDie && "Unable to find subprogram DIE!");
194 DISubprogram SP(SPNode);
196 DISubprogram SPDecl = SP.getFunctionDeclaration();
197 if (!SPDecl.isSubprogram()) {
198 // There is not any need to generate specification DIE for a function
199 // defined at compile unit level. If a function is defined inside another
200 // function then gdb prefers the definition at top level and but does not
201 // expect specification DIE in parent function. So avoid creating
202 // specification DIE for a function defined inside a function.
203 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
204 !SP.getContext().isFile() &&
205 !isSubprogramContext(SP.getContext())) {
206 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
209 DICompositeType SPTy = SP.getType();
210 DIArray Args = SPTy.getTypeArray();
211 unsigned SPTag = SPTy.getTag();
212 if (SPTag == dwarf::DW_TAG_subroutine_type)
213 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
214 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
215 DIType ATy = DIType(DIType(Args.getElement(i)));
216 SPCU->addType(Arg, ATy);
217 if (ATy.isArtificial())
218 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
219 SPDie->addChild(Arg);
221 DIE *SPDeclDie = SPDie;
222 SPDie = new DIE(dwarf::DW_TAG_subprogram);
223 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
228 // Pick up abstract subprogram DIE.
229 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
230 SPDie = new DIE(dwarf::DW_TAG_subprogram);
231 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
232 dwarf::DW_FORM_ref4, AbsSPDIE);
236 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
237 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
238 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
239 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
240 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
241 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
242 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
247 /// constructLexicalScope - Construct new DW_TAG_lexical_block
248 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
249 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
250 LexicalScope *Scope) {
251 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
252 if (Scope->isAbstractScope())
255 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
259 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
260 if (Ranges.size() > 1) {
261 // .debug_range section has not been laid out yet. Emit offset in
262 // .debug_range as a uint, size 4, for now. emitDIE will handle
263 // DW_AT_ranges appropriately.
264 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
265 DebugRangeSymbols.size()
266 * Asm->getTargetData().getPointerSize());
267 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
268 RE = Ranges.end(); RI != RE; ++RI) {
269 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
270 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
272 DebugRangeSymbols.push_back(NULL);
273 DebugRangeSymbols.push_back(NULL);
277 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
278 const MCSymbol *End = getLabelAfterInsn(RI->second);
280 if (End == 0) return 0;
282 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
283 assert(End->isDefined() && "Invalid end label for an inlined scope!");
285 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
286 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
291 /// constructInlinedScopeDIE - This scope represents inlined body of
292 /// a function. Construct DIE to represent this concrete inlined copy
294 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
295 LexicalScope *Scope) {
296 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
297 assert(Ranges.empty() == false &&
298 "LexicalScope does not have instruction markers!");
300 if (!Scope->getScopeNode())
302 DIScope DS(Scope->getScopeNode());
303 DISubprogram InlinedSP = getDISubprogram(DS);
304 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
306 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
310 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
311 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
312 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
314 if (StartLabel == 0 || EndLabel == 0) {
315 assert(0 && "Unexpected Start and End labels for a inlined scope!");
318 assert(StartLabel->isDefined() &&
319 "Invalid starting label for an inlined scope!");
320 assert(EndLabel->isDefined() &&
321 "Invalid end label for an inlined scope!");
323 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
324 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
325 dwarf::DW_FORM_ref4, OriginDIE);
327 if (Ranges.size() > 1) {
328 // .debug_range section has not been laid out yet. Emit offset in
329 // .debug_range as a uint, size 4, for now. emitDIE will handle
330 // DW_AT_ranges appropriately.
331 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
332 DebugRangeSymbols.size()
333 * Asm->getTargetData().getPointerSize());
334 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
335 RE = Ranges.end(); RI != RE; ++RI) {
336 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
337 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
339 DebugRangeSymbols.push_back(NULL);
340 DebugRangeSymbols.push_back(NULL);
342 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
344 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
348 InlinedSubprogramDIEs.insert(OriginDIE);
350 // Track the start label for this inlined function.
351 //.debug_inlined section specification does not clearly state how
352 // to emit inlined scope that is split into multiple instruction ranges.
353 // For now, use first instruction range and emit low_pc/high_pc pair and
354 // corresponding .debug_inlined section entry for this pair.
355 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
356 I = InlineInfo.find(InlinedSP);
358 if (I == InlineInfo.end()) {
359 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
360 InlinedSPNodes.push_back(InlinedSP);
362 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
364 DILocation DL(Scope->getInlinedAt());
365 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
366 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
371 /// constructScopeDIE - Construct a DIE for this scope.
372 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
373 if (!Scope || !Scope->getScopeNode())
376 SmallVector<DIE *, 8> Children;
378 // Collect arguments for current function.
379 if (LScopes.isCurrentFunctionScope(Scope))
380 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
381 if (DbgVariable *ArgDV = CurrentFnArguments[i])
383 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
384 Children.push_back(Arg);
386 // Collect lexical scope children first.
387 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
388 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
390 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
391 Children.push_back(Variable);
392 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
393 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
394 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
395 Children.push_back(Nested);
396 DIScope DS(Scope->getScopeNode());
397 DIE *ScopeDIE = NULL;
398 if (Scope->getInlinedAt())
399 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
400 else if (DS.isSubprogram()) {
401 ProcessedSPNodes.insert(DS);
402 if (Scope->isAbstractScope()) {
403 ScopeDIE = TheCU->getDIE(DS);
404 // Note down abstract DIE.
406 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
409 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
412 // There is no need to emit empty lexical block DIE.
413 if (Children.empty())
415 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
418 if (!ScopeDIE) return NULL;
421 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
422 E = Children.end(); I != E; ++I)
423 ScopeDIE->addChild(*I);
425 if (DS.isSubprogram())
426 TheCU->addPubTypes(DISubprogram(DS));
431 /// GetOrCreateSourceID - Look up the source id with the given directory and
432 /// source file names. If none currently exists, create a new id and insert it
433 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
435 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
437 // If FE did not provide a file name, then assume stdin.
438 if (FileName.empty())
439 return GetOrCreateSourceID("<stdin>", StringRef());
441 // TODO: this might not belong here. See if we can factor this better.
442 if (DirName == CompilationDir)
445 unsigned SrcId = SourceIdMap.size()+1;
446 std::pair<std::string, std::string> SourceName =
447 std::make_pair(FileName, DirName);
448 std::pair<std::pair<std::string, std::string>, unsigned> Entry =
449 make_pair(SourceName, SrcId);
451 std::map<std::pair<std::string, std::string>, unsigned>::iterator I;
453 tie(I, NewlyInserted) = SourceIdMap.insert(Entry);
457 // Print out a .file directive to specify files for .loc directives.
458 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.first.second,
464 /// constructCompileUnit - Create new CompileUnit for the given
465 /// metadata node with tag DW_TAG_compile_unit.
466 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
467 DICompileUnit DIUnit(N);
468 StringRef FN = DIUnit.getFilename();
469 CompilationDir = DIUnit.getDirectory();
470 unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
472 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
473 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
474 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
475 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
476 DIUnit.getLanguage());
477 NewCU->addString(Die, dwarf::DW_AT_name, FN);
478 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
479 // simplifies debug range entries.
480 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
481 // DW_AT_stmt_list is a offset of line number information for this
482 // compile unit in debug_line section.
483 if (Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
484 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
485 Asm->GetTempSymbol("section_line"));
487 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
489 if (!CompilationDir.empty())
490 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
491 if (DIUnit.isOptimized())
492 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
494 StringRef Flags = DIUnit.getFlags();
496 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
498 if (unsigned RVer = DIUnit.getRunTimeVersion())
499 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
500 dwarf::DW_FORM_data1, RVer);
504 CUMap.insert(std::make_pair(N, NewCU));
508 /// construct SubprogramDIE - Construct subprogram DIE.
509 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
511 CompileUnit *&CURef = SPMap[N];
517 if (!SP.isDefinition())
518 // This is a method declaration which will be handled while constructing
522 DISubprogram SPDecl = SP.getFunctionDeclaration();
524 if (SPDecl.isSubprogram()) {
525 DeclDie = TheCU->getOrCreateSubprogramDIE(SPDecl);
528 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
531 // Refer function declaration directly.
532 TheCU->addDIEEntry(SubprogramDie, dwarf::DW_AT_specification,
533 dwarf::DW_FORM_ref4, DeclDie);
537 TheCU->insertDIE(N, SubprogramDie);
539 // Add to context owner.
540 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
543 TheCU->addGlobal(SP.getName(), SubprogramDie);
548 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
549 /// as llvm.dbg.enum and llvm.dbg.ty
550 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
551 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
552 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
553 const MDNode *N = NMD->getOperand(i);
554 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
555 constructSubprogramDIE(CU, N);
558 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
559 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
560 const MDNode *N = NMD->getOperand(i);
561 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
562 CU->createGlobalVariableDIE(N);
565 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
566 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
567 DIType Ty(NMD->getOperand(i));
568 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
569 CU->getOrCreateTypeDIE(Ty);
572 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
573 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
574 DIType Ty(NMD->getOperand(i));
575 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
576 CU->getOrCreateTypeDIE(Ty);
580 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
581 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
582 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
583 DebugInfoFinder DbgFinder;
584 DbgFinder.processModule(*M);
586 bool HasDebugInfo = false;
587 // Scan all the compile-units to see if there are any marked as the main
588 // unit. If not, we do not generate debug info.
589 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
590 E = DbgFinder.compile_unit_end(); I != E; ++I) {
591 if (DICompileUnit(*I).isMain()) {
596 if (!HasDebugInfo) return false;
598 // Create all the compile unit DIEs.
599 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
600 E = DbgFinder.compile_unit_end(); I != E; ++I)
601 constructCompileUnit(*I);
603 // Create DIEs for each global variable.
604 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
605 E = DbgFinder.global_variable_end(); I != E; ++I) {
606 const MDNode *N = *I;
607 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
608 CU->createGlobalVariableDIE(N);
611 // Create DIEs for each subprogram.
612 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
613 E = DbgFinder.subprogram_end(); I != E; ++I) {
614 const MDNode *N = *I;
615 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
616 constructSubprogramDIE(CU, N);
622 /// beginModule - Emit all Dwarf sections that should come prior to the
623 /// content. Create global DIEs and emit initial debug info sections.
624 /// This is invoked by the target AsmPrinter.
625 void DwarfDebug::beginModule(Module *M) {
626 if (DisableDebugInfoPrinting)
629 // If module has named metadata anchors then use them, otherwise scan the
630 // module using debug info finder to collect debug info.
631 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
633 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
634 DICompileUnit CUNode(CU_Nodes->getOperand(i));
635 CompileUnit *CU = constructCompileUnit(CUNode);
636 DIArray GVs = CUNode.getGlobalVariables();
637 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
638 CU->createGlobalVariableDIE(GVs.getElement(i));
639 DIArray SPs = CUNode.getSubprograms();
640 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
641 constructSubprogramDIE(CU, SPs.getElement(i));
642 DIArray EnumTypes = CUNode.getEnumTypes();
643 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
644 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
645 DIArray RetainedTypes = CUNode.getRetainedTypes();
646 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
647 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
649 } else if (!collectLegacyDebugInfo(M))
652 collectInfoFromNamedMDNodes(M);
654 // Tell MMI that we have debug info.
655 MMI->setDebugInfoAvailability(true);
657 // Emit initial sections.
660 // Prime section data.
661 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
664 /// endModule - Emit all Dwarf sections that should come after the content.
666 void DwarfDebug::endModule() {
667 if (!FirstCU) return;
668 const Module *M = MMI->getModule();
669 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
671 // Collect info for variables that were optimized out.
672 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
673 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
674 DICompileUnit TheCU(CU_Nodes->getOperand(i));
675 DIArray Subprograms = TheCU.getSubprograms();
676 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
677 DISubprogram SP(Subprograms.getElement(i));
678 if (ProcessedSPNodes.count(SP) != 0) continue;
679 if (!SP.Verify()) continue;
680 if (!SP.isDefinition()) continue;
681 DIArray Variables = SP.getVariables();
682 if (Variables.getNumElements() == 0) continue;
684 LexicalScope *Scope =
685 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
686 DeadFnScopeMap[SP] = Scope;
688 // Construct subprogram DIE and add variables DIEs.
689 CompileUnit *SPCU = CUMap.lookup(TheCU);
690 assert(SPCU && "Unable to find Compile Unit!");
691 constructSubprogramDIE(SPCU, SP);
692 DIE *ScopeDIE = SPCU->getDIE(SP);
693 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
694 DIVariable DV(Variables.getElement(vi));
695 if (!DV.Verify()) continue;
696 DbgVariable *NewVar = new DbgVariable(DV, NULL);
697 if (DIE *VariableDIE =
698 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
699 ScopeDIE->addChild(VariableDIE);
705 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
706 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
707 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
709 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
712 // Emit DW_AT_containing_type attribute to connect types with their
713 // vtable holding type.
714 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
715 CUE = CUMap.end(); CUI != CUE; ++CUI) {
716 CompileUnit *TheCU = CUI->second;
717 TheCU->constructContainingTypeDIEs();
720 // Standard sections final addresses.
721 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
722 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
723 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
724 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
726 // End text sections.
727 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
728 Asm->OutStreamer.SwitchSection(SectionMap[i]);
729 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
732 // Compute DIE offsets and sizes.
733 computeSizeAndOffsets();
735 // Emit all the DIEs into a debug info section
738 // Corresponding abbreviations into a abbrev section.
741 // Emit info into a debug pubnames section.
744 // Emit info into a debug pubtypes section.
747 // Emit info into a debug loc section.
750 // Emit info into a debug aranges section.
753 // Emit info into a debug ranges section.
756 // Emit info into a debug macinfo section.
760 emitDebugInlineInfo();
762 // Emit info into a debug str section.
766 DeleteContainerSeconds(DeadFnScopeMap);
768 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
769 E = CUMap.end(); I != E; ++I)
771 FirstCU = NULL; // Reset for the next Module, if any.
774 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
775 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
777 LLVMContext &Ctx = DV->getContext();
778 // More then one inlined variable corresponds to one abstract variable.
779 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
780 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
782 return AbsDbgVariable;
784 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
788 AbsDbgVariable = new DbgVariable(Var, NULL);
789 addScopeVariable(Scope, AbsDbgVariable);
790 AbstractVariables[Var] = AbsDbgVariable;
791 return AbsDbgVariable;
794 /// addCurrentFnArgument - If Var is a current function argument then add
795 /// it to CurrentFnArguments list.
796 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
797 DbgVariable *Var, LexicalScope *Scope) {
798 if (!LScopes.isCurrentFunctionScope(Scope))
800 DIVariable DV = Var->getVariable();
801 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
803 unsigned ArgNo = DV.getArgNumber();
807 size_t Size = CurrentFnArguments.size();
809 CurrentFnArguments.resize(MF->getFunction()->arg_size());
810 // llvm::Function argument size is not good indicator of how many
811 // arguments does the function have at source level.
813 CurrentFnArguments.resize(ArgNo * 2);
814 CurrentFnArguments[ArgNo - 1] = Var;
818 /// collectVariableInfoFromMMITable - Collect variable information from
819 /// side table maintained by MMI.
821 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
822 SmallPtrSet<const MDNode *, 16> &Processed) {
823 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
824 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
825 VE = VMap.end(); VI != VE; ++VI) {
826 const MDNode *Var = VI->first;
828 Processed.insert(Var);
830 const std::pair<unsigned, DebugLoc> &VP = VI->second;
832 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
834 // If variable scope is not found then skip this variable.
838 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
839 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
840 RegVar->setFrameIndex(VP.first);
841 if (!addCurrentFnArgument(MF, RegVar, Scope))
842 addScopeVariable(Scope, RegVar);
844 AbsDbgVariable->setFrameIndex(VP.first);
848 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
849 /// DBG_VALUE instruction, is in a defined reg.
850 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
851 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
852 return MI->getNumOperands() == 3 &&
853 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
854 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
857 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
859 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
860 const MCSymbol *FLabel,
861 const MCSymbol *SLabel,
862 const MachineInstr *MI) {
863 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
865 if (MI->getNumOperands() != 3) {
866 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
867 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
869 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
870 MachineLocation MLoc;
871 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
872 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
874 if (MI->getOperand(0).isImm())
875 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
876 if (MI->getOperand(0).isFPImm())
877 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
878 if (MI->getOperand(0).isCImm())
879 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
881 assert(0 && "Unexpected 3 operand DBG_VALUE instruction!");
882 return DotDebugLocEntry();
885 /// collectVariableInfo - Find variables for each lexical scope.
887 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
888 SmallPtrSet<const MDNode *, 16> &Processed) {
890 /// collection info from MMI table.
891 collectVariableInfoFromMMITable(MF, Processed);
893 for (SmallVectorImpl<const MDNode*>::const_iterator
894 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
896 const MDNode *Var = *UVI;
897 if (Processed.count(Var))
900 // History contains relevant DBG_VALUE instructions for Var and instructions
902 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
905 const MachineInstr *MInsn = History.front();
908 LexicalScope *Scope = NULL;
909 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
910 DISubprogram(DV.getContext()).describes(MF->getFunction()))
911 Scope = LScopes.getCurrentFunctionScope();
913 if (DV.getVersion() <= LLVMDebugVersion9)
914 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
916 if (MDNode *IA = DV.getInlinedAt())
917 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
919 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
922 // If variable scope is not found then skip this variable.
926 Processed.insert(DV);
927 assert(MInsn->isDebugValue() && "History must begin with debug value");
928 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
929 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
930 if (!addCurrentFnArgument(MF, RegVar, Scope))
931 addScopeVariable(Scope, RegVar);
933 AbsVar->setMInsn(MInsn);
935 // Simple ranges that are fully coalesced.
936 if (History.size() <= 1 || (History.size() == 2 &&
937 MInsn->isIdenticalTo(History.back()))) {
938 RegVar->setMInsn(MInsn);
942 // handle multiple DBG_VALUE instructions describing one variable.
943 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
945 for (SmallVectorImpl<const MachineInstr*>::const_iterator
946 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
947 const MachineInstr *Begin = *HI;
948 assert(Begin->isDebugValue() && "Invalid History entry");
950 // Check if DBG_VALUE is truncating a range.
951 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
952 && !Begin->getOperand(0).getReg())
955 // Compute the range for a register location.
956 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
957 const MCSymbol *SLabel = 0;
960 // If Begin is the last instruction in History then its value is valid
961 // until the end of the function.
962 SLabel = FunctionEndSym;
964 const MachineInstr *End = HI[1];
965 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
966 << "\t" << *Begin << "\t" << *End << "\n");
967 if (End->isDebugValue())
968 SLabel = getLabelBeforeInsn(End);
970 // End is a normal instruction clobbering the range.
971 SLabel = getLabelAfterInsn(End);
972 assert(SLabel && "Forgot label after clobber instruction");
977 // The value is valid until the next DBG_VALUE or clobber.
978 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
980 DotDebugLocEntries.push_back(DotDebugLocEntry());
983 // Collect info for variables that were optimized out.
984 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
985 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
986 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
987 DIVariable DV(Variables.getElement(i));
988 if (!DV || !DV.Verify() || !Processed.insert(DV))
990 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
991 addScopeVariable(Scope, new DbgVariable(DV, NULL));
995 /// getLabelBeforeInsn - Return Label preceding the instruction.
996 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
997 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
998 assert(Label && "Didn't insert label before instruction");
1002 /// getLabelAfterInsn - Return Label immediately following the instruction.
1003 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1004 return LabelsAfterInsn.lookup(MI);
1007 /// beginInstruction - Process beginning of an instruction.
1008 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1009 // Check if source location changes, but ignore DBG_VALUE locations.
1010 if (!MI->isDebugValue()) {
1011 DebugLoc DL = MI->getDebugLoc();
1012 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1013 unsigned Flags = DWARF2_FLAG_IS_STMT;
1015 if (DL == PrologEndLoc) {
1016 Flags |= DWARF2_FLAG_PROLOGUE_END;
1017 PrologEndLoc = DebugLoc();
1019 if (!DL.isUnknown()) {
1020 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1021 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1023 recordSourceLine(0, 0, 0, 0);
1027 // Insert labels where requested.
1028 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1029 LabelsBeforeInsn.find(MI);
1032 if (I == LabelsBeforeInsn.end())
1035 // Label already assigned.
1040 PrevLabel = MMI->getContext().CreateTempSymbol();
1041 Asm->OutStreamer.EmitLabel(PrevLabel);
1043 I->second = PrevLabel;
1046 /// endInstruction - Process end of an instruction.
1047 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1048 // Don't create a new label after DBG_VALUE instructions.
1049 // They don't generate code.
1050 if (!MI->isDebugValue())
1053 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1054 LabelsAfterInsn.find(MI);
1057 if (I == LabelsAfterInsn.end())
1060 // Label already assigned.
1064 // We need a label after this instruction.
1066 PrevLabel = MMI->getContext().CreateTempSymbol();
1067 Asm->OutStreamer.EmitLabel(PrevLabel);
1069 I->second = PrevLabel;
1072 /// identifyScopeMarkers() -
1073 /// Each LexicalScope has first instruction and last instruction to mark
1074 /// beginning and end of a scope respectively. Create an inverse map that list
1075 /// scopes starts (and ends) with an instruction. One instruction may start (or
1076 /// end) multiple scopes. Ignore scopes that are not reachable.
1077 void DwarfDebug::identifyScopeMarkers() {
1078 SmallVector<LexicalScope *, 4> WorkList;
1079 WorkList.push_back(LScopes.getCurrentFunctionScope());
1080 while (!WorkList.empty()) {
1081 LexicalScope *S = WorkList.pop_back_val();
1083 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1084 if (!Children.empty())
1085 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1086 SE = Children.end(); SI != SE; ++SI)
1087 WorkList.push_back(*SI);
1089 if (S->isAbstractScope())
1092 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1095 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1096 RE = Ranges.end(); RI != RE; ++RI) {
1097 assert(RI->first && "InsnRange does not have first instruction!");
1098 assert(RI->second && "InsnRange does not have second instruction!");
1099 requestLabelBeforeInsn(RI->first);
1100 requestLabelAfterInsn(RI->second);
1105 /// getScopeNode - Get MDNode for DebugLoc's scope.
1106 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1107 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1108 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1109 return DL.getScope(Ctx);
1112 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1113 /// line number info for the function.
1114 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1115 const MDNode *Scope = getScopeNode(DL, Ctx);
1116 DISubprogram SP = getDISubprogram(Scope);
1118 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1122 /// beginFunction - Gather pre-function debug information. Assumes being
1123 /// emitted immediately after the function entry point.
1124 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1125 if (!MMI->hasDebugInfo()) return;
1126 LScopes.initialize(*MF);
1127 if (LScopes.empty()) return;
1128 identifyScopeMarkers();
1130 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1131 Asm->getFunctionNumber());
1132 // Assumes in correct section after the entry point.
1133 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1135 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1137 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1138 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1139 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1141 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1143 bool AtBlockEntry = true;
1144 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1146 const MachineInstr *MI = II;
1148 if (MI->isDebugValue()) {
1149 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1151 // Keep track of user variables.
1153 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1155 // Variable is in a register, we need to check for clobbers.
1156 if (isDbgValueInDefinedReg(MI))
1157 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1159 // Check the history of this variable.
1160 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1161 if (History.empty()) {
1162 UserVariables.push_back(Var);
1163 // The first mention of a function argument gets the FunctionBeginSym
1164 // label, so arguments are visible when breaking at function entry.
1166 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1167 DISubprogram(getDISubprogram(DV.getContext()))
1168 .describes(MF->getFunction()))
1169 LabelsBeforeInsn[MI] = FunctionBeginSym;
1171 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1172 const MachineInstr *Prev = History.back();
1173 if (Prev->isDebugValue()) {
1174 // Coalesce identical entries at the end of History.
1175 if (History.size() >= 2 &&
1176 Prev->isIdenticalTo(History[History.size() - 2])) {
1177 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1179 << "\t" << *History[History.size() - 2] << "\n");
1183 // Terminate old register assignments that don't reach MI;
1184 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1185 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1186 isDbgValueInDefinedReg(Prev)) {
1187 // Previous register assignment needs to terminate at the end of
1189 MachineBasicBlock::const_iterator LastMI =
1190 PrevMBB->getLastNonDebugInstr();
1191 if (LastMI == PrevMBB->end()) {
1192 // Drop DBG_VALUE for empty range.
1193 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1194 << "\t" << *Prev << "\n");
1198 // Terminate after LastMI.
1199 History.push_back(LastMI);
1204 History.push_back(MI);
1206 // Not a DBG_VALUE instruction.
1208 AtBlockEntry = false;
1210 // First known non DBG_VALUE location marks beginning of function
1212 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1213 PrologEndLoc = MI->getDebugLoc();
1215 // Check if the instruction clobbers any registers with debug vars.
1216 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1217 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1218 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1220 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1221 unsigned Reg = *AI; ++AI) {
1222 const MDNode *Var = LiveUserVar[Reg];
1225 // Reg is now clobbered.
1226 LiveUserVar[Reg] = 0;
1228 // Was MD last defined by a DBG_VALUE referring to Reg?
1229 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1230 if (HistI == DbgValues.end())
1232 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1233 if (History.empty())
1235 const MachineInstr *Prev = History.back();
1236 // Sanity-check: Register assignments are terminated at the end of
1238 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1240 // Is the variable still in Reg?
1241 if (!isDbgValueInDefinedReg(Prev) ||
1242 Prev->getOperand(0).getReg() != Reg)
1244 // Var is clobbered. Make sure the next instruction gets a label.
1245 History.push_back(MI);
1252 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1254 SmallVectorImpl<const MachineInstr*> &History = I->second;
1255 if (History.empty())
1258 // Make sure the final register assignments are terminated.
1259 const MachineInstr *Prev = History.back();
1260 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1261 const MachineBasicBlock *PrevMBB = Prev->getParent();
1262 MachineBasicBlock::const_iterator LastMI =
1263 PrevMBB->getLastNonDebugInstr();
1264 if (LastMI == PrevMBB->end())
1265 // Drop DBG_VALUE for empty range.
1268 // Terminate after LastMI.
1269 History.push_back(LastMI);
1272 // Request labels for the full history.
1273 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1274 const MachineInstr *MI = History[i];
1275 if (MI->isDebugValue())
1276 requestLabelBeforeInsn(MI);
1278 requestLabelAfterInsn(MI);
1282 PrevInstLoc = DebugLoc();
1283 PrevLabel = FunctionBeginSym;
1285 // Record beginning of function.
1286 if (!PrologEndLoc.isUnknown()) {
1287 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1288 MF->getFunction()->getContext());
1289 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1290 FnStartDL.getScope(MF->getFunction()->getContext()),
1291 DWARF2_FLAG_IS_STMT);
1295 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1296 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1297 ScopeVariables[LS].push_back(Var);
1298 // Vars.push_back(Var);
1301 /// endFunction - Gather and emit post-function debug information.
1303 void DwarfDebug::endFunction(const MachineFunction *MF) {
1304 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1306 // Define end label for subprogram.
1307 FunctionEndSym = Asm->GetTempSymbol("func_end",
1308 Asm->getFunctionNumber());
1309 // Assumes in correct section after the entry point.
1310 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1312 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1313 collectVariableInfo(MF, ProcessedVars);
1315 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1316 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1317 assert(TheCU && "Unable to find compile unit!");
1319 // Construct abstract scopes.
1320 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1321 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1322 LexicalScope *AScope = AList[i];
1323 DISubprogram SP(AScope->getScopeNode());
1325 // Collect info for variables that were optimized out.
1326 DIArray Variables = SP.getVariables();
1327 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1328 DIVariable DV(Variables.getElement(i));
1329 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1331 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1332 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1335 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1336 constructScopeDIE(TheCU, AScope);
1339 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1341 if (!DisableFramePointerElim(*MF))
1342 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1343 dwarf::DW_FORM_flag, 1);
1345 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1346 MMI->getFrameMoves()));
1349 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1350 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1351 DeleteContainerPointers(I->second);
1352 ScopeVariables.clear();
1353 DeleteContainerPointers(CurrentFnArguments);
1354 UserVariables.clear();
1356 AbstractVariables.clear();
1357 LabelsBeforeInsn.clear();
1358 LabelsAfterInsn.clear();
1362 /// recordSourceLine - Register a source line with debug info. Returns the
1363 /// unique label that was emitted and which provides correspondence to
1364 /// the source line list.
1365 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1371 DIDescriptor Scope(S);
1373 if (Scope.isCompileUnit()) {
1374 DICompileUnit CU(S);
1375 Fn = CU.getFilename();
1376 Dir = CU.getDirectory();
1377 } else if (Scope.isFile()) {
1379 Fn = F.getFilename();
1380 Dir = F.getDirectory();
1381 } else if (Scope.isSubprogram()) {
1383 Fn = SP.getFilename();
1384 Dir = SP.getDirectory();
1385 } else if (Scope.isLexicalBlockFile()) {
1386 DILexicalBlockFile DBF(S);
1387 Fn = DBF.getFilename();
1388 Dir = DBF.getDirectory();
1389 } else if (Scope.isLexicalBlock()) {
1390 DILexicalBlock DB(S);
1391 Fn = DB.getFilename();
1392 Dir = DB.getDirectory();
1394 assert(0 && "Unexpected scope info");
1396 Src = GetOrCreateSourceID(Fn, Dir);
1398 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1401 //===----------------------------------------------------------------------===//
1403 //===----------------------------------------------------------------------===//
1405 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1408 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1409 // Get the children.
1410 const std::vector<DIE *> &Children = Die->getChildren();
1412 // If not last sibling and has children then add sibling offset attribute.
1413 if (!Last && !Children.empty())
1414 Die->addSiblingOffset(DIEValueAllocator);
1416 // Record the abbreviation.
1417 assignAbbrevNumber(Die->getAbbrev());
1419 // Get the abbreviation for this DIE.
1420 unsigned AbbrevNumber = Die->getAbbrevNumber();
1421 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1424 Die->setOffset(Offset);
1426 // Start the size with the size of abbreviation code.
1427 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1429 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1430 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1432 // Size the DIE attribute values.
1433 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1434 // Size attribute value.
1435 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1437 // Size the DIE children if any.
1438 if (!Children.empty()) {
1439 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1440 "Children flag not set");
1442 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1443 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1445 // End of children marker.
1446 Offset += sizeof(int8_t);
1449 Die->setSize(Offset - Die->getOffset());
1453 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1455 void DwarfDebug::computeSizeAndOffsets() {
1456 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1457 E = CUMap.end(); I != E; ++I) {
1458 // Compute size of compile unit header.
1460 sizeof(int32_t) + // Length of Compilation Unit Info
1461 sizeof(int16_t) + // DWARF version number
1462 sizeof(int32_t) + // Offset Into Abbrev. Section
1463 sizeof(int8_t); // Pointer Size (in bytes)
1464 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1468 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1469 /// temporary label to it if SymbolStem is specified.
1470 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1471 const char *SymbolStem = 0) {
1472 Asm->OutStreamer.SwitchSection(Section);
1473 if (!SymbolStem) return 0;
1475 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1476 Asm->OutStreamer.EmitLabel(TmpSym);
1480 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1481 /// the start of each one.
1482 void DwarfDebug::EmitSectionLabels() {
1483 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1485 // Dwarf sections base addresses.
1486 DwarfInfoSectionSym =
1487 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1488 DwarfAbbrevSectionSym =
1489 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1490 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1492 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1493 EmitSectionSym(Asm, MacroInfo);
1495 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1496 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1497 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1498 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1499 DwarfStrSectionSym =
1500 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1501 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1504 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1505 "section_debug_loc");
1507 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1508 EmitSectionSym(Asm, TLOF.getDataSection());
1511 /// emitDIE - Recursively emits a debug information entry.
1513 void DwarfDebug::emitDIE(DIE *Die) {
1514 // Get the abbreviation for this DIE.
1515 unsigned AbbrevNumber = Die->getAbbrevNumber();
1516 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1518 // Emit the code (index) for the abbreviation.
1519 if (Asm->isVerbose())
1520 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1521 Twine::utohexstr(Die->getOffset()) + ":0x" +
1522 Twine::utohexstr(Die->getSize()) + " " +
1523 dwarf::TagString(Abbrev->getTag()));
1524 Asm->EmitULEB128(AbbrevNumber);
1526 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1527 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1529 // Emit the DIE attribute values.
1530 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1531 unsigned Attr = AbbrevData[i].getAttribute();
1532 unsigned Form = AbbrevData[i].getForm();
1533 assert(Form && "Too many attributes for DIE (check abbreviation)");
1535 if (Asm->isVerbose())
1536 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1539 case dwarf::DW_AT_sibling:
1540 Asm->EmitInt32(Die->getSiblingOffset());
1542 case dwarf::DW_AT_abstract_origin: {
1543 DIEEntry *E = cast<DIEEntry>(Values[i]);
1544 DIE *Origin = E->getEntry();
1545 unsigned Addr = Origin->getOffset();
1546 Asm->EmitInt32(Addr);
1549 case dwarf::DW_AT_ranges: {
1550 // DW_AT_range Value encodes offset in debug_range section.
1551 DIEInteger *V = cast<DIEInteger>(Values[i]);
1553 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1554 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1558 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1560 DwarfDebugRangeSectionSym,
1565 case dwarf::DW_AT_location: {
1566 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1567 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1569 Values[i]->EmitValue(Asm, Form);
1572 case dwarf::DW_AT_accessibility: {
1573 if (Asm->isVerbose()) {
1574 DIEInteger *V = cast<DIEInteger>(Values[i]);
1575 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1577 Values[i]->EmitValue(Asm, Form);
1581 // Emit an attribute using the defined form.
1582 Values[i]->EmitValue(Asm, Form);
1587 // Emit the DIE children if any.
1588 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1589 const std::vector<DIE *> &Children = Die->getChildren();
1591 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1592 emitDIE(Children[j]);
1594 if (Asm->isVerbose())
1595 Asm->OutStreamer.AddComment("End Of Children Mark");
1600 /// emitDebugInfo - Emit the debug info section.
1602 void DwarfDebug::emitDebugInfo() {
1603 // Start debug info section.
1604 Asm->OutStreamer.SwitchSection(
1605 Asm->getObjFileLowering().getDwarfInfoSection());
1606 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1607 E = CUMap.end(); I != E; ++I) {
1608 CompileUnit *TheCU = I->second;
1609 DIE *Die = TheCU->getCUDie();
1611 // Emit the compile units header.
1612 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1615 // Emit size of content not including length itself
1616 unsigned ContentSize = Die->getSize() +
1617 sizeof(int16_t) + // DWARF version number
1618 sizeof(int32_t) + // Offset Into Abbrev. Section
1619 sizeof(int8_t); // Pointer Size (in bytes)
1621 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1622 Asm->EmitInt32(ContentSize);
1623 Asm->OutStreamer.AddComment("DWARF version number");
1624 Asm->EmitInt16(dwarf::DWARF_VERSION);
1625 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1626 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1627 DwarfAbbrevSectionSym);
1628 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1629 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1632 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1636 /// emitAbbreviations - Emit the abbreviation section.
1638 void DwarfDebug::emitAbbreviations() const {
1639 // Check to see if it is worth the effort.
1640 if (!Abbreviations.empty()) {
1641 // Start the debug abbrev section.
1642 Asm->OutStreamer.SwitchSection(
1643 Asm->getObjFileLowering().getDwarfAbbrevSection());
1645 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1647 // For each abbrevation.
1648 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1649 // Get abbreviation data
1650 const DIEAbbrev *Abbrev = Abbreviations[i];
1652 // Emit the abbrevations code (base 1 index.)
1653 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1655 // Emit the abbreviations data.
1659 // Mark end of abbreviations.
1660 Asm->EmitULEB128(0, "EOM(3)");
1662 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1666 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1667 /// the line matrix.
1669 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1670 // Define last address of section.
1671 Asm->OutStreamer.AddComment("Extended Op");
1674 Asm->OutStreamer.AddComment("Op size");
1675 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1676 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1677 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1679 Asm->OutStreamer.AddComment("Section end label");
1681 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1682 Asm->getTargetData().getPointerSize(),
1685 // Mark end of matrix.
1686 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1692 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1694 void DwarfDebug::emitDebugPubNames() {
1695 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1696 E = CUMap.end(); I != E; ++I) {
1697 CompileUnit *TheCU = I->second;
1698 // Start the dwarf pubnames section.
1699 Asm->OutStreamer.SwitchSection(
1700 Asm->getObjFileLowering().getDwarfPubNamesSection());
1702 Asm->OutStreamer.AddComment("Length of Public Names Info");
1703 Asm->EmitLabelDifference(
1704 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1705 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1707 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1710 Asm->OutStreamer.AddComment("DWARF Version");
1711 Asm->EmitInt16(dwarf::DWARF_VERSION);
1713 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1714 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1715 DwarfInfoSectionSym);
1717 Asm->OutStreamer.AddComment("Compilation Unit Length");
1718 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1719 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1722 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1723 for (StringMap<DIE*>::const_iterator
1724 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1725 const char *Name = GI->getKeyData();
1726 DIE *Entity = GI->second;
1728 Asm->OutStreamer.AddComment("DIE offset");
1729 Asm->EmitInt32(Entity->getOffset());
1731 if (Asm->isVerbose())
1732 Asm->OutStreamer.AddComment("External Name");
1733 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1736 Asm->OutStreamer.AddComment("End Mark");
1738 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1743 void DwarfDebug::emitDebugPubTypes() {
1744 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1745 E = CUMap.end(); I != E; ++I) {
1746 CompileUnit *TheCU = I->second;
1747 // Start the dwarf pubnames section.
1748 Asm->OutStreamer.SwitchSection(
1749 Asm->getObjFileLowering().getDwarfPubTypesSection());
1750 Asm->OutStreamer.AddComment("Length of Public Types Info");
1751 Asm->EmitLabelDifference(
1752 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1753 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1755 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1758 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1759 Asm->EmitInt16(dwarf::DWARF_VERSION);
1761 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1762 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1763 DwarfInfoSectionSym);
1765 Asm->OutStreamer.AddComment("Compilation Unit Length");
1766 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1767 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1770 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1771 for (StringMap<DIE*>::const_iterator
1772 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1773 const char *Name = GI->getKeyData();
1774 DIE *Entity = GI->second;
1776 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1777 Asm->EmitInt32(Entity->getOffset());
1779 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1780 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1783 Asm->OutStreamer.AddComment("End Mark");
1785 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1790 /// emitDebugStr - Emit visible names into a debug str section.
1792 void DwarfDebug::emitDebugStr() {
1793 // Check to see if it is worth the effort.
1794 if (StringPool.empty()) return;
1796 // Start the dwarf str section.
1797 Asm->OutStreamer.SwitchSection(
1798 Asm->getObjFileLowering().getDwarfStrSection());
1800 // Get all of the string pool entries and put them in an array by their ID so
1801 // we can sort them.
1802 SmallVector<std::pair<unsigned,
1803 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1805 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1806 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1807 Entries.push_back(std::make_pair(I->second.second, &*I));
1809 array_pod_sort(Entries.begin(), Entries.end());
1811 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1812 // Emit a label for reference from debug information entries.
1813 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1815 // Emit the string itself.
1816 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1817 Asm->OutStreamer.EmitZeros(1, 0);
1821 /// emitDebugLoc - Emit visible names into a debug loc section.
1823 void DwarfDebug::emitDebugLoc() {
1824 if (DotDebugLocEntries.empty())
1827 for (SmallVector<DotDebugLocEntry, 4>::iterator
1828 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1830 DotDebugLocEntry &Entry = *I;
1831 if (I + 1 != DotDebugLocEntries.end())
1835 // Start the dwarf loc section.
1836 Asm->OutStreamer.SwitchSection(
1837 Asm->getObjFileLowering().getDwarfLocSection());
1838 unsigned char Size = Asm->getTargetData().getPointerSize();
1839 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1841 for (SmallVector<DotDebugLocEntry, 4>::iterator
1842 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1843 I != E; ++I, ++index) {
1844 DotDebugLocEntry &Entry = *I;
1845 if (Entry.isMerged()) continue;
1846 if (Entry.isEmpty()) {
1847 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1848 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1849 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1851 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1852 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1853 DIVariable DV(Entry.Variable);
1854 Asm->OutStreamer.AddComment("Loc expr size");
1855 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1856 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1857 Asm->EmitLabelDifference(end, begin, 2);
1858 Asm->OutStreamer.EmitLabel(begin);
1859 if (Entry.isInt()) {
1860 DIBasicType BTy(DV.getType());
1862 (BTy.getEncoding() == dwarf::DW_ATE_signed
1863 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1864 Asm->OutStreamer.AddComment("DW_OP_consts");
1865 Asm->EmitInt8(dwarf::DW_OP_consts);
1866 Asm->EmitSLEB128(Entry.getInt());
1868 Asm->OutStreamer.AddComment("DW_OP_constu");
1869 Asm->EmitInt8(dwarf::DW_OP_constu);
1870 Asm->EmitULEB128(Entry.getInt());
1872 } else if (Entry.isLocation()) {
1873 if (!DV.hasComplexAddress())
1875 Asm->EmitDwarfRegOp(Entry.Loc);
1877 // Complex address entry.
1878 unsigned N = DV.getNumAddrElements();
1880 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1881 if (Entry.Loc.getOffset()) {
1883 Asm->EmitDwarfRegOp(Entry.Loc);
1884 Asm->OutStreamer.AddComment("DW_OP_deref");
1885 Asm->EmitInt8(dwarf::DW_OP_deref);
1886 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1887 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1888 Asm->EmitSLEB128(DV.getAddrElement(1));
1890 // If first address element is OpPlus then emit
1891 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1892 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1893 Asm->EmitDwarfRegOp(Loc);
1897 Asm->EmitDwarfRegOp(Entry.Loc);
1900 // Emit remaining complex address elements.
1901 for (; i < N; ++i) {
1902 uint64_t Element = DV.getAddrElement(i);
1903 if (Element == DIBuilder::OpPlus) {
1904 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1905 Asm->EmitULEB128(DV.getAddrElement(++i));
1906 } else if (Element == DIBuilder::OpDeref)
1907 Asm->EmitInt8(dwarf::DW_OP_deref);
1908 else llvm_unreachable("unknown Opcode found in complex address");
1912 // else ... ignore constant fp. There is not any good way to
1913 // to represent them here in dwarf.
1914 Asm->OutStreamer.EmitLabel(end);
1919 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1921 void DwarfDebug::EmitDebugARanges() {
1922 // Start the dwarf aranges section.
1923 Asm->OutStreamer.SwitchSection(
1924 Asm->getObjFileLowering().getDwarfARangesSection());
1927 /// emitDebugRanges - Emit visible names into a debug ranges section.
1929 void DwarfDebug::emitDebugRanges() {
1930 // Start the dwarf ranges section.
1931 Asm->OutStreamer.SwitchSection(
1932 Asm->getObjFileLowering().getDwarfRangesSection());
1933 unsigned char Size = Asm->getTargetData().getPointerSize();
1934 for (SmallVector<const MCSymbol *, 8>::iterator
1935 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1938 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1940 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1944 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1946 void DwarfDebug::emitDebugMacInfo() {
1947 if (const MCSection *LineInfo =
1948 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1949 // Start the dwarf macinfo section.
1950 Asm->OutStreamer.SwitchSection(LineInfo);
1954 /// emitDebugInlineInfo - Emit inline info using following format.
1956 /// 1. length of section
1957 /// 2. Dwarf version number
1958 /// 3. address size.
1960 /// Entries (one "entry" for each function that was inlined):
1962 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1963 /// otherwise offset into __debug_str for regular function name.
1964 /// 2. offset into __debug_str section for regular function name.
1965 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1966 /// instances for the function.
1968 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1969 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1970 /// __debug_info section, and the low_pc is the starting address for the
1971 /// inlining instance.
1972 void DwarfDebug::emitDebugInlineInfo() {
1973 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1979 Asm->OutStreamer.SwitchSection(
1980 Asm->getObjFileLowering().getDwarfDebugInlineSection());
1982 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
1983 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
1984 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
1986 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
1988 Asm->OutStreamer.AddComment("Dwarf Version");
1989 Asm->EmitInt16(dwarf::DWARF_VERSION);
1990 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1991 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1993 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
1994 E = InlinedSPNodes.end(); I != E; ++I) {
1996 const MDNode *Node = *I;
1997 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
1998 = InlineInfo.find(Node);
1999 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2000 DISubprogram SP(Node);
2001 StringRef LName = SP.getLinkageName();
2002 StringRef Name = SP.getName();
2004 Asm->OutStreamer.AddComment("MIPS linkage name");
2005 if (LName.empty()) {
2006 Asm->OutStreamer.EmitBytes(Name, 0);
2007 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2009 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2010 DwarfStrSectionSym);
2012 Asm->OutStreamer.AddComment("Function name");
2013 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2014 Asm->EmitULEB128(Labels.size(), "Inline count");
2016 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2017 LE = Labels.end(); LI != LE; ++LI) {
2018 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2019 Asm->EmitInt32(LI->second->getOffset());
2021 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2022 Asm->OutStreamer.EmitSymbolValue(LI->first,
2023 Asm->getTargetData().getPointerSize(),0);
2027 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));