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::getStringPoolEntry(StringRef Str) {
140 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
141 if (Entry.first) return Entry.first;
143 Entry.second = NextStringPoolNumber++;
144 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
148 /// assignAbbrevNumber - Define a unique number for the abbreviation.
150 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
151 // Profile the node so that we can make it unique.
155 // Check the set for priors.
156 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
158 // If it's newly added.
159 if (InSet == &Abbrev) {
160 // Add to abbreviation list.
161 Abbreviations.push_back(&Abbrev);
163 // Assign the vector position + 1 as its number.
164 Abbrev.setNumber(Abbreviations.size());
166 // Assign existing abbreviation number.
167 Abbrev.setNumber(InSet->getNumber());
171 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
172 /// printer to not emit usual symbol prefix before the symbol name is used then
173 /// return linkage name after skipping this special LLVM prefix.
174 static StringRef getRealLinkageName(StringRef LinkageName) {
176 if (LinkageName.startswith(StringRef(&One, 1)))
177 return LinkageName.substr(1);
181 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
182 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
183 /// If there are global variables in this scope then create and insert
184 /// DIEs for these variables.
185 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
186 const MDNode *SPNode) {
187 DIE *SPDie = SPCU->getDIE(SPNode);
189 assert(SPDie && "Unable to find subprogram DIE!");
190 DISubprogram SP(SPNode);
192 DISubprogram SPDecl = SP.getFunctionDeclaration();
193 if (SPDecl.isSubprogram())
194 // Refer function declaration directly.
195 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
196 SPCU->getOrCreateSubprogramDIE(SPDecl));
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) {
252 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
253 if (Scope->isAbstractScope())
256 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
260 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
261 if (Ranges.size() > 1) {
262 // .debug_range section has not been laid out yet. Emit offset in
263 // .debug_range as a uint, size 4, for now. emitDIE will handle
264 // DW_AT_ranges appropriately.
265 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
266 DebugRangeSymbols.size()
267 * Asm->getTargetData().getPointerSize());
268 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
269 RE = Ranges.end(); RI != RE; ++RI) {
270 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
271 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
273 DebugRangeSymbols.push_back(NULL);
274 DebugRangeSymbols.push_back(NULL);
278 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
279 const MCSymbol *End = getLabelAfterInsn(RI->second);
281 if (End == 0) return 0;
283 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
284 assert(End->isDefined() && "Invalid end label for an inlined scope!");
286 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
287 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
292 /// constructInlinedScopeDIE - This scope represents inlined body of
293 /// a function. Construct DIE to represent this concrete inlined copy
295 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
296 LexicalScope *Scope) {
298 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
299 assert (Ranges.empty() == false
300 && "LexicalScope does not have instruction markers!");
302 if (!Scope->getScopeNode())
304 DIScope DS(Scope->getScopeNode());
305 DISubprogram InlinedSP = getDISubprogram(DS);
306 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
308 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
312 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
313 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
314 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
316 if (StartLabel == 0 || EndLabel == 0) {
317 assert (0 && "Unexpected Start and End labels for a inlined scope!");
320 assert(StartLabel->isDefined() &&
321 "Invalid starting label for an inlined scope!");
322 assert(EndLabel->isDefined() &&
323 "Invalid end label for an inlined scope!");
325 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
326 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
327 dwarf::DW_FORM_ref4, OriginDIE);
329 if (Ranges.size() > 1) {
330 // .debug_range section has not been laid out yet. Emit offset in
331 // .debug_range as a uint, size 4, for now. emitDIE will handle
332 // DW_AT_ranges appropriately.
333 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
334 DebugRangeSymbols.size()
335 * Asm->getTargetData().getPointerSize());
336 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
337 RE = Ranges.end(); RI != RE; ++RI) {
338 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
339 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
341 DebugRangeSymbols.push_back(NULL);
342 DebugRangeSymbols.push_back(NULL);
344 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
346 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
350 InlinedSubprogramDIEs.insert(OriginDIE);
352 // Track the start label for this inlined function.
353 //.debug_inlined section specification does not clearly state how
354 // to emit inlined scope that is split into multiple instruction ranges.
355 // For now, use first instruction range and emit low_pc/high_pc pair and
356 // corresponding .debug_inlined section entry for this pair.
357 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
358 I = InlineInfo.find(InlinedSP);
360 if (I == InlineInfo.end()) {
361 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel,
363 InlinedSPNodes.push_back(InlinedSP);
365 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
367 DILocation DL(Scope->getInlinedAt());
368 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
369 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
374 /// constructScopeDIE - Construct a DIE for this scope.
375 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
376 if (!Scope || !Scope->getScopeNode())
379 SmallVector <DIE *, 8> Children;
381 // Collect arguments for current function.
382 if (LScopes.isCurrentFunctionScope(Scope))
383 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
384 if (DbgVariable *ArgDV = CurrentFnArguments[i])
386 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
387 Children.push_back(Arg);
389 // Collect lexical scope children first.
390 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
391 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
393 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
394 Children.push_back(Variable);
395 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
396 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
397 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
398 Children.push_back(Nested);
399 DIScope DS(Scope->getScopeNode());
400 DIE *ScopeDIE = NULL;
401 if (Scope->getInlinedAt())
402 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
403 else if (DS.isSubprogram()) {
404 ProcessedSPNodes.insert(DS);
405 if (Scope->isAbstractScope()) {
406 ScopeDIE = TheCU->getDIE(DS);
407 // Note down abstract DIE.
409 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
412 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
415 // There is no need to emit empty lexical block DIE.
416 if (Children.empty())
418 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
421 if (!ScopeDIE) return NULL;
424 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
425 E = Children.end(); I != E; ++I)
426 ScopeDIE->addChild(*I);
428 if (DS.isSubprogram())
429 TheCU->addPubTypes(DISubprogram(DS));
434 /// GetOrCreateSourceID - Look up the source id with the given directory and
435 /// source file names. If none currently exists, create a new id and insert it
436 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
439 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
441 // If FE did not provide a file name, then assume stdin.
442 if (FileName.empty())
443 return GetOrCreateSourceID("<stdin>", StringRef());
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 StringRef Dir = DIUnit.getDirectory();
470 unsigned ID = GetOrCreateSourceID(FN, Dir);
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, dwarf::DW_FORM_string,
475 DIUnit.getProducer());
476 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
477 DIUnit.getLanguage());
478 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
479 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
480 // simplifies debug range entries.
481 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
482 // DW_AT_stmt_list is a offset of line number information for this
483 // compile unit in debug_line section.
484 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
485 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
486 Asm->GetTempSymbol("section_line"));
488 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
491 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
492 if (DIUnit.isOptimized())
493 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
495 StringRef Flags = DIUnit.getFlags();
497 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
500 unsigned RVer = DIUnit.getRunTimeVersion();
502 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
503 dwarf::DW_FORM_data1, RVer);
507 CUMap.insert(std::make_pair(N, NewCU));
511 /// construct SubprogramDIE - Construct subprogram DIE.
512 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
515 if (!SP.isDefinition())
516 // This is a method declaration which will be handled while constructing
520 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
523 TheCU->insertDIE(N, SubprogramDie);
525 // Add to context owner.
526 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
529 TheCU->addGlobal(SP.getName(), SubprogramDie);
535 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
536 /// as llvm.dbg.enum and llvm.dbg.ty
537 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
538 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
539 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
540 const MDNode *N = NMD->getOperand(i);
541 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
542 constructSubprogramDIE(CU, N);
545 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
546 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
547 const MDNode *N = NMD->getOperand(i);
548 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
549 CU->createGlobalVariableDIE(N);
552 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
553 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
554 DIType Ty(NMD->getOperand(i));
555 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
556 CU->getOrCreateTypeDIE(Ty);
559 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
560 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
561 DIType Ty(NMD->getOperand(i));
562 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
563 CU->getOrCreateTypeDIE(Ty);
567 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
568 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
569 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
570 DebugInfoFinder DbgFinder;
571 DbgFinder.processModule(*M);
573 bool HasDebugInfo = false;
574 // Scan all the compile-units to see if there are any marked as the main
575 // unit. If not, we do not generate debug info.
576 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
577 E = DbgFinder.compile_unit_end(); I != E; ++I) {
578 if (DICompileUnit(*I).isMain()) {
583 if (!HasDebugInfo) return false;
585 // Create all the compile unit DIEs.
586 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
587 E = DbgFinder.compile_unit_end(); I != E; ++I)
588 constructCompileUnit(*I);
590 // Create DIEs for each global variable.
591 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
592 E = DbgFinder.global_variable_end(); I != E; ++I) {
593 const MDNode *N = *I;
594 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
595 CU->createGlobalVariableDIE(N);
598 // Create DIEs for each subprogram.
599 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
600 E = DbgFinder.subprogram_end(); I != E; ++I) {
601 const MDNode *N = *I;
602 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
603 constructSubprogramDIE(CU, N);
609 /// beginModule - Emit all Dwarf sections that should come prior to the
610 /// content. Create global DIEs and emit initial debug info sections.
611 /// This is invoked by the target AsmPrinter.
612 void DwarfDebug::beginModule(Module *M) {
613 if (DisableDebugInfoPrinting)
616 // If module has named metadata anchors then use them, otherwise scan the
617 // module using debug info finder to collect debug info.
618 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
620 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
621 DICompileUnit CUNode(CU_Nodes->getOperand(i));
622 CompileUnit *CU = constructCompileUnit(CUNode);
623 DIArray GVs = CUNode.getGlobalVariables();
624 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
625 CU->createGlobalVariableDIE(GVs.getElement(i));
626 DIArray SPs = CUNode.getSubprograms();
627 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
628 constructSubprogramDIE(CU, SPs.getElement(i));
629 DIArray EnumTypes = CUNode.getEnumTypes();
630 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
631 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
632 DIArray RetainedTypes = CUNode.getRetainedTypes();
633 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
634 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
636 } else if (!collectLegacyDebugInfo(M))
639 collectInfoFromNamedMDNodes(M);
641 // Tell MMI that we have debug info.
642 MMI->setDebugInfoAvailability(true);
644 // Emit initial sections.
647 // Prime section data.
648 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
651 /// endModule - Emit all Dwarf sections that should come after the content.
653 void DwarfDebug::endModule() {
654 if (!FirstCU) return;
655 const Module *M = MMI->getModule();
656 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
658 // Collect info for variables that were optimized out.
659 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
660 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
661 DICompileUnit TheCU(CU_Nodes->getOperand(i));
662 DIArray Subprograms = TheCU.getSubprograms();
663 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
664 DISubprogram SP(Subprograms.getElement(i));
665 if (ProcessedSPNodes.count(SP) != 0) continue;
666 if (!SP.Verify()) continue;
667 if (!SP.isDefinition()) continue;
668 DIArray Variables = SP.getVariables();
669 if (Variables.getNumElements() == 0) continue;
671 LexicalScope *Scope =
672 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
673 DeadFnScopeMap[SP] = Scope;
675 // Construct subprogram DIE and add variables DIEs.
676 CompileUnit *SPCU = CUMap.lookup(TheCU);
677 assert (SPCU && "Unable to find Compile Unit!");
678 constructSubprogramDIE(SPCU, SP);
679 DIE *ScopeDIE = SPCU->getDIE(SP);
680 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
681 DIVariable DV(Variables.getElement(vi));
682 if (!DV.Verify()) continue;
683 DbgVariable *NewVar = new DbgVariable(DV, NULL);
684 if (DIE *VariableDIE =
685 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
686 ScopeDIE->addChild(VariableDIE);
692 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
693 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
694 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
696 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
699 // Emit DW_AT_containing_type attribute to connect types with their
700 // vtable holding type.
701 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
702 CUE = CUMap.end(); CUI != CUE; ++CUI) {
703 CompileUnit *TheCU = CUI->second;
704 TheCU->constructContainingTypeDIEs();
707 // Standard sections final addresses.
708 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
709 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
710 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
711 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
713 // End text sections.
714 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
715 Asm->OutStreamer.SwitchSection(SectionMap[i]);
716 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
719 // Compute DIE offsets and sizes.
720 computeSizeAndOffsets();
722 // Emit all the DIEs into a debug info section
725 // Corresponding abbreviations into a abbrev section.
728 // Emit info into a debug pubnames section.
731 // Emit info into a debug pubtypes section.
734 // Emit info into a debug loc section.
737 // Emit info into a debug aranges section.
740 // Emit info into a debug ranges section.
743 // Emit info into a debug macinfo section.
747 emitDebugInlineInfo();
749 // Emit info into a debug str section.
753 DeleteContainerSeconds(DeadFnScopeMap);
755 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
756 E = CUMap.end(); I != E; ++I)
758 FirstCU = NULL; // Reset for the next Module, if any.
761 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
762 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
764 LLVMContext &Ctx = DV->getContext();
765 // More then one inlined variable corresponds to one abstract variable.
766 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
767 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
769 return AbsDbgVariable;
771 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
775 AbsDbgVariable = new DbgVariable(Var, NULL);
776 addScopeVariable(Scope, AbsDbgVariable);
777 AbstractVariables[Var] = AbsDbgVariable;
778 return AbsDbgVariable;
781 /// addCurrentFnArgument - If Var is a current function argument then add
782 /// it to CurrentFnArguments list.
783 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
784 DbgVariable *Var, LexicalScope *Scope) {
785 if (!LScopes.isCurrentFunctionScope(Scope))
787 DIVariable DV = Var->getVariable();
788 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
790 unsigned ArgNo = DV.getArgNumber();
794 size_t Size = CurrentFnArguments.size();
796 CurrentFnArguments.resize(MF->getFunction()->arg_size());
797 // llvm::Function argument size is not good indicator of how many
798 // arguments does the function have at source level.
800 CurrentFnArguments.resize(ArgNo * 2);
801 CurrentFnArguments[ArgNo - 1] = Var;
805 /// collectVariableInfoFromMMITable - Collect variable information from
806 /// side table maintained by MMI.
808 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
809 SmallPtrSet<const MDNode *, 16> &Processed) {
810 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
811 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
812 VE = VMap.end(); VI != VE; ++VI) {
813 const MDNode *Var = VI->first;
815 Processed.insert(Var);
817 const std::pair<unsigned, DebugLoc> &VP = VI->second;
819 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
821 // If variable scope is not found then skip this variable.
825 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
826 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
827 RegVar->setFrameIndex(VP.first);
828 if (!addCurrentFnArgument(MF, RegVar, Scope))
829 addScopeVariable(Scope, RegVar);
831 AbsDbgVariable->setFrameIndex(VP.first);
835 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
836 /// DBG_VALUE instruction, is in a defined reg.
837 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
838 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
839 return MI->getNumOperands() == 3 &&
840 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
841 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
844 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
846 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
847 const MCSymbol *FLabel,
848 const MCSymbol *SLabel,
849 const MachineInstr *MI) {
850 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
852 if (MI->getNumOperands() != 3) {
853 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
854 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
856 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
857 MachineLocation MLoc;
858 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
859 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
861 if (MI->getOperand(0).isImm())
862 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
863 if (MI->getOperand(0).isFPImm())
864 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
865 if (MI->getOperand(0).isCImm())
866 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
868 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
869 return DotDebugLocEntry();
872 /// collectVariableInfo - Find variables for each lexical scope.
874 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
875 SmallPtrSet<const MDNode *, 16> &Processed) {
877 /// collection info from MMI table.
878 collectVariableInfoFromMMITable(MF, Processed);
880 for (SmallVectorImpl<const MDNode*>::const_iterator
881 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
883 const MDNode *Var = *UVI;
884 if (Processed.count(Var))
887 // History contains relevant DBG_VALUE instructions for Var and instructions
889 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
892 const MachineInstr *MInsn = History.front();
895 LexicalScope *Scope = NULL;
896 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
897 DISubprogram(DV.getContext()).describes(MF->getFunction()))
898 Scope = LScopes.getCurrentFunctionScope();
900 if (DV.getVersion() <= LLVMDebugVersion9)
901 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
903 if (MDNode *IA = DV.getInlinedAt())
904 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
906 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
909 // If variable scope is not found then skip this variable.
913 Processed.insert(DV);
914 assert(MInsn->isDebugValue() && "History must begin with debug value");
915 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
916 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
917 if (!addCurrentFnArgument(MF, RegVar, Scope))
918 addScopeVariable(Scope, RegVar);
920 AbsVar->setMInsn(MInsn);
922 // Simple ranges that are fully coalesced.
923 if (History.size() <= 1 || (History.size() == 2 &&
924 MInsn->isIdenticalTo(History.back()))) {
925 RegVar->setMInsn(MInsn);
929 // handle multiple DBG_VALUE instructions describing one variable.
930 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
932 for (SmallVectorImpl<const MachineInstr*>::const_iterator
933 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
934 const MachineInstr *Begin = *HI;
935 assert(Begin->isDebugValue() && "Invalid History entry");
937 // Check if DBG_VALUE is truncating a range.
938 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
939 && !Begin->getOperand(0).getReg())
942 // Compute the range for a register location.
943 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
944 const MCSymbol *SLabel = 0;
947 // If Begin is the last instruction in History then its value is valid
948 // until the end of the function.
949 SLabel = FunctionEndSym;
951 const MachineInstr *End = HI[1];
952 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
953 << "\t" << *Begin << "\t" << *End << "\n");
954 if (End->isDebugValue())
955 SLabel = getLabelBeforeInsn(End);
957 // End is a normal instruction clobbering the range.
958 SLabel = getLabelAfterInsn(End);
959 assert(SLabel && "Forgot label after clobber instruction");
964 // The value is valid until the next DBG_VALUE or clobber.
965 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
967 DotDebugLocEntries.push_back(DotDebugLocEntry());
970 // Collect info for variables that were optimized out.
971 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
972 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
973 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
974 DIVariable DV(Variables.getElement(i));
975 if (!DV || !DV.Verify() || !Processed.insert(DV))
977 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
978 addScopeVariable(Scope, new DbgVariable(DV, NULL));
982 /// getLabelBeforeInsn - Return Label preceding the instruction.
983 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
984 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
985 assert(Label && "Didn't insert label before instruction");
989 /// getLabelAfterInsn - Return Label immediately following the instruction.
990 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
991 return LabelsAfterInsn.lookup(MI);
994 /// beginInstruction - Process beginning of an instruction.
995 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
996 // Check if source location changes, but ignore DBG_VALUE locations.
997 if (!MI->isDebugValue()) {
998 DebugLoc DL = MI->getDebugLoc();
999 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1000 unsigned Flags = DWARF2_FLAG_IS_STMT;
1002 if (DL == PrologEndLoc) {
1003 Flags |= DWARF2_FLAG_PROLOGUE_END;
1004 PrologEndLoc = DebugLoc();
1006 if (!DL.isUnknown()) {
1007 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1008 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1010 recordSourceLine(0, 0, 0, 0);
1014 // Insert labels where requested.
1015 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1016 LabelsBeforeInsn.find(MI);
1019 if (I == LabelsBeforeInsn.end())
1022 // Label already assigned.
1027 PrevLabel = MMI->getContext().CreateTempSymbol();
1028 Asm->OutStreamer.EmitLabel(PrevLabel);
1030 I->second = PrevLabel;
1033 /// endInstruction - Process end of an instruction.
1034 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1035 // Don't create a new label after DBG_VALUE instructions.
1036 // They don't generate code.
1037 if (!MI->isDebugValue())
1040 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1041 LabelsAfterInsn.find(MI);
1044 if (I == LabelsAfterInsn.end())
1047 // Label already assigned.
1051 // We need a label after this instruction.
1053 PrevLabel = MMI->getContext().CreateTempSymbol();
1054 Asm->OutStreamer.EmitLabel(PrevLabel);
1056 I->second = PrevLabel;
1059 /// identifyScopeMarkers() -
1060 /// Each LexicalScope has first instruction and last instruction to mark
1061 /// beginning and end of a scope respectively. Create an inverse map that list
1062 /// scopes starts (and ends) with an instruction. One instruction may start (or
1063 /// end) multiple scopes. Ignore scopes that are not reachable.
1064 void DwarfDebug::identifyScopeMarkers() {
1065 SmallVector<LexicalScope *, 4> WorkList;
1066 WorkList.push_back(LScopes.getCurrentFunctionScope());
1067 while (!WorkList.empty()) {
1068 LexicalScope *S = WorkList.pop_back_val();
1070 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1071 if (!Children.empty())
1072 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1073 SE = Children.end(); SI != SE; ++SI)
1074 WorkList.push_back(*SI);
1076 if (S->isAbstractScope())
1079 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1082 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1083 RE = Ranges.end(); RI != RE; ++RI) {
1084 assert(RI->first && "InsnRange does not have first instruction!");
1085 assert(RI->second && "InsnRange does not have second instruction!");
1086 requestLabelBeforeInsn(RI->first);
1087 requestLabelAfterInsn(RI->second);
1092 /// getScopeNode - Get MDNode for DebugLoc's scope.
1093 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1094 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1095 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1096 return DL.getScope(Ctx);
1099 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1100 /// line number info for the function.
1101 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1102 const MDNode *Scope = getScopeNode(DL, Ctx);
1103 DISubprogram SP = getDISubprogram(Scope);
1105 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1109 /// beginFunction - Gather pre-function debug information. Assumes being
1110 /// emitted immediately after the function entry point.
1111 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1112 if (!MMI->hasDebugInfo()) return;
1113 LScopes.initialize(*MF);
1114 if (LScopes.empty()) return;
1115 identifyScopeMarkers();
1117 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1118 Asm->getFunctionNumber());
1119 // Assumes in correct section after the entry point.
1120 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1122 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1124 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1125 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1126 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1128 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1130 bool AtBlockEntry = true;
1131 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1133 const MachineInstr *MI = II;
1135 if (MI->isDebugValue()) {
1136 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1138 // Keep track of user variables.
1140 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1142 // Variable is in a register, we need to check for clobbers.
1143 if (isDbgValueInDefinedReg(MI))
1144 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1146 // Check the history of this variable.
1147 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1148 if (History.empty()) {
1149 UserVariables.push_back(Var);
1150 // The first mention of a function argument gets the FunctionBeginSym
1151 // label, so arguments are visible when breaking at function entry.
1153 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1154 DISubprogram(getDISubprogram(DV.getContext()))
1155 .describes(MF->getFunction()))
1156 LabelsBeforeInsn[MI] = FunctionBeginSym;
1158 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1159 const MachineInstr *Prev = History.back();
1160 if (Prev->isDebugValue()) {
1161 // Coalesce identical entries at the end of History.
1162 if (History.size() >= 2 &&
1163 Prev->isIdenticalTo(History[History.size() - 2])) {
1164 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1166 << "\t" << *History[History.size() - 2] << "\n");
1170 // Terminate old register assignments that don't reach MI;
1171 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1172 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1173 isDbgValueInDefinedReg(Prev)) {
1174 // Previous register assignment needs to terminate at the end of
1176 MachineBasicBlock::const_iterator LastMI =
1177 PrevMBB->getLastNonDebugInstr();
1178 if (LastMI == PrevMBB->end()) {
1179 // Drop DBG_VALUE for empty range.
1180 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1181 << "\t" << *Prev << "\n");
1185 // Terminate after LastMI.
1186 History.push_back(LastMI);
1191 History.push_back(MI);
1193 // Not a DBG_VALUE instruction.
1195 AtBlockEntry = false;
1197 // First known non DBG_VALUE location marks beginning of function
1199 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1200 PrologEndLoc = MI->getDebugLoc();
1202 // Check if the instruction clobbers any registers with debug vars.
1203 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1204 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1205 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1207 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1208 unsigned Reg = *AI; ++AI) {
1209 const MDNode *Var = LiveUserVar[Reg];
1212 // Reg is now clobbered.
1213 LiveUserVar[Reg] = 0;
1215 // Was MD last defined by a DBG_VALUE referring to Reg?
1216 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1217 if (HistI == DbgValues.end())
1219 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1220 if (History.empty())
1222 const MachineInstr *Prev = History.back();
1223 // Sanity-check: Register assignments are terminated at the end of
1225 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1227 // Is the variable still in Reg?
1228 if (!isDbgValueInDefinedReg(Prev) ||
1229 Prev->getOperand(0).getReg() != Reg)
1231 // Var is clobbered. Make sure the next instruction gets a label.
1232 History.push_back(MI);
1239 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1241 SmallVectorImpl<const MachineInstr*> &History = I->second;
1242 if (History.empty())
1245 // Make sure the final register assignments are terminated.
1246 const MachineInstr *Prev = History.back();
1247 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1248 const MachineBasicBlock *PrevMBB = Prev->getParent();
1249 MachineBasicBlock::const_iterator LastMI =
1250 PrevMBB->getLastNonDebugInstr();
1251 if (LastMI == PrevMBB->end())
1252 // Drop DBG_VALUE for empty range.
1255 // Terminate after LastMI.
1256 History.push_back(LastMI);
1259 // Request labels for the full history.
1260 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1261 const MachineInstr *MI = History[i];
1262 if (MI->isDebugValue())
1263 requestLabelBeforeInsn(MI);
1265 requestLabelAfterInsn(MI);
1269 PrevInstLoc = DebugLoc();
1270 PrevLabel = FunctionBeginSym;
1272 // Record beginning of function.
1273 if (!PrologEndLoc.isUnknown()) {
1274 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1275 MF->getFunction()->getContext());
1276 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1277 FnStartDL.getScope(MF->getFunction()->getContext()),
1278 DWARF2_FLAG_IS_STMT);
1282 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1283 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1284 ScopeVariables[LS].push_back(Var);
1285 // Vars.push_back(Var);
1288 /// endFunction - Gather and emit post-function debug information.
1290 void DwarfDebug::endFunction(const MachineFunction *MF) {
1291 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1293 // Define end label for subprogram.
1294 FunctionEndSym = Asm->GetTempSymbol("func_end",
1295 Asm->getFunctionNumber());
1296 // Assumes in correct section after the entry point.
1297 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1299 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1300 collectVariableInfo(MF, ProcessedVars);
1302 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1303 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1304 assert (TheCU && "Unable to find compile unit!");
1306 // Construct abstract scopes.
1307 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1308 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1309 LexicalScope *AScope = AList[i];
1310 DISubprogram SP(AScope->getScopeNode());
1312 // Collect info for variables that were optimized out.
1313 DIArray Variables = SP.getVariables();
1314 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1315 DIVariable DV(Variables.getElement(i));
1316 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1318 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1319 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1322 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1323 constructScopeDIE(TheCU, AScope);
1326 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1328 if (!DisableFramePointerElim(*MF))
1329 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1330 dwarf::DW_FORM_flag, 1);
1332 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1333 MMI->getFrameMoves()));
1336 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1337 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1338 DeleteContainerPointers(I->second);
1339 ScopeVariables.clear();
1340 DeleteContainerPointers(CurrentFnArguments);
1341 UserVariables.clear();
1343 AbstractVariables.clear();
1344 LabelsBeforeInsn.clear();
1345 LabelsAfterInsn.clear();
1349 /// recordSourceLine - Register a source line with debug info. Returns the
1350 /// unique label that was emitted and which provides correspondence to
1351 /// the source line list.
1352 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1358 DIDescriptor Scope(S);
1360 if (Scope.isCompileUnit()) {
1361 DICompileUnit CU(S);
1362 Fn = CU.getFilename();
1363 Dir = CU.getDirectory();
1364 } else if (Scope.isFile()) {
1366 Fn = F.getFilename();
1367 Dir = F.getDirectory();
1368 } else if (Scope.isSubprogram()) {
1370 Fn = SP.getFilename();
1371 Dir = SP.getDirectory();
1372 } else if (Scope.isLexicalBlockFile()) {
1373 DILexicalBlockFile DBF(S);
1374 Fn = DBF.getFilename();
1375 Dir = DBF.getDirectory();
1376 } else if (Scope.isLexicalBlock()) {
1377 DILexicalBlock DB(S);
1378 Fn = DB.getFilename();
1379 Dir = DB.getDirectory();
1381 assert(0 && "Unexpected scope info");
1383 Src = GetOrCreateSourceID(Fn, Dir);
1385 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1388 //===----------------------------------------------------------------------===//
1390 //===----------------------------------------------------------------------===//
1392 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1395 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1396 // Get the children.
1397 const std::vector<DIE *> &Children = Die->getChildren();
1399 // If not last sibling and has children then add sibling offset attribute.
1400 if (!Last && !Children.empty())
1401 Die->addSiblingOffset(DIEValueAllocator);
1403 // Record the abbreviation.
1404 assignAbbrevNumber(Die->getAbbrev());
1406 // Get the abbreviation for this DIE.
1407 unsigned AbbrevNumber = Die->getAbbrevNumber();
1408 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1411 Die->setOffset(Offset);
1413 // Start the size with the size of abbreviation code.
1414 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1416 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1417 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1419 // Size the DIE attribute values.
1420 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1421 // Size attribute value.
1422 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1424 // Size the DIE children if any.
1425 if (!Children.empty()) {
1426 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1427 "Children flag not set");
1429 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1430 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1432 // End of children marker.
1433 Offset += sizeof(int8_t);
1436 Die->setSize(Offset - Die->getOffset());
1440 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1442 void DwarfDebug::computeSizeAndOffsets() {
1443 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1444 E = CUMap.end(); I != E; ++I) {
1445 // Compute size of compile unit header.
1447 sizeof(int32_t) + // Length of Compilation Unit Info
1448 sizeof(int16_t) + // DWARF version number
1449 sizeof(int32_t) + // Offset Into Abbrev. Section
1450 sizeof(int8_t); // Pointer Size (in bytes)
1451 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1455 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1456 /// temporary label to it if SymbolStem is specified.
1457 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1458 const char *SymbolStem = 0) {
1459 Asm->OutStreamer.SwitchSection(Section);
1460 if (!SymbolStem) return 0;
1462 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1463 Asm->OutStreamer.EmitLabel(TmpSym);
1467 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1468 /// the start of each one.
1469 void DwarfDebug::EmitSectionLabels() {
1470 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1472 // Dwarf sections base addresses.
1473 DwarfInfoSectionSym =
1474 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1475 DwarfAbbrevSectionSym =
1476 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1477 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1479 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1480 EmitSectionSym(Asm, MacroInfo);
1482 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1483 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1484 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1485 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1486 DwarfStrSectionSym =
1487 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1488 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1491 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1492 "section_debug_loc");
1494 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1495 EmitSectionSym(Asm, TLOF.getDataSection());
1498 /// emitDIE - Recursively emits a debug information entry.
1500 void DwarfDebug::emitDIE(DIE *Die) {
1501 // Get the abbreviation for this DIE.
1502 unsigned AbbrevNumber = Die->getAbbrevNumber();
1503 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1505 // Emit the code (index) for the abbreviation.
1506 if (Asm->isVerbose())
1507 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1508 Twine::utohexstr(Die->getOffset()) + ":0x" +
1509 Twine::utohexstr(Die->getSize()) + " " +
1510 dwarf::TagString(Abbrev->getTag()));
1511 Asm->EmitULEB128(AbbrevNumber);
1513 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1514 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1516 // Emit the DIE attribute values.
1517 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1518 unsigned Attr = AbbrevData[i].getAttribute();
1519 unsigned Form = AbbrevData[i].getForm();
1520 assert(Form && "Too many attributes for DIE (check abbreviation)");
1522 if (Asm->isVerbose())
1523 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1526 case dwarf::DW_AT_sibling:
1527 Asm->EmitInt32(Die->getSiblingOffset());
1529 case dwarf::DW_AT_abstract_origin: {
1530 DIEEntry *E = cast<DIEEntry>(Values[i]);
1531 DIE *Origin = E->getEntry();
1532 unsigned Addr = Origin->getOffset();
1533 Asm->EmitInt32(Addr);
1536 case dwarf::DW_AT_ranges: {
1537 // DW_AT_range Value encodes offset in debug_range section.
1538 DIEInteger *V = cast<DIEInteger>(Values[i]);
1540 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1541 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1545 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1547 DwarfDebugRangeSectionSym,
1552 case dwarf::DW_AT_location: {
1553 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1554 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1556 Values[i]->EmitValue(Asm, Form);
1559 case dwarf::DW_AT_accessibility: {
1560 if (Asm->isVerbose()) {
1561 DIEInteger *V = cast<DIEInteger>(Values[i]);
1562 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1564 Values[i]->EmitValue(Asm, Form);
1568 // Emit an attribute using the defined form.
1569 Values[i]->EmitValue(Asm, Form);
1574 // Emit the DIE children if any.
1575 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1576 const std::vector<DIE *> &Children = Die->getChildren();
1578 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1579 emitDIE(Children[j]);
1581 if (Asm->isVerbose())
1582 Asm->OutStreamer.AddComment("End Of Children Mark");
1587 /// emitDebugInfo - Emit the debug info section.
1589 void DwarfDebug::emitDebugInfo() {
1590 // Start debug info section.
1591 Asm->OutStreamer.SwitchSection(
1592 Asm->getObjFileLowering().getDwarfInfoSection());
1593 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1594 E = CUMap.end(); I != E; ++I) {
1595 CompileUnit *TheCU = I->second;
1596 DIE *Die = TheCU->getCUDie();
1598 // Emit the compile units header.
1599 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1602 // Emit size of content not including length itself
1603 unsigned ContentSize = Die->getSize() +
1604 sizeof(int16_t) + // DWARF version number
1605 sizeof(int32_t) + // Offset Into Abbrev. Section
1606 sizeof(int8_t); // Pointer Size (in bytes)
1608 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1609 Asm->EmitInt32(ContentSize);
1610 Asm->OutStreamer.AddComment("DWARF version number");
1611 Asm->EmitInt16(dwarf::DWARF_VERSION);
1612 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1613 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1614 DwarfAbbrevSectionSym);
1615 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1616 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1619 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1623 /// emitAbbreviations - Emit the abbreviation section.
1625 void DwarfDebug::emitAbbreviations() const {
1626 // Check to see if it is worth the effort.
1627 if (!Abbreviations.empty()) {
1628 // Start the debug abbrev section.
1629 Asm->OutStreamer.SwitchSection(
1630 Asm->getObjFileLowering().getDwarfAbbrevSection());
1632 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1634 // For each abbrevation.
1635 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1636 // Get abbreviation data
1637 const DIEAbbrev *Abbrev = Abbreviations[i];
1639 // Emit the abbrevations code (base 1 index.)
1640 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1642 // Emit the abbreviations data.
1646 // Mark end of abbreviations.
1647 Asm->EmitULEB128(0, "EOM(3)");
1649 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1653 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1654 /// the line matrix.
1656 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1657 // Define last address of section.
1658 Asm->OutStreamer.AddComment("Extended Op");
1661 Asm->OutStreamer.AddComment("Op size");
1662 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1663 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1664 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1666 Asm->OutStreamer.AddComment("Section end label");
1668 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1669 Asm->getTargetData().getPointerSize(),
1672 // Mark end of matrix.
1673 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1679 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1681 void DwarfDebug::emitDebugPubNames() {
1682 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1683 E = CUMap.end(); I != E; ++I) {
1684 CompileUnit *TheCU = I->second;
1685 // Start the dwarf pubnames section.
1686 Asm->OutStreamer.SwitchSection(
1687 Asm->getObjFileLowering().getDwarfPubNamesSection());
1689 Asm->OutStreamer.AddComment("Length of Public Names Info");
1690 Asm->EmitLabelDifference(
1691 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1692 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1694 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1697 Asm->OutStreamer.AddComment("DWARF Version");
1698 Asm->EmitInt16(dwarf::DWARF_VERSION);
1700 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1701 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1702 DwarfInfoSectionSym);
1704 Asm->OutStreamer.AddComment("Compilation Unit Length");
1705 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1706 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1709 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1710 for (StringMap<DIE*>::const_iterator
1711 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1712 const char *Name = GI->getKeyData();
1713 DIE *Entity = GI->second;
1715 Asm->OutStreamer.AddComment("DIE offset");
1716 Asm->EmitInt32(Entity->getOffset());
1718 if (Asm->isVerbose())
1719 Asm->OutStreamer.AddComment("External Name");
1720 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1723 Asm->OutStreamer.AddComment("End Mark");
1725 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1730 void DwarfDebug::emitDebugPubTypes() {
1731 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1732 E = CUMap.end(); I != E; ++I) {
1733 CompileUnit *TheCU = I->second;
1734 // Start the dwarf pubnames section.
1735 Asm->OutStreamer.SwitchSection(
1736 Asm->getObjFileLowering().getDwarfPubTypesSection());
1737 Asm->OutStreamer.AddComment("Length of Public Types Info");
1738 Asm->EmitLabelDifference(
1739 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1740 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1742 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1745 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1746 Asm->EmitInt16(dwarf::DWARF_VERSION);
1748 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1749 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1750 DwarfInfoSectionSym);
1752 Asm->OutStreamer.AddComment("Compilation Unit Length");
1753 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1754 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1757 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1758 for (StringMap<DIE*>::const_iterator
1759 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1760 const char *Name = GI->getKeyData();
1761 DIE *Entity = GI->second;
1763 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1764 Asm->EmitInt32(Entity->getOffset());
1766 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1767 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1770 Asm->OutStreamer.AddComment("End Mark");
1772 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1777 /// emitDebugStr - Emit visible names into a debug str section.
1779 void DwarfDebug::emitDebugStr() {
1780 // Check to see if it is worth the effort.
1781 if (StringPool.empty()) return;
1783 // Start the dwarf str section.
1784 Asm->OutStreamer.SwitchSection(
1785 Asm->getObjFileLowering().getDwarfStrSection());
1787 // Get all of the string pool entries and put them in an array by their ID so
1788 // we can sort them.
1789 SmallVector<std::pair<unsigned,
1790 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1792 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1793 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1794 Entries.push_back(std::make_pair(I->second.second, &*I));
1796 array_pod_sort(Entries.begin(), Entries.end());
1798 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1799 // Emit a label for reference from debug information entries.
1800 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1802 // Emit the string itself.
1803 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1807 /// emitDebugLoc - Emit visible names into a debug loc section.
1809 void DwarfDebug::emitDebugLoc() {
1810 if (DotDebugLocEntries.empty())
1813 for (SmallVector<DotDebugLocEntry, 4>::iterator
1814 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1816 DotDebugLocEntry &Entry = *I;
1817 if (I + 1 != DotDebugLocEntries.end())
1821 // Start the dwarf loc section.
1822 Asm->OutStreamer.SwitchSection(
1823 Asm->getObjFileLowering().getDwarfLocSection());
1824 unsigned char Size = Asm->getTargetData().getPointerSize();
1825 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1827 for (SmallVector<DotDebugLocEntry, 4>::iterator
1828 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1829 I != E; ++I, ++index) {
1830 DotDebugLocEntry &Entry = *I;
1831 if (Entry.isMerged()) continue;
1832 if (Entry.isEmpty()) {
1833 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1834 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1835 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1837 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1838 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1839 DIVariable DV(Entry.Variable);
1840 Asm->OutStreamer.AddComment("Loc expr size");
1841 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1842 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1843 Asm->EmitLabelDifference(end, begin, 2);
1844 Asm->OutStreamer.EmitLabel(begin);
1845 if (Entry.isInt()) {
1846 DIBasicType BTy(DV.getType());
1848 (BTy.getEncoding() == dwarf::DW_ATE_signed
1849 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1850 Asm->OutStreamer.AddComment("DW_OP_consts");
1851 Asm->EmitInt8(dwarf::DW_OP_consts);
1852 Asm->EmitSLEB128(Entry.getInt());
1854 Asm->OutStreamer.AddComment("DW_OP_constu");
1855 Asm->EmitInt8(dwarf::DW_OP_constu);
1856 Asm->EmitULEB128(Entry.getInt());
1858 } else if (Entry.isLocation()) {
1859 if (!DV.hasComplexAddress())
1861 Asm->EmitDwarfRegOp(Entry.Loc);
1863 // Complex address entry.
1864 unsigned N = DV.getNumAddrElements();
1866 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1867 if (Entry.Loc.getOffset()) {
1869 Asm->EmitDwarfRegOp(Entry.Loc);
1870 Asm->OutStreamer.AddComment("DW_OP_deref");
1871 Asm->EmitInt8(dwarf::DW_OP_deref);
1872 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1873 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1874 Asm->EmitSLEB128(DV.getAddrElement(1));
1876 // If first address element is OpPlus then emit
1877 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1878 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1879 Asm->EmitDwarfRegOp(Loc);
1883 Asm->EmitDwarfRegOp(Entry.Loc);
1886 // Emit remaining complex address elements.
1887 for (; i < N; ++i) {
1888 uint64_t Element = DV.getAddrElement(i);
1889 if (Element == DIBuilder::OpPlus) {
1890 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1891 Asm->EmitULEB128(DV.getAddrElement(++i));
1892 } else if (Element == DIBuilder::OpDeref)
1893 Asm->EmitInt8(dwarf::DW_OP_deref);
1894 else llvm_unreachable("unknown Opcode found in complex address");
1898 // else ... ignore constant fp. There is not any good way to
1899 // to represent them here in dwarf.
1900 Asm->OutStreamer.EmitLabel(end);
1905 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1907 void DwarfDebug::EmitDebugARanges() {
1908 // Start the dwarf aranges section.
1909 Asm->OutStreamer.SwitchSection(
1910 Asm->getObjFileLowering().getDwarfARangesSection());
1913 /// emitDebugRanges - Emit visible names into a debug ranges section.
1915 void DwarfDebug::emitDebugRanges() {
1916 // Start the dwarf ranges section.
1917 Asm->OutStreamer.SwitchSection(
1918 Asm->getObjFileLowering().getDwarfRangesSection());
1919 unsigned char Size = Asm->getTargetData().getPointerSize();
1920 for (SmallVector<const MCSymbol *, 8>::iterator
1921 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1924 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1926 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1930 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1932 void DwarfDebug::emitDebugMacInfo() {
1933 if (const MCSection *LineInfo =
1934 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1935 // Start the dwarf macinfo section.
1936 Asm->OutStreamer.SwitchSection(LineInfo);
1940 /// emitDebugInlineInfo - Emit inline info using following format.
1942 /// 1. length of section
1943 /// 2. Dwarf version number
1944 /// 3. address size.
1946 /// Entries (one "entry" for each function that was inlined):
1948 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1949 /// otherwise offset into __debug_str for regular function name.
1950 /// 2. offset into __debug_str section for regular function name.
1951 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1952 /// instances for the function.
1954 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1955 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1956 /// __debug_info section, and the low_pc is the starting address for the
1957 /// inlining instance.
1958 void DwarfDebug::emitDebugInlineInfo() {
1959 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1965 Asm->OutStreamer.SwitchSection(
1966 Asm->getObjFileLowering().getDwarfDebugInlineSection());
1968 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
1969 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
1970 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
1972 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
1974 Asm->OutStreamer.AddComment("Dwarf Version");
1975 Asm->EmitInt16(dwarf::DWARF_VERSION);
1976 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1977 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1979 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
1980 E = InlinedSPNodes.end(); I != E; ++I) {
1982 const MDNode *Node = *I;
1983 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
1984 = InlineInfo.find(Node);
1985 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
1986 DISubprogram SP(Node);
1987 StringRef LName = SP.getLinkageName();
1988 StringRef Name = SP.getName();
1990 Asm->OutStreamer.AddComment("MIPS linkage name");
1991 if (LName.empty()) {
1992 Asm->OutStreamer.EmitBytes(Name, 0);
1993 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
1995 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
1996 DwarfStrSectionSym);
1998 Asm->OutStreamer.AddComment("Function name");
1999 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2000 Asm->EmitULEB128(Labels.size(), "Inline count");
2002 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2003 LE = Labels.end(); LI != LE; ++LI) {
2004 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2005 Asm->EmitInt32(LI->second->getOffset());
2007 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2008 Asm->OutStreamer.EmitSymbolValue(LI->first,
2009 Asm->getTargetData().getPointerSize(),0);
2013 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));