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 childrens 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 // MCStream expects full path name as filename.
446 if (!DirName.empty() && !sys::path::is_absolute(FileName)) {
447 SmallString<128> FullPathName = DirName;
448 sys::path::append(FullPathName, FileName);
449 // Here FullPathName will be copied into StringMap by GetOrCreateSourceID.
450 return GetOrCreateSourceID(StringRef(FullPathName), StringRef());
453 StringMapEntry<unsigned> &Entry = SourceIdMap.GetOrCreateValue(FileName);
454 if (Entry.getValue())
455 return Entry.getValue();
457 unsigned SrcId = SourceIdMap.size();
458 Entry.setValue(SrcId);
460 // Print out a .file directive to specify files for .loc directives.
461 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, Entry.getKey());
466 /// constructCompileUnit - Create new CompileUnit for the given
467 /// metadata node with tag DW_TAG_compile_unit.
468 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
469 DICompileUnit DIUnit(N);
470 StringRef FN = DIUnit.getFilename();
471 StringRef Dir = DIUnit.getDirectory();
472 unsigned ID = GetOrCreateSourceID(FN, Dir);
474 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
475 CompileUnit *NewCU = new CompileUnit(ID, Die, Asm, this);
476 NewCU->addString(Die, dwarf::DW_AT_producer, dwarf::DW_FORM_string,
477 DIUnit.getProducer());
478 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
479 DIUnit.getLanguage());
480 NewCU->addString(Die, dwarf::DW_AT_name, dwarf::DW_FORM_string, FN);
481 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
482 // simplifies debug range entries.
483 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
484 // DW_AT_stmt_list is a offset of line number information for this
485 // compile unit in debug_line section.
486 if(Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
487 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
488 Asm->GetTempSymbol("section_line"));
490 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
493 NewCU->addString(Die, dwarf::DW_AT_comp_dir, dwarf::DW_FORM_string, Dir);
494 if (DIUnit.isOptimized())
495 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
497 StringRef Flags = DIUnit.getFlags();
499 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, dwarf::DW_FORM_string,
502 unsigned RVer = DIUnit.getRunTimeVersion();
504 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
505 dwarf::DW_FORM_data1, RVer);
509 CUMap.insert(std::make_pair(N, NewCU));
513 /// construct SubprogramDIE - Construct subprogram DIE.
514 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
517 if (!SP.isDefinition())
518 // This is a method declaration which will be handled while constructing
522 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
525 TheCU->insertDIE(N, SubprogramDie);
527 // Add to context owner.
528 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
531 TheCU->addGlobal(SP.getName(), SubprogramDie);
537 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
538 /// as llvm.dbg.enum and llvm.dbg.ty
539 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
540 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
541 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
542 const MDNode *N = NMD->getOperand(i);
543 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
544 constructSubprogramDIE(CU, N);
547 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
548 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
549 const MDNode *N = NMD->getOperand(i);
550 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
551 CU->createGlobalVariableDIE(N);
554 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
555 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
556 DIType Ty(NMD->getOperand(i));
557 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
558 CU->getOrCreateTypeDIE(Ty);
561 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
562 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
563 DIType Ty(NMD->getOperand(i));
564 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
565 CU->getOrCreateTypeDIE(Ty);
569 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
570 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
571 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
572 DebugInfoFinder DbgFinder;
573 DbgFinder.processModule(*M);
575 bool HasDebugInfo = false;
576 // Scan all the compile-units to see if there are any marked as the main
577 // unit. If not, we do not generate debug info.
578 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
579 E = DbgFinder.compile_unit_end(); I != E; ++I) {
580 if (DICompileUnit(*I).isMain()) {
585 if (!HasDebugInfo) return false;
587 // Create all the compile unit DIEs.
588 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
589 E = DbgFinder.compile_unit_end(); I != E; ++I)
590 constructCompileUnit(*I);
592 // Create DIEs for each global variable.
593 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
594 E = DbgFinder.global_variable_end(); I != E; ++I) {
595 const MDNode *N = *I;
596 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
597 CU->createGlobalVariableDIE(N);
600 // Create DIEs for each subprogram.
601 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
602 E = DbgFinder.subprogram_end(); I != E; ++I) {
603 const MDNode *N = *I;
604 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
605 constructSubprogramDIE(CU, N);
611 /// beginModule - Emit all Dwarf sections that should come prior to the
612 /// content. Create global DIEs and emit initial debug info sections.
613 /// This is invoked by the target AsmPrinter.
614 void DwarfDebug::beginModule(Module *M) {
615 if (DisableDebugInfoPrinting)
618 // If module has named metadata anchors then use them, otherwise scan the
619 // module using debug info finder to collect debug info.
620 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
622 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
623 DICompileUnit CUNode(CU_Nodes->getOperand(i));
624 CompileUnit *CU = constructCompileUnit(CUNode);
625 DIArray GVs = CUNode.getGlobalVariables();
626 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
627 CU->createGlobalVariableDIE(GVs.getElement(i));
628 DIArray SPs = CUNode.getSubprograms();
629 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
630 constructSubprogramDIE(CU, SPs.getElement(i));
631 DIArray EnumTypes = CUNode.getEnumTypes();
632 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
633 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
634 DIArray RetainedTypes = CUNode.getRetainedTypes();
635 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
636 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
638 } else if (!collectLegacyDebugInfo(M))
641 collectInfoFromNamedMDNodes(M);
643 // Tell MMI that we have debug info.
644 MMI->setDebugInfoAvailability(true);
646 // Emit initial sections.
649 // Prime section data.
650 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
653 /// endModule - Emit all Dwarf sections that should come after the content.
655 void DwarfDebug::endModule() {
656 if (!FirstCU) return;
657 const Module *M = MMI->getModule();
658 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
660 // Collect info for variables that were optimized out.
661 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
662 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
663 DICompileUnit TheCU(CU_Nodes->getOperand(i));
664 DIArray Subprograms = TheCU.getSubprograms();
665 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
666 DISubprogram SP(Subprograms.getElement(i));
667 if (ProcessedSPNodes.count(SP) != 0) continue;
668 if (!SP.Verify()) continue;
669 if (!SP.isDefinition()) continue;
670 StringRef FName = SP.getLinkageName();
672 FName = SP.getName();
673 NamedMDNode *NMD = getFnSpecificMDNode(*(MMI->getModule()), FName);
675 unsigned E = NMD->getNumOperands();
677 LexicalScope *Scope =
678 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
679 DeadFnScopeMap[SP] = Scope;
681 // Construct subprogram DIE and add variables DIEs.
682 SmallVector<DbgVariable, 8> Variables;
683 for (unsigned I = 0; I != E; ++I) {
684 DIVariable DV(NMD->getOperand(I));
685 if (!DV.Verify()) continue;
686 Variables.push_back(DbgVariable(DV, NULL));
688 CompileUnit *SPCU = CUMap.lookup(TheCU);
689 assert (SPCU && "Unable to find Compile Unit!");
690 constructSubprogramDIE(SPCU, SP);
691 DIE *ScopeDIE = SPCU->getDIE(SP);
692 for (unsigned i = 0, N = Variables.size(); i < N; ++i) {
693 if (DIE *VariableDIE =
694 SPCU->constructVariableDIE(&Variables[i], Scope->isAbstractScope()))
695 ScopeDIE->addChild(VariableDIE);
701 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
702 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
703 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
705 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
708 // Emit DW_AT_containing_type attribute to connect types with their
709 // vtable holding type.
710 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
711 CUE = CUMap.end(); CUI != CUE; ++CUI) {
712 CompileUnit *TheCU = CUI->second;
713 TheCU->constructContainingTypeDIEs();
716 // Standard sections final addresses.
717 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
718 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
719 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
720 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
722 // End text sections.
723 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
724 Asm->OutStreamer.SwitchSection(SectionMap[i]);
725 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
728 // Compute DIE offsets and sizes.
729 computeSizeAndOffsets();
731 // Emit all the DIEs into a debug info section
734 // Corresponding abbreviations into a abbrev section.
737 // Emit info into a debug pubnames section.
740 // Emit info into a debug pubtypes section.
743 // Emit info into a debug loc section.
746 // Emit info into a debug aranges section.
749 // Emit info into a debug ranges section.
752 // Emit info into a debug macinfo section.
756 emitDebugInlineInfo();
758 // Emit info into a debug str section.
762 DeleteContainerSeconds(DeadFnScopeMap);
764 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
765 E = CUMap.end(); I != E; ++I)
767 FirstCU = NULL; // Reset for the next Module, if any.
770 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
771 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
773 LLVMContext &Ctx = DV->getContext();
774 // More then one inlined variable corresponds to one abstract variable.
775 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
776 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
778 return AbsDbgVariable;
780 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
784 AbsDbgVariable = new DbgVariable(Var, NULL);
785 addScopeVariable(Scope, AbsDbgVariable);
786 AbstractVariables[Var] = AbsDbgVariable;
787 return AbsDbgVariable;
790 /// addCurrentFnArgument - If Var is a current function argument then add
791 /// it to CurrentFnArguments list.
792 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
793 DbgVariable *Var, LexicalScope *Scope) {
794 if (!LScopes.isCurrentFunctionScope(Scope))
796 DIVariable DV = Var->getVariable();
797 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
799 unsigned ArgNo = DV.getArgNumber();
803 size_t Size = CurrentFnArguments.size();
805 CurrentFnArguments.resize(MF->getFunction()->arg_size());
806 // llvm::Function argument size is not good indicator of how many
807 // arguments does the function have at source level.
809 CurrentFnArguments.resize(ArgNo * 2);
810 CurrentFnArguments[ArgNo - 1] = Var;
814 /// collectVariableInfoFromMMITable - Collect variable information from
815 /// side table maintained by MMI.
817 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
818 SmallPtrSet<const MDNode *, 16> &Processed) {
819 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
820 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
821 VE = VMap.end(); VI != VE; ++VI) {
822 const MDNode *Var = VI->first;
824 Processed.insert(Var);
826 const std::pair<unsigned, DebugLoc> &VP = VI->second;
828 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
830 // If variable scope is not found then skip this variable.
834 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
835 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
836 RegVar->setFrameIndex(VP.first);
837 if (!addCurrentFnArgument(MF, RegVar, Scope))
838 addScopeVariable(Scope, RegVar);
840 AbsDbgVariable->setFrameIndex(VP.first);
844 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
845 /// DBG_VALUE instruction, is in a defined reg.
846 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
847 assert (MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
848 return MI->getNumOperands() == 3 &&
849 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
850 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
853 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
855 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
856 const MCSymbol *FLabel,
857 const MCSymbol *SLabel,
858 const MachineInstr *MI) {
859 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
861 if (MI->getNumOperands() != 3) {
862 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
863 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
865 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
866 MachineLocation MLoc;
867 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
868 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
870 if (MI->getOperand(0).isImm())
871 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
872 if (MI->getOperand(0).isFPImm())
873 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
874 if (MI->getOperand(0).isCImm())
875 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
877 assert (0 && "Unexpected 3 operand DBG_VALUE instruction!");
878 return DotDebugLocEntry();
881 /// collectVariableInfo - Find variables for each lexical scope.
883 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
884 SmallPtrSet<const MDNode *, 16> &Processed) {
886 /// collection info from MMI table.
887 collectVariableInfoFromMMITable(MF, Processed);
889 for (SmallVectorImpl<const MDNode*>::const_iterator
890 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
892 const MDNode *Var = *UVI;
893 if (Processed.count(Var))
896 // History contains relevant DBG_VALUE instructions for Var and instructions
898 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
901 const MachineInstr *MInsn = History.front();
904 LexicalScope *Scope = NULL;
905 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
906 DISubprogram(DV.getContext()).describes(MF->getFunction()))
907 Scope = LScopes.getCurrentFunctionScope();
909 if (DV.getVersion() <= LLVMDebugVersion9)
910 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
912 if (MDNode *IA = DV.getInlinedAt())
913 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
915 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
918 // If variable scope is not found then skip this variable.
922 Processed.insert(DV);
923 assert(MInsn->isDebugValue() && "History must begin with debug value");
924 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
925 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
926 if (!addCurrentFnArgument(MF, RegVar, Scope))
927 addScopeVariable(Scope, RegVar);
929 AbsVar->setMInsn(MInsn);
931 // Simple ranges that are fully coalesced.
932 if (History.size() <= 1 || (History.size() == 2 &&
933 MInsn->isIdenticalTo(History.back()))) {
934 RegVar->setMInsn(MInsn);
938 // handle multiple DBG_VALUE instructions describing one variable.
939 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
941 for (SmallVectorImpl<const MachineInstr*>::const_iterator
942 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
943 const MachineInstr *Begin = *HI;
944 assert(Begin->isDebugValue() && "Invalid History entry");
946 // Check if DBG_VALUE is truncating a range.
947 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
948 && !Begin->getOperand(0).getReg())
951 // Compute the range for a register location.
952 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
953 const MCSymbol *SLabel = 0;
956 // If Begin is the last instruction in History then its value is valid
957 // until the end of the function.
958 SLabel = FunctionEndSym;
960 const MachineInstr *End = HI[1];
961 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
962 << "\t" << *Begin << "\t" << *End << "\n");
963 if (End->isDebugValue())
964 SLabel = getLabelBeforeInsn(End);
966 // End is a normal instruction clobbering the range.
967 SLabel = getLabelAfterInsn(End);
968 assert(SLabel && "Forgot label after clobber instruction");
973 // The value is valid until the next DBG_VALUE or clobber.
974 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
976 DotDebugLocEntries.push_back(DotDebugLocEntry());
979 // Collect info for variables that were optimized out.
980 const Function *F = MF->getFunction();
981 if (NamedMDNode *NMD = getFnSpecificMDNode(*(F->getParent()), F->getName())) {
982 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
983 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
984 if (!DV || !Processed.insert(DV))
986 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
987 addScopeVariable(Scope, new DbgVariable(DV, NULL));
992 /// getLabelBeforeInsn - Return Label preceding the instruction.
993 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
994 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
995 assert(Label && "Didn't insert label before instruction");
999 /// getLabelAfterInsn - Return Label immediately following the instruction.
1000 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1001 return LabelsAfterInsn.lookup(MI);
1004 /// beginInstruction - Process beginning of an instruction.
1005 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1006 // Check if source location changes, but ignore DBG_VALUE locations.
1007 if (!MI->isDebugValue()) {
1008 DebugLoc DL = MI->getDebugLoc();
1009 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1010 unsigned Flags = DWARF2_FLAG_IS_STMT;
1012 if (DL == PrologEndLoc) {
1013 Flags |= DWARF2_FLAG_PROLOGUE_END;
1014 PrologEndLoc = DebugLoc();
1016 if (!DL.isUnknown()) {
1017 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1018 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1020 recordSourceLine(0, 0, 0, 0);
1024 // Insert labels where requested.
1025 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1026 LabelsBeforeInsn.find(MI);
1029 if (I == LabelsBeforeInsn.end())
1032 // Label already assigned.
1037 PrevLabel = MMI->getContext().CreateTempSymbol();
1038 Asm->OutStreamer.EmitLabel(PrevLabel);
1040 I->second = PrevLabel;
1043 /// endInstruction - Process end of an instruction.
1044 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1045 // Don't create a new label after DBG_VALUE instructions.
1046 // They don't generate code.
1047 if (!MI->isDebugValue())
1050 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1051 LabelsAfterInsn.find(MI);
1054 if (I == LabelsAfterInsn.end())
1057 // Label already assigned.
1061 // We need a label after this instruction.
1063 PrevLabel = MMI->getContext().CreateTempSymbol();
1064 Asm->OutStreamer.EmitLabel(PrevLabel);
1066 I->second = PrevLabel;
1069 /// identifyScopeMarkers() -
1070 /// Each LexicalScope has first instruction and last instruction to mark
1071 /// beginning and end of a scope respectively. Create an inverse map that list
1072 /// scopes starts (and ends) with an instruction. One instruction may start (or
1073 /// end) multiple scopes. Ignore scopes that are not reachable.
1074 void DwarfDebug::identifyScopeMarkers() {
1075 SmallVector<LexicalScope *, 4> WorkList;
1076 WorkList.push_back(LScopes.getCurrentFunctionScope());
1077 while (!WorkList.empty()) {
1078 LexicalScope *S = WorkList.pop_back_val();
1080 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1081 if (!Children.empty())
1082 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1083 SE = Children.end(); SI != SE; ++SI)
1084 WorkList.push_back(*SI);
1086 if (S->isAbstractScope())
1089 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1092 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1093 RE = Ranges.end(); RI != RE; ++RI) {
1094 assert(RI->first && "InsnRange does not have first instruction!");
1095 assert(RI->second && "InsnRange does not have second instruction!");
1096 requestLabelBeforeInsn(RI->first);
1097 requestLabelAfterInsn(RI->second);
1102 /// getScopeNode - Get MDNode for DebugLoc's scope.
1103 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1104 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1105 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1106 return DL.getScope(Ctx);
1109 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1110 /// line number info for the function.
1111 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1112 const MDNode *Scope = getScopeNode(DL, Ctx);
1113 DISubprogram SP = getDISubprogram(Scope);
1115 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1119 /// beginFunction - Gather pre-function debug information. Assumes being
1120 /// emitted immediately after the function entry point.
1121 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1122 if (!MMI->hasDebugInfo()) return;
1123 LScopes.initialize(*MF);
1124 if (LScopes.empty()) return;
1125 identifyScopeMarkers();
1127 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1128 Asm->getFunctionNumber());
1129 // Assumes in correct section after the entry point.
1130 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1132 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1134 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1135 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1136 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1138 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1140 bool AtBlockEntry = true;
1141 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1143 const MachineInstr *MI = II;
1145 if (MI->isDebugValue()) {
1146 assert (MI->getNumOperands() > 1 && "Invalid machine instruction!");
1148 // Keep track of user variables.
1150 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1152 // Variable is in a register, we need to check for clobbers.
1153 if (isDbgValueInDefinedReg(MI))
1154 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1156 // Check the history of this variable.
1157 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1158 if (History.empty()) {
1159 UserVariables.push_back(Var);
1160 // The first mention of a function argument gets the FunctionBeginSym
1161 // label, so arguments are visible when breaking at function entry.
1163 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1164 DISubprogram(getDISubprogram(DV.getContext()))
1165 .describes(MF->getFunction()))
1166 LabelsBeforeInsn[MI] = FunctionBeginSym;
1168 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1169 const MachineInstr *Prev = History.back();
1170 if (Prev->isDebugValue()) {
1171 // Coalesce identical entries at the end of History.
1172 if (History.size() >= 2 &&
1173 Prev->isIdenticalTo(History[History.size() - 2])) {
1174 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1176 << "\t" << *History[History.size() - 2] << "\n");
1180 // Terminate old register assignments that don't reach MI;
1181 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1182 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1183 isDbgValueInDefinedReg(Prev)) {
1184 // Previous register assignment needs to terminate at the end of
1186 MachineBasicBlock::const_iterator LastMI =
1187 PrevMBB->getLastNonDebugInstr();
1188 if (LastMI == PrevMBB->end()) {
1189 // Drop DBG_VALUE for empty range.
1190 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1191 << "\t" << *Prev << "\n");
1195 // Terminate after LastMI.
1196 History.push_back(LastMI);
1201 History.push_back(MI);
1203 // Not a DBG_VALUE instruction.
1205 AtBlockEntry = false;
1207 // First known non DBG_VALUE location marks beginning of function
1209 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1210 PrologEndLoc = MI->getDebugLoc();
1212 // Check if the instruction clobbers any registers with debug vars.
1213 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1214 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1215 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1217 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1218 unsigned Reg = *AI; ++AI) {
1219 const MDNode *Var = LiveUserVar[Reg];
1222 // Reg is now clobbered.
1223 LiveUserVar[Reg] = 0;
1225 // Was MD last defined by a DBG_VALUE referring to Reg?
1226 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1227 if (HistI == DbgValues.end())
1229 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1230 if (History.empty())
1232 const MachineInstr *Prev = History.back();
1233 // Sanity-check: Register assignments are terminated at the end of
1235 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1237 // Is the variable still in Reg?
1238 if (!isDbgValueInDefinedReg(Prev) ||
1239 Prev->getOperand(0).getReg() != Reg)
1241 // Var is clobbered. Make sure the next instruction gets a label.
1242 History.push_back(MI);
1249 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1251 SmallVectorImpl<const MachineInstr*> &History = I->second;
1252 if (History.empty())
1255 // Make sure the final register assignments are terminated.
1256 const MachineInstr *Prev = History.back();
1257 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1258 const MachineBasicBlock *PrevMBB = Prev->getParent();
1259 MachineBasicBlock::const_iterator LastMI =
1260 PrevMBB->getLastNonDebugInstr();
1261 if (LastMI == PrevMBB->end())
1262 // Drop DBG_VALUE for empty range.
1265 // Terminate after LastMI.
1266 History.push_back(LastMI);
1269 // Request labels for the full history.
1270 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1271 const MachineInstr *MI = History[i];
1272 if (MI->isDebugValue())
1273 requestLabelBeforeInsn(MI);
1275 requestLabelAfterInsn(MI);
1279 PrevInstLoc = DebugLoc();
1280 PrevLabel = FunctionBeginSym;
1282 // Record beginning of function.
1283 if (!PrologEndLoc.isUnknown()) {
1284 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1285 MF->getFunction()->getContext());
1286 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1287 FnStartDL.getScope(MF->getFunction()->getContext()),
1288 DWARF2_FLAG_IS_STMT);
1292 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1293 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1294 ScopeVariables[LS].push_back(Var);
1295 // Vars.push_back(Var);
1298 /// endFunction - Gather and emit post-function debug information.
1300 void DwarfDebug::endFunction(const MachineFunction *MF) {
1301 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1303 // Define end label for subprogram.
1304 FunctionEndSym = Asm->GetTempSymbol("func_end",
1305 Asm->getFunctionNumber());
1306 // Assumes in correct section after the entry point.
1307 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1309 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1310 collectVariableInfo(MF, ProcessedVars);
1312 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1313 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1314 assert (TheCU && "Unable to find compile unit!");
1316 // Construct abstract scopes.
1317 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1318 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1319 LexicalScope *AScope = AList[i];
1320 DISubprogram SP(AScope->getScopeNode());
1322 // Collect info for variables that were optimized out.
1323 StringRef FName = SP.getLinkageName();
1325 FName = SP.getName();
1326 if (NamedMDNode *NMD =
1327 getFnSpecificMDNode(*(MF->getFunction()->getParent()), FName)) {
1328 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
1329 DIVariable DV(cast<MDNode>(NMD->getOperand(i)));
1330 if (!DV || !ProcessedVars.insert(DV))
1332 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1333 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1337 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1338 constructScopeDIE(TheCU, AScope);
1341 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1343 if (!DisableFramePointerElim(*MF))
1344 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1345 dwarf::DW_FORM_flag, 1);
1347 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1348 MMI->getFrameMoves()));
1351 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1352 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1353 DeleteContainerPointers(I->second);
1354 ScopeVariables.clear();
1355 DeleteContainerPointers(CurrentFnArguments);
1356 UserVariables.clear();
1358 AbstractVariables.clear();
1359 LabelsBeforeInsn.clear();
1360 LabelsAfterInsn.clear();
1364 /// recordSourceLine - Register a source line with debug info. Returns the
1365 /// unique label that was emitted and which provides correspondence to
1366 /// the source line list.
1367 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1373 DIDescriptor Scope(S);
1375 if (Scope.isCompileUnit()) {
1376 DICompileUnit CU(S);
1377 Fn = CU.getFilename();
1378 Dir = CU.getDirectory();
1379 } else if (Scope.isFile()) {
1381 Fn = F.getFilename();
1382 Dir = F.getDirectory();
1383 } else if (Scope.isSubprogram()) {
1385 Fn = SP.getFilename();
1386 Dir = SP.getDirectory();
1387 } else if (Scope.isLexicalBlock()) {
1388 DILexicalBlock DB(S);
1389 Fn = DB.getFilename();
1390 Dir = DB.getDirectory();
1392 assert(0 && "Unexpected scope info");
1394 Src = GetOrCreateSourceID(Fn, Dir);
1396 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1399 //===----------------------------------------------------------------------===//
1401 //===----------------------------------------------------------------------===//
1403 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1406 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1407 // Get the children.
1408 const std::vector<DIE *> &Children = Die->getChildren();
1410 // If not last sibling and has children then add sibling offset attribute.
1411 if (!Last && !Children.empty())
1412 Die->addSiblingOffset(DIEValueAllocator);
1414 // Record the abbreviation.
1415 assignAbbrevNumber(Die->getAbbrev());
1417 // Get the abbreviation for this DIE.
1418 unsigned AbbrevNumber = Die->getAbbrevNumber();
1419 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1422 Die->setOffset(Offset);
1424 // Start the size with the size of abbreviation code.
1425 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1427 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1428 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1430 // Size the DIE attribute values.
1431 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1432 // Size attribute value.
1433 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1435 // Size the DIE children if any.
1436 if (!Children.empty()) {
1437 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1438 "Children flag not set");
1440 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1441 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1443 // End of children marker.
1444 Offset += sizeof(int8_t);
1447 Die->setSize(Offset - Die->getOffset());
1451 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1453 void DwarfDebug::computeSizeAndOffsets() {
1454 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1455 E = CUMap.end(); I != E; ++I) {
1456 // Compute size of compile unit header.
1458 sizeof(int32_t) + // Length of Compilation Unit Info
1459 sizeof(int16_t) + // DWARF version number
1460 sizeof(int32_t) + // Offset Into Abbrev. Section
1461 sizeof(int8_t); // Pointer Size (in bytes)
1462 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1466 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1467 /// temporary label to it if SymbolStem is specified.
1468 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1469 const char *SymbolStem = 0) {
1470 Asm->OutStreamer.SwitchSection(Section);
1471 if (!SymbolStem) return 0;
1473 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1474 Asm->OutStreamer.EmitLabel(TmpSym);
1478 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1479 /// the start of each one.
1480 void DwarfDebug::EmitSectionLabels() {
1481 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1483 // Dwarf sections base addresses.
1484 DwarfInfoSectionSym =
1485 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1486 DwarfAbbrevSectionSym =
1487 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1488 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1490 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1491 EmitSectionSym(Asm, MacroInfo);
1493 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1494 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1495 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1496 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1497 DwarfStrSectionSym =
1498 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1499 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1502 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1503 "section_debug_loc");
1505 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1506 EmitSectionSym(Asm, TLOF.getDataSection());
1509 /// emitDIE - Recursively emits a debug information entry.
1511 void DwarfDebug::emitDIE(DIE *Die) {
1512 // Get the abbreviation for this DIE.
1513 unsigned AbbrevNumber = Die->getAbbrevNumber();
1514 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1516 // Emit the code (index) for the abbreviation.
1517 if (Asm->isVerbose())
1518 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1519 Twine::utohexstr(Die->getOffset()) + ":0x" +
1520 Twine::utohexstr(Die->getSize()) + " " +
1521 dwarf::TagString(Abbrev->getTag()));
1522 Asm->EmitULEB128(AbbrevNumber);
1524 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1525 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1527 // Emit the DIE attribute values.
1528 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1529 unsigned Attr = AbbrevData[i].getAttribute();
1530 unsigned Form = AbbrevData[i].getForm();
1531 assert(Form && "Too many attributes for DIE (check abbreviation)");
1533 if (Asm->isVerbose())
1534 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1537 case dwarf::DW_AT_sibling:
1538 Asm->EmitInt32(Die->getSiblingOffset());
1540 case dwarf::DW_AT_abstract_origin: {
1541 DIEEntry *E = cast<DIEEntry>(Values[i]);
1542 DIE *Origin = E->getEntry();
1543 unsigned Addr = Origin->getOffset();
1544 Asm->EmitInt32(Addr);
1547 case dwarf::DW_AT_ranges: {
1548 // DW_AT_range Value encodes offset in debug_range section.
1549 DIEInteger *V = cast<DIEInteger>(Values[i]);
1551 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1552 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1556 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1558 DwarfDebugRangeSectionSym,
1563 case dwarf::DW_AT_location: {
1564 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1565 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1567 Values[i]->EmitValue(Asm, Form);
1570 case dwarf::DW_AT_accessibility: {
1571 if (Asm->isVerbose()) {
1572 DIEInteger *V = cast<DIEInteger>(Values[i]);
1573 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1575 Values[i]->EmitValue(Asm, Form);
1579 // Emit an attribute using the defined form.
1580 Values[i]->EmitValue(Asm, Form);
1585 // Emit the DIE children if any.
1586 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1587 const std::vector<DIE *> &Children = Die->getChildren();
1589 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1590 emitDIE(Children[j]);
1592 if (Asm->isVerbose())
1593 Asm->OutStreamer.AddComment("End Of Children Mark");
1598 /// emitDebugInfo - Emit the debug info section.
1600 void DwarfDebug::emitDebugInfo() {
1601 // Start debug info section.
1602 Asm->OutStreamer.SwitchSection(
1603 Asm->getObjFileLowering().getDwarfInfoSection());
1604 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1605 E = CUMap.end(); I != E; ++I) {
1606 CompileUnit *TheCU = I->second;
1607 DIE *Die = TheCU->getCUDie();
1609 // Emit the compile units header.
1610 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1613 // Emit size of content not including length itself
1614 unsigned ContentSize = Die->getSize() +
1615 sizeof(int16_t) + // DWARF version number
1616 sizeof(int32_t) + // Offset Into Abbrev. Section
1617 sizeof(int8_t); // Pointer Size (in bytes)
1619 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1620 Asm->EmitInt32(ContentSize);
1621 Asm->OutStreamer.AddComment("DWARF version number");
1622 Asm->EmitInt16(dwarf::DWARF_VERSION);
1623 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1624 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1625 DwarfAbbrevSectionSym);
1626 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1627 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1630 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1634 /// emitAbbreviations - Emit the abbreviation section.
1636 void DwarfDebug::emitAbbreviations() const {
1637 // Check to see if it is worth the effort.
1638 if (!Abbreviations.empty()) {
1639 // Start the debug abbrev section.
1640 Asm->OutStreamer.SwitchSection(
1641 Asm->getObjFileLowering().getDwarfAbbrevSection());
1643 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1645 // For each abbrevation.
1646 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1647 // Get abbreviation data
1648 const DIEAbbrev *Abbrev = Abbreviations[i];
1650 // Emit the abbrevations code (base 1 index.)
1651 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1653 // Emit the abbreviations data.
1657 // Mark end of abbreviations.
1658 Asm->EmitULEB128(0, "EOM(3)");
1660 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1664 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1665 /// the line matrix.
1667 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1668 // Define last address of section.
1669 Asm->OutStreamer.AddComment("Extended Op");
1672 Asm->OutStreamer.AddComment("Op size");
1673 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1674 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1675 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1677 Asm->OutStreamer.AddComment("Section end label");
1679 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1680 Asm->getTargetData().getPointerSize(),
1683 // Mark end of matrix.
1684 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1690 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1692 void DwarfDebug::emitDebugPubNames() {
1693 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1694 E = CUMap.end(); I != E; ++I) {
1695 CompileUnit *TheCU = I->second;
1696 // Start the dwarf pubnames section.
1697 Asm->OutStreamer.SwitchSection(
1698 Asm->getObjFileLowering().getDwarfPubNamesSection());
1700 Asm->OutStreamer.AddComment("Length of Public Names Info");
1701 Asm->EmitLabelDifference(
1702 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1703 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1705 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1708 Asm->OutStreamer.AddComment("DWARF Version");
1709 Asm->EmitInt16(dwarf::DWARF_VERSION);
1711 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1712 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1713 DwarfInfoSectionSym);
1715 Asm->OutStreamer.AddComment("Compilation Unit Length");
1716 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1717 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1720 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1721 for (StringMap<DIE*>::const_iterator
1722 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1723 const char *Name = GI->getKeyData();
1724 DIE *Entity = GI->second;
1726 Asm->OutStreamer.AddComment("DIE offset");
1727 Asm->EmitInt32(Entity->getOffset());
1729 if (Asm->isVerbose())
1730 Asm->OutStreamer.AddComment("External Name");
1731 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1734 Asm->OutStreamer.AddComment("End Mark");
1736 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1741 void DwarfDebug::emitDebugPubTypes() {
1742 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1743 E = CUMap.end(); I != E; ++I) {
1744 CompileUnit *TheCU = I->second;
1745 // Start the dwarf pubnames section.
1746 Asm->OutStreamer.SwitchSection(
1747 Asm->getObjFileLowering().getDwarfPubTypesSection());
1748 Asm->OutStreamer.AddComment("Length of Public Types Info");
1749 Asm->EmitLabelDifference(
1750 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1751 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1753 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1756 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1757 Asm->EmitInt16(dwarf::DWARF_VERSION);
1759 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1760 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1761 DwarfInfoSectionSym);
1763 Asm->OutStreamer.AddComment("Compilation Unit Length");
1764 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1765 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1768 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1769 for (StringMap<DIE*>::const_iterator
1770 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1771 const char *Name = GI->getKeyData();
1772 DIE *Entity = GI->second;
1774 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1775 Asm->EmitInt32(Entity->getOffset());
1777 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1778 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1781 Asm->OutStreamer.AddComment("End Mark");
1783 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1788 /// emitDebugStr - Emit visible names into a debug str section.
1790 void DwarfDebug::emitDebugStr() {
1791 // Check to see if it is worth the effort.
1792 if (StringPool.empty()) return;
1794 // Start the dwarf str section.
1795 Asm->OutStreamer.SwitchSection(
1796 Asm->getObjFileLowering().getDwarfStrSection());
1798 // Get all of the string pool entries and put them in an array by their ID so
1799 // we can sort them.
1800 SmallVector<std::pair<unsigned,
1801 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1803 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1804 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1805 Entries.push_back(std::make_pair(I->second.second, &*I));
1807 array_pod_sort(Entries.begin(), Entries.end());
1809 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1810 // Emit a label for reference from debug information entries.
1811 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1813 // Emit the string itself.
1814 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1818 /// emitDebugLoc - Emit visible names into a debug loc section.
1820 void DwarfDebug::emitDebugLoc() {
1821 if (DotDebugLocEntries.empty())
1824 for (SmallVector<DotDebugLocEntry, 4>::iterator
1825 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1827 DotDebugLocEntry &Entry = *I;
1828 if (I + 1 != DotDebugLocEntries.end())
1832 // Start the dwarf loc section.
1833 Asm->OutStreamer.SwitchSection(
1834 Asm->getObjFileLowering().getDwarfLocSection());
1835 unsigned char Size = Asm->getTargetData().getPointerSize();
1836 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1838 for (SmallVector<DotDebugLocEntry, 4>::iterator
1839 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1840 I != E; ++I, ++index) {
1841 DotDebugLocEntry &Entry = *I;
1842 if (Entry.isMerged()) continue;
1843 if (Entry.isEmpty()) {
1844 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1845 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1846 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1848 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1849 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1850 DIVariable DV(Entry.Variable);
1851 Asm->OutStreamer.AddComment("Loc expr size");
1852 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1853 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1854 Asm->EmitLabelDifference(end, begin, 2);
1855 Asm->OutStreamer.EmitLabel(begin);
1856 if (Entry.isInt()) {
1857 DIBasicType BTy(DV.getType());
1859 (BTy.getEncoding() == dwarf::DW_ATE_signed
1860 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1861 Asm->OutStreamer.AddComment("DW_OP_consts");
1862 Asm->EmitInt8(dwarf::DW_OP_consts);
1863 Asm->EmitSLEB128(Entry.getInt());
1865 Asm->OutStreamer.AddComment("DW_OP_constu");
1866 Asm->EmitInt8(dwarf::DW_OP_constu);
1867 Asm->EmitULEB128(Entry.getInt());
1869 } else if (Entry.isLocation()) {
1870 if (!DV.hasComplexAddress())
1872 Asm->EmitDwarfRegOp(Entry.Loc);
1874 // Complex address entry.
1875 unsigned N = DV.getNumAddrElements();
1877 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1878 if (Entry.Loc.getOffset()) {
1880 Asm->EmitDwarfRegOp(Entry.Loc);
1881 Asm->OutStreamer.AddComment("DW_OP_deref");
1882 Asm->EmitInt8(dwarf::DW_OP_deref);
1883 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1884 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1885 Asm->EmitSLEB128(DV.getAddrElement(1));
1887 // If first address element is OpPlus then emit
1888 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1889 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1890 Asm->EmitDwarfRegOp(Loc);
1894 Asm->EmitDwarfRegOp(Entry.Loc);
1897 // Emit remaining complex address elements.
1898 for (; i < N; ++i) {
1899 uint64_t Element = DV.getAddrElement(i);
1900 if (Element == DIBuilder::OpPlus) {
1901 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1902 Asm->EmitULEB128(DV.getAddrElement(++i));
1903 } else if (Element == DIBuilder::OpDeref)
1904 Asm->EmitInt8(dwarf::DW_OP_deref);
1905 else llvm_unreachable("unknown Opcode found in complex address");
1909 // else ... ignore constant fp. There is not any good way to
1910 // to represent them here in dwarf.
1911 Asm->OutStreamer.EmitLabel(end);
1916 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1918 void DwarfDebug::EmitDebugARanges() {
1919 // Start the dwarf aranges section.
1920 Asm->OutStreamer.SwitchSection(
1921 Asm->getObjFileLowering().getDwarfARangesSection());
1924 /// emitDebugRanges - Emit visible names into a debug ranges section.
1926 void DwarfDebug::emitDebugRanges() {
1927 // Start the dwarf ranges section.
1928 Asm->OutStreamer.SwitchSection(
1929 Asm->getObjFileLowering().getDwarfRangesSection());
1930 unsigned char Size = Asm->getTargetData().getPointerSize();
1931 for (SmallVector<const MCSymbol *, 8>::iterator
1932 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1935 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1937 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1941 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1943 void DwarfDebug::emitDebugMacInfo() {
1944 if (const MCSection *LineInfo =
1945 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1946 // Start the dwarf macinfo section.
1947 Asm->OutStreamer.SwitchSection(LineInfo);
1951 /// emitDebugInlineInfo - Emit inline info using following format.
1953 /// 1. length of section
1954 /// 2. Dwarf version number
1955 /// 3. address size.
1957 /// Entries (one "entry" for each function that was inlined):
1959 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1960 /// otherwise offset into __debug_str for regular function name.
1961 /// 2. offset into __debug_str section for regular function name.
1962 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1963 /// instances for the function.
1965 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1966 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1967 /// __debug_info section, and the low_pc is the starting address for the
1968 /// inlining instance.
1969 void DwarfDebug::emitDebugInlineInfo() {
1970 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1976 Asm->OutStreamer.SwitchSection(
1977 Asm->getObjFileLowering().getDwarfDebugInlineSection());
1979 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
1980 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
1981 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
1983 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
1985 Asm->OutStreamer.AddComment("Dwarf Version");
1986 Asm->EmitInt16(dwarf::DWARF_VERSION);
1987 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1988 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1990 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
1991 E = InlinedSPNodes.end(); I != E; ++I) {
1993 const MDNode *Node = *I;
1994 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
1995 = InlineInfo.find(Node);
1996 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
1997 DISubprogram SP(Node);
1998 StringRef LName = SP.getLinkageName();
1999 StringRef Name = SP.getName();
2001 Asm->OutStreamer.AddComment("MIPS linkage name");
2002 if (LName.empty()) {
2003 Asm->OutStreamer.EmitBytes(Name, 0);
2004 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
2006 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2007 DwarfStrSectionSym);
2009 Asm->OutStreamer.AddComment("Function name");
2010 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2011 Asm->EmitULEB128(Labels.size(), "Inline count");
2013 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2014 LE = Labels.end(); LI != LE; ++LI) {
2015 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2016 Asm->EmitInt32(LI->second->getOffset());
2018 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2019 Asm->OutStreamer.EmitSymbolValue(LI->first,
2020 Asm->getTargetData().getPointerSize(),0);
2024 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));