1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "DwarfCompileUnit.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Module.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineModuleInfo.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/MC/MCStreamer.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameLowering.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Analysis/DebugInfo.h"
34 #include "llvm/Analysis/DIBuilder.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/Path.h"
47 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
49 cl::desc("Disable debug info printing"));
51 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
52 cl::desc("Make an absence of debug location information explicit."),
56 const char *DWARFGroupName = "DWARF Emission";
57 const char *DbgTimerName = "DWARF Debug Writer";
58 } // end anonymous namespace
60 //===----------------------------------------------------------------------===//
62 /// Configuration values for initial hash set sizes (log2).
64 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
68 DIType DbgVariable::getType() const {
69 DIType Ty = Var.getType();
70 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
72 if (Var.isBlockByrefVariable()) {
73 /* Byref variables, in Blocks, are declared by the programmer as
74 "SomeType VarName;", but the compiler creates a
75 __Block_byref_x_VarName struct, and gives the variable VarName
76 either the struct, or a pointer to the struct, as its type. This
77 is necessary for various behind-the-scenes things the compiler
78 needs to do with by-reference variables in blocks.
80 However, as far as the original *programmer* is concerned, the
81 variable should still have type 'SomeType', as originally declared.
83 The following function dives into the __Block_byref_x_VarName
84 struct to find the original type of the variable. This will be
85 passed back to the code generating the type for the Debug
86 Information Entry for the variable 'VarName'. 'VarName' will then
87 have the original type 'SomeType' in its debug information.
89 The original type 'SomeType' will be the type of the field named
90 'VarName' inside the __Block_byref_x_VarName struct.
92 NOTE: In order for this to not completely fail on the debugger
93 side, the Debug Information Entry for the variable VarName needs to
94 have a DW_AT_location that tells the debugger how to unwind through
95 the pointers and __Block_byref_x_VarName struct to find the actual
96 value of the variable. The function addBlockByrefType does this. */
98 unsigned tag = Ty.getTag();
100 if (tag == dwarf::DW_TAG_pointer_type) {
101 DIDerivedType DTy = DIDerivedType(Ty);
102 subType = DTy.getTypeDerivedFrom();
105 DICompositeType blockStruct = DICompositeType(subType);
106 DIArray Elements = blockStruct.getTypeArray();
108 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
109 DIDescriptor Element = Elements.getElement(i);
110 DIDerivedType DT = DIDerivedType(Element);
111 if (getName() == DT.getName())
112 return (DT.getTypeDerivedFrom());
119 } // end llvm namespace
121 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
122 : Asm(A), MMI(Asm->MMI), FirstCU(0),
123 AbbreviationsSet(InitAbbreviationsSetSize),
125 NextStringPoolNumber = 0;
127 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
128 DwarfStrSectionSym = TextSectionSym = 0;
129 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
130 FunctionBeginSym = FunctionEndSym = 0;
132 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
136 DwarfDebug::~DwarfDebug() {
139 MCSymbol *DwarfDebug::getStringPool() {
140 return Asm->GetTempSymbol("section_str");
143 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
144 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
145 if (Entry.first) return Entry.first;
147 Entry.second = NextStringPoolNumber++;
148 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
152 /// assignAbbrevNumber - Define a unique number for the abbreviation.
154 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
155 // Profile the node so that we can make it unique.
159 // Check the set for priors.
160 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
162 // If it's newly added.
163 if (InSet == &Abbrev) {
164 // Add to abbreviation list.
165 Abbreviations.push_back(&Abbrev);
167 // Assign the vector position + 1 as its number.
168 Abbrev.setNumber(Abbreviations.size());
170 // Assign existing abbreviation number.
171 Abbrev.setNumber(InSet->getNumber());
175 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
176 /// printer to not emit usual symbol prefix before the symbol name is used then
177 /// return linkage name after skipping this special LLVM prefix.
178 static StringRef getRealLinkageName(StringRef LinkageName) {
180 if (LinkageName.startswith(StringRef(&One, 1)))
181 return LinkageName.substr(1);
185 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
186 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
187 /// If there are global variables in this scope then create and insert
188 /// DIEs for these variables.
189 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
190 const MDNode *SPNode) {
191 DIE *SPDie = SPCU->getDIE(SPNode);
193 assert(SPDie && "Unable to find subprogram DIE!");
194 DISubprogram SP(SPNode);
196 DISubprogram SPDecl = SP.getFunctionDeclaration();
197 if (SPDecl.isSubprogram())
198 // Refer function declaration directly.
199 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
200 SPCU->getOrCreateSubprogramDIE(SPDecl));
202 // There is not any need to generate specification DIE for a function
203 // defined at compile unit level. If a function is defined inside another
204 // function then gdb prefers the definition at top level and but does not
205 // expect specification DIE in parent function. So avoid creating
206 // specification DIE for a function defined inside a function.
207 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
208 !SP.getContext().isFile() &&
209 !isSubprogramContext(SP.getContext())) {
210 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
213 DICompositeType SPTy = SP.getType();
214 DIArray Args = SPTy.getTypeArray();
215 unsigned SPTag = SPTy.getTag();
216 if (SPTag == dwarf::DW_TAG_subroutine_type)
217 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
218 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
219 DIType ATy = DIType(DIType(Args.getElement(i)));
220 SPCU->addType(Arg, ATy);
221 if (ATy.isArtificial())
222 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
223 SPDie->addChild(Arg);
225 DIE *SPDeclDie = SPDie;
226 SPDie = new DIE(dwarf::DW_TAG_subprogram);
227 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
232 // Pick up abstract subprogram DIE.
233 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
234 SPDie = new DIE(dwarf::DW_TAG_subprogram);
235 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
236 dwarf::DW_FORM_ref4, AbsSPDIE);
240 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
241 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
242 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
243 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
244 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
245 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
246 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
251 /// constructLexicalScope - Construct new DW_TAG_lexical_block
252 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
253 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
254 LexicalScope *Scope) {
255 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
256 if (Scope->isAbstractScope())
259 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
263 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
264 if (Ranges.size() > 1) {
265 // .debug_range section has not been laid out yet. Emit offset in
266 // .debug_range as a uint, size 4, for now. emitDIE will handle
267 // DW_AT_ranges appropriately.
268 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
269 DebugRangeSymbols.size()
270 * Asm->getTargetData().getPointerSize());
271 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
272 RE = Ranges.end(); RI != RE; ++RI) {
273 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
274 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
276 DebugRangeSymbols.push_back(NULL);
277 DebugRangeSymbols.push_back(NULL);
281 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
282 const MCSymbol *End = getLabelAfterInsn(RI->second);
284 if (End == 0) return 0;
286 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
287 assert(End->isDefined() && "Invalid end label for an inlined scope!");
289 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
290 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
295 /// constructInlinedScopeDIE - This scope represents inlined body of
296 /// a function. Construct DIE to represent this concrete inlined copy
298 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
299 LexicalScope *Scope) {
300 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
301 assert(Ranges.empty() == false &&
302 "LexicalScope does not have instruction markers!");
304 if (!Scope->getScopeNode())
306 DIScope DS(Scope->getScopeNode());
307 DISubprogram InlinedSP = getDISubprogram(DS);
308 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
310 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
314 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
315 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
316 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
318 if (StartLabel == 0 || EndLabel == 0) {
319 assert(0 && "Unexpected Start and End labels for a inlined scope!");
322 assert(StartLabel->isDefined() &&
323 "Invalid starting label for an inlined scope!");
324 assert(EndLabel->isDefined() &&
325 "Invalid end label for an inlined scope!");
327 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
328 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
329 dwarf::DW_FORM_ref4, OriginDIE);
331 if (Ranges.size() > 1) {
332 // .debug_range section has not been laid out yet. Emit offset in
333 // .debug_range as a uint, size 4, for now. emitDIE will handle
334 // DW_AT_ranges appropriately.
335 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
336 DebugRangeSymbols.size()
337 * Asm->getTargetData().getPointerSize());
338 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
339 RE = Ranges.end(); RI != RE; ++RI) {
340 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
341 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
343 DebugRangeSymbols.push_back(NULL);
344 DebugRangeSymbols.push_back(NULL);
346 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
348 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
352 InlinedSubprogramDIEs.insert(OriginDIE);
354 // Track the start label for this inlined function.
355 //.debug_inlined section specification does not clearly state how
356 // to emit inlined scope that is split into multiple instruction ranges.
357 // For now, use first instruction range and emit low_pc/high_pc pair and
358 // corresponding .debug_inlined section entry for this pair.
359 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
360 I = InlineInfo.find(InlinedSP);
362 if (I == InlineInfo.end()) {
363 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
364 InlinedSPNodes.push_back(InlinedSP);
366 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
368 DILocation DL(Scope->getInlinedAt());
369 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0, TheCU->getID());
370 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
375 /// constructScopeDIE - Construct a DIE for this scope.
376 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
377 if (!Scope || !Scope->getScopeNode())
380 SmallVector<DIE *, 8> Children;
382 // Collect arguments for current function.
383 if (LScopes.isCurrentFunctionScope(Scope))
384 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
385 if (DbgVariable *ArgDV = CurrentFnArguments[i])
387 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
388 Children.push_back(Arg);
390 // Collect lexical scope children first.
391 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
392 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
394 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
395 Children.push_back(Variable);
396 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
397 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
398 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
399 Children.push_back(Nested);
400 DIScope DS(Scope->getScopeNode());
401 DIE *ScopeDIE = NULL;
402 if (Scope->getInlinedAt())
403 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
404 else if (DS.isSubprogram()) {
405 ProcessedSPNodes.insert(DS);
406 if (Scope->isAbstractScope()) {
407 ScopeDIE = TheCU->getDIE(DS);
408 // Note down abstract DIE.
410 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
413 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
416 // There is no need to emit empty lexical block DIE.
417 if (Children.empty())
419 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
422 if (!ScopeDIE) return NULL;
425 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
426 E = Children.end(); I != E; ++I)
427 ScopeDIE->addChild(*I);
429 if (DS.isSubprogram())
430 TheCU->addPubTypes(DISubprogram(DS));
435 /// GetOrCreateSourceID - Look up the source id with the given directory and
436 /// source file names. If none currently exists, create a new id and insert it
437 /// 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, DIUnit.getProducer());
475 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
476 DIUnit.getLanguage());
477 NewCU->addString(Die, dwarf::DW_AT_name, FN);
478 // Use DW_AT_entry_pc instead of DW_AT_low_pc/DW_AT_high_pc pair. This
479 // simplifies debug range entries.
480 NewCU->addUInt(Die, dwarf::DW_AT_entry_pc, dwarf::DW_FORM_addr, 0);
481 // DW_AT_stmt_list is a offset of line number information for this
482 // compile unit in debug_line section.
483 if (Asm->MAI->doesDwarfRequireRelocationForSectionOffset())
484 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
485 Asm->GetTempSymbol("section_line"));
487 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
490 NewCU->addString(Die, dwarf::DW_AT_comp_dir, Dir);
491 if (DIUnit.isOptimized())
492 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
494 StringRef Flags = DIUnit.getFlags();
496 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
498 if (unsigned RVer = DIUnit.getRunTimeVersion())
499 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
500 dwarf::DW_FORM_data1, RVer);
504 CUMap.insert(std::make_pair(N, NewCU));
508 /// construct SubprogramDIE - Construct subprogram DIE.
509 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
512 if (!SP.isDefinition())
513 // This is a method declaration which will be handled while constructing
517 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
520 TheCU->insertDIE(N, SubprogramDie);
522 // Add to context owner.
523 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
526 TheCU->addGlobal(SP.getName(), SubprogramDie);
532 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
533 /// as llvm.dbg.enum and llvm.dbg.ty
534 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
535 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
536 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
537 const MDNode *N = NMD->getOperand(i);
538 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
539 constructSubprogramDIE(CU, N);
542 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
543 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
544 const MDNode *N = NMD->getOperand(i);
545 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
546 CU->createGlobalVariableDIE(N);
549 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
550 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
551 DIType Ty(NMD->getOperand(i));
552 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
553 CU->getOrCreateTypeDIE(Ty);
556 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
557 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
558 DIType Ty(NMD->getOperand(i));
559 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
560 CU->getOrCreateTypeDIE(Ty);
564 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
565 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
566 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
567 DebugInfoFinder DbgFinder;
568 DbgFinder.processModule(*M);
570 bool HasDebugInfo = false;
571 // Scan all the compile-units to see if there are any marked as the main
572 // unit. If not, we do not generate debug info.
573 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
574 E = DbgFinder.compile_unit_end(); I != E; ++I) {
575 if (DICompileUnit(*I).isMain()) {
580 if (!HasDebugInfo) return false;
582 // Create all the compile unit DIEs.
583 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
584 E = DbgFinder.compile_unit_end(); I != E; ++I)
585 constructCompileUnit(*I);
587 // Create DIEs for each global variable.
588 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
589 E = DbgFinder.global_variable_end(); I != E; ++I) {
590 const MDNode *N = *I;
591 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
592 CU->createGlobalVariableDIE(N);
595 // Create DIEs for each subprogram.
596 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
597 E = DbgFinder.subprogram_end(); I != E; ++I) {
598 const MDNode *N = *I;
599 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
600 constructSubprogramDIE(CU, N);
606 /// beginModule - Emit all Dwarf sections that should come prior to the
607 /// content. Create global DIEs and emit initial debug info sections.
608 /// This is invoked by the target AsmPrinter.
609 void DwarfDebug::beginModule(Module *M) {
610 if (DisableDebugInfoPrinting)
613 // If module has named metadata anchors then use them, otherwise scan the
614 // module using debug info finder to collect debug info.
615 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
617 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
618 DICompileUnit CUNode(CU_Nodes->getOperand(i));
619 CompileUnit *CU = constructCompileUnit(CUNode);
620 DIArray GVs = CUNode.getGlobalVariables();
621 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
622 CU->createGlobalVariableDIE(GVs.getElement(i));
623 DIArray SPs = CUNode.getSubprograms();
624 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
625 constructSubprogramDIE(CU, SPs.getElement(i));
626 DIArray EnumTypes = CUNode.getEnumTypes();
627 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
628 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
629 DIArray RetainedTypes = CUNode.getRetainedTypes();
630 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
631 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
633 } else if (!collectLegacyDebugInfo(M))
636 collectInfoFromNamedMDNodes(M);
638 // Tell MMI that we have debug info.
639 MMI->setDebugInfoAvailability(true);
641 // Emit initial sections.
644 // Prime section data.
645 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
648 /// endModule - Emit all Dwarf sections that should come after the content.
650 void DwarfDebug::endModule() {
651 if (!FirstCU) return;
652 const Module *M = MMI->getModule();
653 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
655 // Collect info for variables that were optimized out.
656 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
657 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
658 DICompileUnit TheCU(CU_Nodes->getOperand(i));
659 DIArray Subprograms = TheCU.getSubprograms();
660 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
661 DISubprogram SP(Subprograms.getElement(i));
662 if (ProcessedSPNodes.count(SP) != 0) continue;
663 if (!SP.Verify()) continue;
664 if (!SP.isDefinition()) continue;
665 DIArray Variables = SP.getVariables();
666 if (Variables.getNumElements() == 0) continue;
668 LexicalScope *Scope =
669 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
670 DeadFnScopeMap[SP] = Scope;
672 // Construct subprogram DIE and add variables DIEs.
673 CompileUnit *SPCU = CUMap.lookup(TheCU);
674 assert(SPCU && "Unable to find Compile Unit!");
675 constructSubprogramDIE(SPCU, SP);
676 DIE *ScopeDIE = SPCU->getDIE(SP);
677 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
678 DIVariable DV(Variables.getElement(vi));
679 if (!DV.Verify()) continue;
680 DbgVariable *NewVar = new DbgVariable(DV, NULL);
681 if (DIE *VariableDIE =
682 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
683 ScopeDIE->addChild(VariableDIE);
689 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
690 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
691 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
693 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
696 // Emit DW_AT_containing_type attribute to connect types with their
697 // vtable holding type.
698 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
699 CUE = CUMap.end(); CUI != CUE; ++CUI) {
700 CompileUnit *TheCU = CUI->second;
701 TheCU->constructContainingTypeDIEs();
704 // Standard sections final addresses.
705 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
706 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
707 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
708 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
710 // End text sections.
711 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
712 Asm->OutStreamer.SwitchSection(SectionMap[i]);
713 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
716 // Compute DIE offsets and sizes.
717 computeSizeAndOffsets();
719 // Emit all the DIEs into a debug info section
722 // Corresponding abbreviations into a abbrev section.
725 // Emit info into a debug pubnames section.
728 // Emit info into a debug pubtypes section.
731 // Emit info into a debug loc section.
734 // Emit info into a debug aranges section.
737 // Emit info into a debug ranges section.
740 // Emit info into a debug macinfo section.
744 emitDebugInlineInfo();
746 // Emit info into a debug str section.
750 DeleteContainerSeconds(DeadFnScopeMap);
752 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
753 E = CUMap.end(); I != E; ++I)
755 FirstCU = NULL; // Reset for the next Module, if any.
758 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
759 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
761 LLVMContext &Ctx = DV->getContext();
762 // More then one inlined variable corresponds to one abstract variable.
763 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
764 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
766 return AbsDbgVariable;
768 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
772 AbsDbgVariable = new DbgVariable(Var, NULL);
773 addScopeVariable(Scope, AbsDbgVariable);
774 AbstractVariables[Var] = AbsDbgVariable;
775 return AbsDbgVariable;
778 /// addCurrentFnArgument - If Var is a current function argument then add
779 /// it to CurrentFnArguments list.
780 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
781 DbgVariable *Var, LexicalScope *Scope) {
782 if (!LScopes.isCurrentFunctionScope(Scope))
784 DIVariable DV = Var->getVariable();
785 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
787 unsigned ArgNo = DV.getArgNumber();
791 size_t Size = CurrentFnArguments.size();
793 CurrentFnArguments.resize(MF->getFunction()->arg_size());
794 // llvm::Function argument size is not good indicator of how many
795 // arguments does the function have at source level.
797 CurrentFnArguments.resize(ArgNo * 2);
798 CurrentFnArguments[ArgNo - 1] = Var;
802 /// collectVariableInfoFromMMITable - Collect variable information from
803 /// side table maintained by MMI.
805 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
806 SmallPtrSet<const MDNode *, 16> &Processed) {
807 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
808 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
809 VE = VMap.end(); VI != VE; ++VI) {
810 const MDNode *Var = VI->first;
812 Processed.insert(Var);
814 const std::pair<unsigned, DebugLoc> &VP = VI->second;
816 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
818 // If variable scope is not found then skip this variable.
822 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
823 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
824 RegVar->setFrameIndex(VP.first);
825 if (!addCurrentFnArgument(MF, RegVar, Scope))
826 addScopeVariable(Scope, RegVar);
828 AbsDbgVariable->setFrameIndex(VP.first);
832 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
833 /// DBG_VALUE instruction, is in a defined reg.
834 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
835 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
836 return MI->getNumOperands() == 3 &&
837 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
838 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
841 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
843 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
844 const MCSymbol *FLabel,
845 const MCSymbol *SLabel,
846 const MachineInstr *MI) {
847 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
849 if (MI->getNumOperands() != 3) {
850 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
851 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
853 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
854 MachineLocation MLoc;
855 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
856 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
858 if (MI->getOperand(0).isImm())
859 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
860 if (MI->getOperand(0).isFPImm())
861 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
862 if (MI->getOperand(0).isCImm())
863 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
865 assert(0 && "Unexpected 3 operand DBG_VALUE instruction!");
866 return DotDebugLocEntry();
869 /// collectVariableInfo - Find variables for each lexical scope.
871 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
872 SmallPtrSet<const MDNode *, 16> &Processed) {
874 /// collection info from MMI table.
875 collectVariableInfoFromMMITable(MF, Processed);
877 for (SmallVectorImpl<const MDNode*>::const_iterator
878 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
880 const MDNode *Var = *UVI;
881 if (Processed.count(Var))
884 // History contains relevant DBG_VALUE instructions for Var and instructions
886 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
889 const MachineInstr *MInsn = History.front();
892 LexicalScope *Scope = NULL;
893 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
894 DISubprogram(DV.getContext()).describes(MF->getFunction()))
895 Scope = LScopes.getCurrentFunctionScope();
897 if (DV.getVersion() <= LLVMDebugVersion9)
898 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
900 if (MDNode *IA = DV.getInlinedAt())
901 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
903 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
906 // If variable scope is not found then skip this variable.
910 Processed.insert(DV);
911 assert(MInsn->isDebugValue() && "History must begin with debug value");
912 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
913 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
914 if (!addCurrentFnArgument(MF, RegVar, Scope))
915 addScopeVariable(Scope, RegVar);
917 AbsVar->setMInsn(MInsn);
919 // Simple ranges that are fully coalesced.
920 if (History.size() <= 1 || (History.size() == 2 &&
921 MInsn->isIdenticalTo(History.back()))) {
922 RegVar->setMInsn(MInsn);
926 // handle multiple DBG_VALUE instructions describing one variable.
927 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
929 for (SmallVectorImpl<const MachineInstr*>::const_iterator
930 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
931 const MachineInstr *Begin = *HI;
932 assert(Begin->isDebugValue() && "Invalid History entry");
934 // Check if DBG_VALUE is truncating a range.
935 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
936 && !Begin->getOperand(0).getReg())
939 // Compute the range for a register location.
940 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
941 const MCSymbol *SLabel = 0;
944 // If Begin is the last instruction in History then its value is valid
945 // until the end of the function.
946 SLabel = FunctionEndSym;
948 const MachineInstr *End = HI[1];
949 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
950 << "\t" << *Begin << "\t" << *End << "\n");
951 if (End->isDebugValue())
952 SLabel = getLabelBeforeInsn(End);
954 // End is a normal instruction clobbering the range.
955 SLabel = getLabelAfterInsn(End);
956 assert(SLabel && "Forgot label after clobber instruction");
961 // The value is valid until the next DBG_VALUE or clobber.
962 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel, Begin));
964 DotDebugLocEntries.push_back(DotDebugLocEntry());
967 // Collect info for variables that were optimized out.
968 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
969 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
970 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
971 DIVariable DV(Variables.getElement(i));
972 if (!DV || !DV.Verify() || !Processed.insert(DV))
974 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
975 addScopeVariable(Scope, new DbgVariable(DV, NULL));
979 /// getLabelBeforeInsn - Return Label preceding the instruction.
980 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
981 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
982 assert(Label && "Didn't insert label before instruction");
986 /// getLabelAfterInsn - Return Label immediately following the instruction.
987 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
988 return LabelsAfterInsn.lookup(MI);
991 /// beginInstruction - Process beginning of an instruction.
992 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
993 // Check if source location changes, but ignore DBG_VALUE locations.
994 if (!MI->isDebugValue()) {
995 DebugLoc DL = MI->getDebugLoc();
996 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
997 unsigned Flags = DWARF2_FLAG_IS_STMT;
999 if (DL == PrologEndLoc) {
1000 Flags |= DWARF2_FLAG_PROLOGUE_END;
1001 PrologEndLoc = DebugLoc();
1003 if (!DL.isUnknown()) {
1004 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1005 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1007 recordSourceLine(0, 0, 0, 0);
1011 // Insert labels where requested.
1012 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1013 LabelsBeforeInsn.find(MI);
1016 if (I == LabelsBeforeInsn.end())
1019 // Label already assigned.
1024 PrevLabel = MMI->getContext().CreateTempSymbol();
1025 Asm->OutStreamer.EmitLabel(PrevLabel);
1027 I->second = PrevLabel;
1030 /// endInstruction - Process end of an instruction.
1031 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1032 // Don't create a new label after DBG_VALUE instructions.
1033 // They don't generate code.
1034 if (!MI->isDebugValue())
1037 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1038 LabelsAfterInsn.find(MI);
1041 if (I == LabelsAfterInsn.end())
1044 // Label already assigned.
1048 // We need a label after this instruction.
1050 PrevLabel = MMI->getContext().CreateTempSymbol();
1051 Asm->OutStreamer.EmitLabel(PrevLabel);
1053 I->second = PrevLabel;
1056 /// identifyScopeMarkers() -
1057 /// Each LexicalScope has first instruction and last instruction to mark
1058 /// beginning and end of a scope respectively. Create an inverse map that list
1059 /// scopes starts (and ends) with an instruction. One instruction may start (or
1060 /// end) multiple scopes. Ignore scopes that are not reachable.
1061 void DwarfDebug::identifyScopeMarkers() {
1062 SmallVector<LexicalScope *, 4> WorkList;
1063 WorkList.push_back(LScopes.getCurrentFunctionScope());
1064 while (!WorkList.empty()) {
1065 LexicalScope *S = WorkList.pop_back_val();
1067 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1068 if (!Children.empty())
1069 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1070 SE = Children.end(); SI != SE; ++SI)
1071 WorkList.push_back(*SI);
1073 if (S->isAbstractScope())
1076 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1079 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1080 RE = Ranges.end(); RI != RE; ++RI) {
1081 assert(RI->first && "InsnRange does not have first instruction!");
1082 assert(RI->second && "InsnRange does not have second instruction!");
1083 requestLabelBeforeInsn(RI->first);
1084 requestLabelAfterInsn(RI->second);
1089 /// getScopeNode - Get MDNode for DebugLoc's scope.
1090 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1091 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1092 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1093 return DL.getScope(Ctx);
1096 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1097 /// line number info for the function.
1098 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1099 const MDNode *Scope = getScopeNode(DL, Ctx);
1100 DISubprogram SP = getDISubprogram(Scope);
1102 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1106 /// beginFunction - Gather pre-function debug information. Assumes being
1107 /// emitted immediately after the function entry point.
1108 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1109 if (!MMI->hasDebugInfo()) return;
1110 LScopes.initialize(*MF);
1111 if (LScopes.empty()) return;
1112 identifyScopeMarkers();
1114 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1115 Asm->getFunctionNumber());
1116 // Assumes in correct section after the entry point.
1117 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1119 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1121 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1122 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1123 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1125 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1127 bool AtBlockEntry = true;
1128 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1130 const MachineInstr *MI = II;
1132 if (MI->isDebugValue()) {
1133 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1135 // Keep track of user variables.
1137 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1139 // Variable is in a register, we need to check for clobbers.
1140 if (isDbgValueInDefinedReg(MI))
1141 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1143 // Check the history of this variable.
1144 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1145 if (History.empty()) {
1146 UserVariables.push_back(Var);
1147 // The first mention of a function argument gets the FunctionBeginSym
1148 // label, so arguments are visible when breaking at function entry.
1150 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1151 DISubprogram(getDISubprogram(DV.getContext()))
1152 .describes(MF->getFunction()))
1153 LabelsBeforeInsn[MI] = FunctionBeginSym;
1155 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1156 const MachineInstr *Prev = History.back();
1157 if (Prev->isDebugValue()) {
1158 // Coalesce identical entries at the end of History.
1159 if (History.size() >= 2 &&
1160 Prev->isIdenticalTo(History[History.size() - 2])) {
1161 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1163 << "\t" << *History[History.size() - 2] << "\n");
1167 // Terminate old register assignments that don't reach MI;
1168 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1169 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1170 isDbgValueInDefinedReg(Prev)) {
1171 // Previous register assignment needs to terminate at the end of
1173 MachineBasicBlock::const_iterator LastMI =
1174 PrevMBB->getLastNonDebugInstr();
1175 if (LastMI == PrevMBB->end()) {
1176 // Drop DBG_VALUE for empty range.
1177 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1178 << "\t" << *Prev << "\n");
1182 // Terminate after LastMI.
1183 History.push_back(LastMI);
1188 History.push_back(MI);
1190 // Not a DBG_VALUE instruction.
1192 AtBlockEntry = false;
1194 // First known non DBG_VALUE location marks beginning of function
1196 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1197 PrologEndLoc = MI->getDebugLoc();
1199 // Check if the instruction clobbers any registers with debug vars.
1200 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1201 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1202 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1204 for (const unsigned *AI = TRI->getOverlaps(MOI->getReg());
1205 unsigned Reg = *AI; ++AI) {
1206 const MDNode *Var = LiveUserVar[Reg];
1209 // Reg is now clobbered.
1210 LiveUserVar[Reg] = 0;
1212 // Was MD last defined by a DBG_VALUE referring to Reg?
1213 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1214 if (HistI == DbgValues.end())
1216 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1217 if (History.empty())
1219 const MachineInstr *Prev = History.back();
1220 // Sanity-check: Register assignments are terminated at the end of
1222 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1224 // Is the variable still in Reg?
1225 if (!isDbgValueInDefinedReg(Prev) ||
1226 Prev->getOperand(0).getReg() != Reg)
1228 // Var is clobbered. Make sure the next instruction gets a label.
1229 History.push_back(MI);
1236 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1238 SmallVectorImpl<const MachineInstr*> &History = I->second;
1239 if (History.empty())
1242 // Make sure the final register assignments are terminated.
1243 const MachineInstr *Prev = History.back();
1244 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1245 const MachineBasicBlock *PrevMBB = Prev->getParent();
1246 MachineBasicBlock::const_iterator LastMI =
1247 PrevMBB->getLastNonDebugInstr();
1248 if (LastMI == PrevMBB->end())
1249 // Drop DBG_VALUE for empty range.
1252 // Terminate after LastMI.
1253 History.push_back(LastMI);
1256 // Request labels for the full history.
1257 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1258 const MachineInstr *MI = History[i];
1259 if (MI->isDebugValue())
1260 requestLabelBeforeInsn(MI);
1262 requestLabelAfterInsn(MI);
1266 PrevInstLoc = DebugLoc();
1267 PrevLabel = FunctionBeginSym;
1269 // Record beginning of function.
1270 if (!PrologEndLoc.isUnknown()) {
1271 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1272 MF->getFunction()->getContext());
1273 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1274 FnStartDL.getScope(MF->getFunction()->getContext()),
1275 DWARF2_FLAG_IS_STMT);
1279 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1280 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1281 ScopeVariables[LS].push_back(Var);
1282 // Vars.push_back(Var);
1285 /// endFunction - Gather and emit post-function debug information.
1287 void DwarfDebug::endFunction(const MachineFunction *MF) {
1288 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1290 // Define end label for subprogram.
1291 FunctionEndSym = Asm->GetTempSymbol("func_end",
1292 Asm->getFunctionNumber());
1293 // Assumes in correct section after the entry point.
1294 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1296 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1297 collectVariableInfo(MF, ProcessedVars);
1299 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1300 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1301 assert(TheCU && "Unable to find compile unit!");
1303 // Construct abstract scopes.
1304 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1305 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1306 LexicalScope *AScope = AList[i];
1307 DISubprogram SP(AScope->getScopeNode());
1309 // Collect info for variables that were optimized out.
1310 DIArray Variables = SP.getVariables();
1311 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1312 DIVariable DV(Variables.getElement(i));
1313 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1315 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1316 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1319 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1320 constructScopeDIE(TheCU, AScope);
1323 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1325 if (!DisableFramePointerElim(*MF))
1326 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1327 dwarf::DW_FORM_flag, 1);
1329 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1330 MMI->getFrameMoves()));
1333 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1334 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1335 DeleteContainerPointers(I->second);
1336 ScopeVariables.clear();
1337 DeleteContainerPointers(CurrentFnArguments);
1338 UserVariables.clear();
1340 AbstractVariables.clear();
1341 LabelsBeforeInsn.clear();
1342 LabelsAfterInsn.clear();
1346 /// recordSourceLine - Register a source line with debug info. Returns the
1347 /// unique label that was emitted and which provides correspondence to
1348 /// the source line list.
1349 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1355 DIDescriptor Scope(S);
1357 if (Scope.isCompileUnit()) {
1358 DICompileUnit CU(S);
1359 Fn = CU.getFilename();
1360 Dir = CU.getDirectory();
1361 } else if (Scope.isFile()) {
1363 Fn = F.getFilename();
1364 Dir = F.getDirectory();
1365 } else if (Scope.isSubprogram()) {
1367 Fn = SP.getFilename();
1368 Dir = SP.getDirectory();
1369 } else if (Scope.isLexicalBlockFile()) {
1370 DILexicalBlockFile DBF(S);
1371 Fn = DBF.getFilename();
1372 Dir = DBF.getDirectory();
1373 } else if (Scope.isLexicalBlock()) {
1374 DILexicalBlock DB(S);
1375 Fn = DB.getFilename();
1376 Dir = DB.getDirectory();
1378 assert(0 && "Unexpected scope info");
1380 Src = GetOrCreateSourceID(Fn, Dir);
1382 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1385 //===----------------------------------------------------------------------===//
1387 //===----------------------------------------------------------------------===//
1389 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1392 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1393 // Get the children.
1394 const std::vector<DIE *> &Children = Die->getChildren();
1396 // If not last sibling and has children then add sibling offset attribute.
1397 if (!Last && !Children.empty())
1398 Die->addSiblingOffset(DIEValueAllocator);
1400 // Record the abbreviation.
1401 assignAbbrevNumber(Die->getAbbrev());
1403 // Get the abbreviation for this DIE.
1404 unsigned AbbrevNumber = Die->getAbbrevNumber();
1405 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1408 Die->setOffset(Offset);
1410 // Start the size with the size of abbreviation code.
1411 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1413 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1414 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1416 // Size the DIE attribute values.
1417 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1418 // Size attribute value.
1419 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1421 // Size the DIE children if any.
1422 if (!Children.empty()) {
1423 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1424 "Children flag not set");
1426 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1427 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1429 // End of children marker.
1430 Offset += sizeof(int8_t);
1433 Die->setSize(Offset - Die->getOffset());
1437 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1439 void DwarfDebug::computeSizeAndOffsets() {
1440 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1441 E = CUMap.end(); I != E; ++I) {
1442 // Compute size of compile unit header.
1444 sizeof(int32_t) + // Length of Compilation Unit Info
1445 sizeof(int16_t) + // DWARF version number
1446 sizeof(int32_t) + // Offset Into Abbrev. Section
1447 sizeof(int8_t); // Pointer Size (in bytes)
1448 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1452 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
1453 /// temporary label to it if SymbolStem is specified.
1454 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
1455 const char *SymbolStem = 0) {
1456 Asm->OutStreamer.SwitchSection(Section);
1457 if (!SymbolStem) return 0;
1459 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
1460 Asm->OutStreamer.EmitLabel(TmpSym);
1464 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1465 /// the start of each one.
1466 void DwarfDebug::EmitSectionLabels() {
1467 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1469 // Dwarf sections base addresses.
1470 DwarfInfoSectionSym =
1471 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1472 DwarfAbbrevSectionSym =
1473 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1474 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1476 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1477 EmitSectionSym(Asm, MacroInfo);
1479 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1480 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1481 EmitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1482 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1483 DwarfStrSectionSym =
1484 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1485 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1488 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1489 "section_debug_loc");
1491 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1492 EmitSectionSym(Asm, TLOF.getDataSection());
1495 /// emitDIE - Recursively emits a debug information entry.
1497 void DwarfDebug::emitDIE(DIE *Die) {
1498 // Get the abbreviation for this DIE.
1499 unsigned AbbrevNumber = Die->getAbbrevNumber();
1500 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1502 // Emit the code (index) for the abbreviation.
1503 if (Asm->isVerbose())
1504 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1505 Twine::utohexstr(Die->getOffset()) + ":0x" +
1506 Twine::utohexstr(Die->getSize()) + " " +
1507 dwarf::TagString(Abbrev->getTag()));
1508 Asm->EmitULEB128(AbbrevNumber);
1510 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1511 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1513 // Emit the DIE attribute values.
1514 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1515 unsigned Attr = AbbrevData[i].getAttribute();
1516 unsigned Form = AbbrevData[i].getForm();
1517 assert(Form && "Too many attributes for DIE (check abbreviation)");
1519 if (Asm->isVerbose())
1520 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1523 case dwarf::DW_AT_sibling:
1524 Asm->EmitInt32(Die->getSiblingOffset());
1526 case dwarf::DW_AT_abstract_origin: {
1527 DIEEntry *E = cast<DIEEntry>(Values[i]);
1528 DIE *Origin = E->getEntry();
1529 unsigned Addr = Origin->getOffset();
1530 Asm->EmitInt32(Addr);
1533 case dwarf::DW_AT_ranges: {
1534 // DW_AT_range Value encodes offset in debug_range section.
1535 DIEInteger *V = cast<DIEInteger>(Values[i]);
1537 if (Asm->MAI->doesDwarfUsesLabelOffsetForRanges()) {
1538 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1542 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1544 DwarfDebugRangeSectionSym,
1549 case dwarf::DW_AT_location: {
1550 if (DIELabel *L = dyn_cast<DIELabel>(Values[i]))
1551 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1553 Values[i]->EmitValue(Asm, Form);
1556 case dwarf::DW_AT_accessibility: {
1557 if (Asm->isVerbose()) {
1558 DIEInteger *V = cast<DIEInteger>(Values[i]);
1559 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1561 Values[i]->EmitValue(Asm, Form);
1565 // Emit an attribute using the defined form.
1566 Values[i]->EmitValue(Asm, Form);
1571 // Emit the DIE children if any.
1572 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1573 const std::vector<DIE *> &Children = Die->getChildren();
1575 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1576 emitDIE(Children[j]);
1578 if (Asm->isVerbose())
1579 Asm->OutStreamer.AddComment("End Of Children Mark");
1584 /// emitDebugInfo - Emit the debug info section.
1586 void DwarfDebug::emitDebugInfo() {
1587 // Start debug info section.
1588 Asm->OutStreamer.SwitchSection(
1589 Asm->getObjFileLowering().getDwarfInfoSection());
1590 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1591 E = CUMap.end(); I != E; ++I) {
1592 CompileUnit *TheCU = I->second;
1593 DIE *Die = TheCU->getCUDie();
1595 // Emit the compile units header.
1596 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1599 // Emit size of content not including length itself
1600 unsigned ContentSize = Die->getSize() +
1601 sizeof(int16_t) + // DWARF version number
1602 sizeof(int32_t) + // Offset Into Abbrev. Section
1603 sizeof(int8_t); // Pointer Size (in bytes)
1605 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1606 Asm->EmitInt32(ContentSize);
1607 Asm->OutStreamer.AddComment("DWARF version number");
1608 Asm->EmitInt16(dwarf::DWARF_VERSION);
1609 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1610 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1611 DwarfAbbrevSectionSym);
1612 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1613 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1616 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1620 /// emitAbbreviations - Emit the abbreviation section.
1622 void DwarfDebug::emitAbbreviations() const {
1623 // Check to see if it is worth the effort.
1624 if (!Abbreviations.empty()) {
1625 // Start the debug abbrev section.
1626 Asm->OutStreamer.SwitchSection(
1627 Asm->getObjFileLowering().getDwarfAbbrevSection());
1629 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1631 // For each abbrevation.
1632 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1633 // Get abbreviation data
1634 const DIEAbbrev *Abbrev = Abbreviations[i];
1636 // Emit the abbrevations code (base 1 index.)
1637 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1639 // Emit the abbreviations data.
1643 // Mark end of abbreviations.
1644 Asm->EmitULEB128(0, "EOM(3)");
1646 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1650 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1651 /// the line matrix.
1653 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1654 // Define last address of section.
1655 Asm->OutStreamer.AddComment("Extended Op");
1658 Asm->OutStreamer.AddComment("Op size");
1659 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1660 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1661 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1663 Asm->OutStreamer.AddComment("Section end label");
1665 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1666 Asm->getTargetData().getPointerSize(),
1669 // Mark end of matrix.
1670 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1676 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1678 void DwarfDebug::emitDebugPubNames() {
1679 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1680 E = CUMap.end(); I != E; ++I) {
1681 CompileUnit *TheCU = I->second;
1682 // Start the dwarf pubnames section.
1683 Asm->OutStreamer.SwitchSection(
1684 Asm->getObjFileLowering().getDwarfPubNamesSection());
1686 Asm->OutStreamer.AddComment("Length of Public Names Info");
1687 Asm->EmitLabelDifference(
1688 Asm->GetTempSymbol("pubnames_end", TheCU->getID()),
1689 Asm->GetTempSymbol("pubnames_begin", TheCU->getID()), 4);
1691 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin",
1694 Asm->OutStreamer.AddComment("DWARF Version");
1695 Asm->EmitInt16(dwarf::DWARF_VERSION);
1697 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1698 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1699 DwarfInfoSectionSym);
1701 Asm->OutStreamer.AddComment("Compilation Unit Length");
1702 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1703 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1706 const StringMap<DIE*> &Globals = TheCU->getGlobals();
1707 for (StringMap<DIE*>::const_iterator
1708 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1709 const char *Name = GI->getKeyData();
1710 DIE *Entity = GI->second;
1712 Asm->OutStreamer.AddComment("DIE offset");
1713 Asm->EmitInt32(Entity->getOffset());
1715 if (Asm->isVerbose())
1716 Asm->OutStreamer.AddComment("External Name");
1717 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
1720 Asm->OutStreamer.AddComment("End Mark");
1722 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end",
1727 void DwarfDebug::emitDebugPubTypes() {
1728 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1729 E = CUMap.end(); I != E; ++I) {
1730 CompileUnit *TheCU = I->second;
1731 // Start the dwarf pubnames section.
1732 Asm->OutStreamer.SwitchSection(
1733 Asm->getObjFileLowering().getDwarfPubTypesSection());
1734 Asm->OutStreamer.AddComment("Length of Public Types Info");
1735 Asm->EmitLabelDifference(
1736 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1737 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1739 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1742 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1743 Asm->EmitInt16(dwarf::DWARF_VERSION);
1745 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1746 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1747 DwarfInfoSectionSym);
1749 Asm->OutStreamer.AddComment("Compilation Unit Length");
1750 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1751 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1754 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1755 for (StringMap<DIE*>::const_iterator
1756 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1757 const char *Name = GI->getKeyData();
1758 DIE *Entity = GI->second;
1760 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1761 Asm->EmitInt32(Entity->getOffset());
1763 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1764 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1767 Asm->OutStreamer.AddComment("End Mark");
1769 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1774 /// emitDebugStr - Emit visible names into a debug str section.
1776 void DwarfDebug::emitDebugStr() {
1777 // Check to see if it is worth the effort.
1778 if (StringPool.empty()) return;
1780 // Start the dwarf str section.
1781 Asm->OutStreamer.SwitchSection(
1782 Asm->getObjFileLowering().getDwarfStrSection());
1784 // Get all of the string pool entries and put them in an array by their ID so
1785 // we can sort them.
1786 SmallVector<std::pair<unsigned,
1787 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1789 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1790 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1791 Entries.push_back(std::make_pair(I->second.second, &*I));
1793 array_pod_sort(Entries.begin(), Entries.end());
1795 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1796 // Emit a label for reference from debug information entries.
1797 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1799 // Emit the string itself.
1800 Asm->OutStreamer.EmitBytes(Entries[i].second->getKey(), 0/*addrspace*/);
1801 Asm->OutStreamer.EmitZeros(1, 0);
1805 /// emitDebugLoc - Emit visible names into a debug loc section.
1807 void DwarfDebug::emitDebugLoc() {
1808 if (DotDebugLocEntries.empty())
1811 for (SmallVector<DotDebugLocEntry, 4>::iterator
1812 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1814 DotDebugLocEntry &Entry = *I;
1815 if (I + 1 != DotDebugLocEntries.end())
1819 // Start the dwarf loc section.
1820 Asm->OutStreamer.SwitchSection(
1821 Asm->getObjFileLowering().getDwarfLocSection());
1822 unsigned char Size = Asm->getTargetData().getPointerSize();
1823 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
1825 for (SmallVector<DotDebugLocEntry, 4>::iterator
1826 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
1827 I != E; ++I, ++index) {
1828 DotDebugLocEntry &Entry = *I;
1829 if (Entry.isMerged()) continue;
1830 if (Entry.isEmpty()) {
1831 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1832 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1833 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
1835 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
1836 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
1837 DIVariable DV(Entry.Variable);
1838 Asm->OutStreamer.AddComment("Loc expr size");
1839 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1840 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1841 Asm->EmitLabelDifference(end, begin, 2);
1842 Asm->OutStreamer.EmitLabel(begin);
1843 if (Entry.isInt()) {
1844 DIBasicType BTy(DV.getType());
1846 (BTy.getEncoding() == dwarf::DW_ATE_signed
1847 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
1848 Asm->OutStreamer.AddComment("DW_OP_consts");
1849 Asm->EmitInt8(dwarf::DW_OP_consts);
1850 Asm->EmitSLEB128(Entry.getInt());
1852 Asm->OutStreamer.AddComment("DW_OP_constu");
1853 Asm->EmitInt8(dwarf::DW_OP_constu);
1854 Asm->EmitULEB128(Entry.getInt());
1856 } else if (Entry.isLocation()) {
1857 if (!DV.hasComplexAddress())
1859 Asm->EmitDwarfRegOp(Entry.Loc);
1861 // Complex address entry.
1862 unsigned N = DV.getNumAddrElements();
1864 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
1865 if (Entry.Loc.getOffset()) {
1867 Asm->EmitDwarfRegOp(Entry.Loc);
1868 Asm->OutStreamer.AddComment("DW_OP_deref");
1869 Asm->EmitInt8(dwarf::DW_OP_deref);
1870 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
1871 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1872 Asm->EmitSLEB128(DV.getAddrElement(1));
1874 // If first address element is OpPlus then emit
1875 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1876 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
1877 Asm->EmitDwarfRegOp(Loc);
1881 Asm->EmitDwarfRegOp(Entry.Loc);
1884 // Emit remaining complex address elements.
1885 for (; i < N; ++i) {
1886 uint64_t Element = DV.getAddrElement(i);
1887 if (Element == DIBuilder::OpPlus) {
1888 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
1889 Asm->EmitULEB128(DV.getAddrElement(++i));
1890 } else if (Element == DIBuilder::OpDeref)
1891 Asm->EmitInt8(dwarf::DW_OP_deref);
1892 else llvm_unreachable("unknown Opcode found in complex address");
1896 // else ... ignore constant fp. There is not any good way to
1897 // to represent them here in dwarf.
1898 Asm->OutStreamer.EmitLabel(end);
1903 /// EmitDebugARanges - Emit visible names into a debug aranges section.
1905 void DwarfDebug::EmitDebugARanges() {
1906 // Start the dwarf aranges section.
1907 Asm->OutStreamer.SwitchSection(
1908 Asm->getObjFileLowering().getDwarfARangesSection());
1911 /// emitDebugRanges - Emit visible names into a debug ranges section.
1913 void DwarfDebug::emitDebugRanges() {
1914 // Start the dwarf ranges section.
1915 Asm->OutStreamer.SwitchSection(
1916 Asm->getObjFileLowering().getDwarfRangesSection());
1917 unsigned char Size = Asm->getTargetData().getPointerSize();
1918 for (SmallVector<const MCSymbol *, 8>::iterator
1919 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
1922 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
1924 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
1928 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
1930 void DwarfDebug::emitDebugMacInfo() {
1931 if (const MCSection *LineInfo =
1932 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
1933 // Start the dwarf macinfo section.
1934 Asm->OutStreamer.SwitchSection(LineInfo);
1938 /// emitDebugInlineInfo - Emit inline info using following format.
1940 /// 1. length of section
1941 /// 2. Dwarf version number
1942 /// 3. address size.
1944 /// Entries (one "entry" for each function that was inlined):
1946 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
1947 /// otherwise offset into __debug_str for regular function name.
1948 /// 2. offset into __debug_str section for regular function name.
1949 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
1950 /// instances for the function.
1952 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
1953 /// inlined instance; the die_offset points to the inlined_subroutine die in the
1954 /// __debug_info section, and the low_pc is the starting address for the
1955 /// inlining instance.
1956 void DwarfDebug::emitDebugInlineInfo() {
1957 if (!Asm->MAI->doesDwarfUsesInlineInfoSection())
1963 Asm->OutStreamer.SwitchSection(
1964 Asm->getObjFileLowering().getDwarfDebugInlineSection());
1966 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
1967 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
1968 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
1970 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
1972 Asm->OutStreamer.AddComment("Dwarf Version");
1973 Asm->EmitInt16(dwarf::DWARF_VERSION);
1974 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1975 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1977 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
1978 E = InlinedSPNodes.end(); I != E; ++I) {
1980 const MDNode *Node = *I;
1981 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
1982 = InlineInfo.find(Node);
1983 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
1984 DISubprogram SP(Node);
1985 StringRef LName = SP.getLinkageName();
1986 StringRef Name = SP.getName();
1988 Asm->OutStreamer.AddComment("MIPS linkage name");
1989 if (LName.empty()) {
1990 Asm->OutStreamer.EmitBytes(Name, 0);
1991 Asm->OutStreamer.EmitIntValue(0, 1, 0); // nul terminator.
1993 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
1994 DwarfStrSectionSym);
1996 Asm->OutStreamer.AddComment("Function name");
1997 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
1998 Asm->EmitULEB128(Labels.size(), "Inline count");
2000 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2001 LE = Labels.end(); LI != LE; ++LI) {
2002 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2003 Asm->EmitInt32(LI->second->getOffset());
2005 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2006 Asm->OutStreamer.EmitSymbolValue(LI->first,
2007 Asm->getTargetData().getPointerSize(),0);
2011 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));