1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for writing dwarf debug info into asm files.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "DwarfDebug.h"
17 #include "DwarfAccelTable.h"
18 #include "DwarfCompileUnit.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DebugInfo.h"
21 #include "llvm/DIBuilder.h"
22 #include "llvm/Module.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCSection.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetFrameLowering.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Timer.h"
46 #include "llvm/Support/Path.h"
49 static cl::opt<bool> DisableDebugInfoPrinting("disable-debug-info-print",
51 cl::desc("Disable debug info printing"));
53 static cl::opt<bool> UnknownLocations("use-unknown-locations", cl::Hidden,
54 cl::desc("Make an absence of debug location information explicit."),
59 Default, Enable, Disable
63 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
64 cl::desc("Output prototype dwarf accelerator tables."),
66 clEnumVal(Default, "Default for platform"),
67 clEnumVal(Enable, "Enabled"),
68 clEnumVal(Disable, "Disabled"),
72 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
73 cl::desc("Compatibility with Darwin gdb."),
75 clEnumVal(Default, "Default for platform"),
76 clEnumVal(Enable, "Enabled"),
77 clEnumVal(Disable, "Disabled"),
82 const char *DWARFGroupName = "DWARF Emission";
83 const char *DbgTimerName = "DWARF Debug Writer";
84 } // end anonymous namespace
86 //===----------------------------------------------------------------------===//
88 /// Configuration values for initial hash set sizes (log2).
90 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
94 DIType DbgVariable::getType() const {
95 DIType Ty = Var.getType();
96 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
98 if (Var.isBlockByrefVariable()) {
99 /* Byref variables, in Blocks, are declared by the programmer as
100 "SomeType VarName;", but the compiler creates a
101 __Block_byref_x_VarName struct, and gives the variable VarName
102 either the struct, or a pointer to the struct, as its type. This
103 is necessary for various behind-the-scenes things the compiler
104 needs to do with by-reference variables in blocks.
106 However, as far as the original *programmer* is concerned, the
107 variable should still have type 'SomeType', as originally declared.
109 The following function dives into the __Block_byref_x_VarName
110 struct to find the original type of the variable. This will be
111 passed back to the code generating the type for the Debug
112 Information Entry for the variable 'VarName'. 'VarName' will then
113 have the original type 'SomeType' in its debug information.
115 The original type 'SomeType' will be the type of the field named
116 'VarName' inside the __Block_byref_x_VarName struct.
118 NOTE: In order for this to not completely fail on the debugger
119 side, the Debug Information Entry for the variable VarName needs to
120 have a DW_AT_location that tells the debugger how to unwind through
121 the pointers and __Block_byref_x_VarName struct to find the actual
122 value of the variable. The function addBlockByrefType does this. */
124 unsigned tag = Ty.getTag();
126 if (tag == dwarf::DW_TAG_pointer_type) {
127 DIDerivedType DTy = DIDerivedType(Ty);
128 subType = DTy.getTypeDerivedFrom();
131 DICompositeType blockStruct = DICompositeType(subType);
132 DIArray Elements = blockStruct.getTypeArray();
134 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
135 DIDescriptor Element = Elements.getElement(i);
136 DIDerivedType DT = DIDerivedType(Element);
137 if (getName() == DT.getName())
138 return (DT.getTypeDerivedFrom());
144 } // end llvm namespace
146 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
147 : Asm(A), MMI(Asm->MMI), FirstCU(0),
148 AbbreviationsSet(InitAbbreviationsSetSize),
149 SourceIdMap(DIEValueAllocator), StringPool(DIEValueAllocator),
151 NextStringPoolNumber = 0;
153 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
154 DwarfStrSectionSym = TextSectionSym = 0;
155 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
156 FunctionBeginSym = FunctionEndSym = 0;
158 // Turn on accelerator tables and older gdb compatibility
160 bool isDarwin = Triple(M->getTargetTriple()).isOSDarwin();
161 if (DarwinGDBCompat == Default) {
163 isDarwinGDBCompat = true;
165 isDarwinGDBCompat = false;
167 isDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
169 if (DwarfAccelTables == Default) {
171 hasDwarfAccelTables = true;
173 hasDwarfAccelTables = false;
175 hasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
178 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
182 DwarfDebug::~DwarfDebug() {
185 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
186 /// temporary label to it if SymbolStem is specified.
187 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
188 const char *SymbolStem = 0) {
189 Asm->OutStreamer.SwitchSection(Section);
190 if (!SymbolStem) return 0;
192 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
193 Asm->OutStreamer.EmitLabel(TmpSym);
197 MCSymbol *DwarfDebug::getStringPool() {
198 return Asm->GetTempSymbol("section_str");
201 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
202 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
203 if (Entry.first) return Entry.first;
205 Entry.second = NextStringPoolNumber++;
206 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
209 /// assignAbbrevNumber - Define a unique number for the abbreviation.
211 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
212 // Profile the node so that we can make it unique.
216 // Check the set for priors.
217 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
219 // If it's newly added.
220 if (InSet == &Abbrev) {
221 // Add to abbreviation list.
222 Abbreviations.push_back(&Abbrev);
224 // Assign the vector position + 1 as its number.
225 Abbrev.setNumber(Abbreviations.size());
227 // Assign existing abbreviation number.
228 Abbrev.setNumber(InSet->getNumber());
232 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
233 /// printer to not emit usual symbol prefix before the symbol name is used then
234 /// return linkage name after skipping this special LLVM prefix.
235 static StringRef getRealLinkageName(StringRef LinkageName) {
237 if (LinkageName.startswith(StringRef(&One, 1)))
238 return LinkageName.substr(1);
242 static bool isObjCClass(StringRef Name) {
243 return Name.startswith("+") || Name.startswith("-");
246 static bool hasObjCCategory(StringRef Name) {
247 if (!isObjCClass(Name)) return false;
249 size_t pos = Name.find(')');
250 if (pos != std::string::npos) {
251 if (Name[pos+1] != ' ') return false;
257 static void getObjCClassCategory(StringRef In, StringRef &Class,
258 StringRef &Category) {
259 if (!hasObjCCategory(In)) {
260 Class = In.slice(In.find('[') + 1, In.find(' '));
265 Class = In.slice(In.find('[') + 1, In.find('('));
266 Category = In.slice(In.find('[') + 1, In.find(' '));
270 static StringRef getObjCMethodName(StringRef In) {
271 return In.slice(In.find(' ') + 1, In.find(']'));
274 // Add the various names to the Dwarf accelerator table names.
275 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
277 if (!SP.isDefinition()) return;
279 TheCU->addAccelName(SP.getName(), Die);
281 // If the linkage name is different than the name, go ahead and output
282 // that as well into the name table.
283 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
284 TheCU->addAccelName(SP.getLinkageName(), Die);
286 // If this is an Objective-C selector name add it to the ObjC accelerator
288 if (isObjCClass(SP.getName())) {
289 StringRef Class, Category;
290 getObjCClassCategory(SP.getName(), Class, Category);
291 TheCU->addAccelObjC(Class, Die);
293 TheCU->addAccelObjC(Category, Die);
294 // Also add the base method name to the name table.
295 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
299 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
300 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
301 /// If there are global variables in this scope then create and insert
302 /// DIEs for these variables.
303 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
304 const MDNode *SPNode) {
305 DIE *SPDie = SPCU->getDIE(SPNode);
307 assert(SPDie && "Unable to find subprogram DIE!");
308 DISubprogram SP(SPNode);
310 DISubprogram SPDecl = SP.getFunctionDeclaration();
311 if (!SPDecl.isSubprogram()) {
312 // There is not any need to generate specification DIE for a function
313 // defined at compile unit level. If a function is defined inside another
314 // function then gdb prefers the definition at top level and but does not
315 // expect specification DIE in parent function. So avoid creating
316 // specification DIE for a function defined inside a function.
317 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
318 !SP.getContext().isFile() &&
319 !isSubprogramContext(SP.getContext())) {
320 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
323 DICompositeType SPTy = SP.getType();
324 DIArray Args = SPTy.getTypeArray();
325 unsigned SPTag = SPTy.getTag();
326 if (SPTag == dwarf::DW_TAG_subroutine_type)
327 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
328 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
329 DIType ATy = DIType(Args.getElement(i));
330 SPCU->addType(Arg, ATy);
331 if (ATy.isArtificial())
332 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
333 if (ATy.isObjectPointer())
334 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer, dwarf::DW_FORM_ref4,
336 SPDie->addChild(Arg);
338 DIE *SPDeclDie = SPDie;
339 SPDie = new DIE(dwarf::DW_TAG_subprogram);
340 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
345 // Pick up abstract subprogram DIE.
346 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
347 SPDie = new DIE(dwarf::DW_TAG_subprogram);
348 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
349 dwarf::DW_FORM_ref4, AbsSPDIE);
353 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
354 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
355 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
356 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
357 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
358 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
359 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
361 // Add name to the name table, we do this here because we're guaranteed
362 // to have concrete versions of our DW_TAG_subprogram nodes.
363 addSubprogramNames(SPCU, SP, SPDie);
368 /// constructLexicalScope - Construct new DW_TAG_lexical_block
369 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
370 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
371 LexicalScope *Scope) {
372 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
373 if (Scope->isAbstractScope())
376 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
380 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
381 if (Ranges.size() > 1) {
382 // .debug_range section has not been laid out yet. Emit offset in
383 // .debug_range as a uint, size 4, for now. emitDIE will handle
384 // DW_AT_ranges appropriately.
385 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
386 DebugRangeSymbols.size()
387 * Asm->getTargetData().getPointerSize());
388 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
389 RE = Ranges.end(); RI != RE; ++RI) {
390 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
391 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
393 DebugRangeSymbols.push_back(NULL);
394 DebugRangeSymbols.push_back(NULL);
398 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
399 const MCSymbol *End = getLabelAfterInsn(RI->second);
401 if (End == 0) return 0;
403 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
404 assert(End->isDefined() && "Invalid end label for an inlined scope!");
406 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
407 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
412 /// constructInlinedScopeDIE - This scope represents inlined body of
413 /// a function. Construct DIE to represent this concrete inlined copy
415 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
416 LexicalScope *Scope) {
417 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
418 assert(Ranges.empty() == false &&
419 "LexicalScope does not have instruction markers!");
421 if (!Scope->getScopeNode())
423 DIScope DS(Scope->getScopeNode());
424 DISubprogram InlinedSP = getDISubprogram(DS);
425 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
427 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
431 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
432 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
433 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
435 if (StartLabel == 0 || EndLabel == 0) {
436 llvm_unreachable("Unexpected Start and End labels for a inlined scope!");
438 assert(StartLabel->isDefined() &&
439 "Invalid starting label for an inlined scope!");
440 assert(EndLabel->isDefined() &&
441 "Invalid end label for an inlined scope!");
443 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
444 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
445 dwarf::DW_FORM_ref4, OriginDIE);
447 if (Ranges.size() > 1) {
448 // .debug_range section has not been laid out yet. Emit offset in
449 // .debug_range as a uint, size 4, for now. emitDIE will handle
450 // DW_AT_ranges appropriately.
451 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
452 DebugRangeSymbols.size()
453 * Asm->getTargetData().getPointerSize());
454 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
455 RE = Ranges.end(); RI != RE; ++RI) {
456 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
457 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
459 DebugRangeSymbols.push_back(NULL);
460 DebugRangeSymbols.push_back(NULL);
462 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
464 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
468 InlinedSubprogramDIEs.insert(OriginDIE);
470 // Track the start label for this inlined function.
471 //.debug_inlined section specification does not clearly state how
472 // to emit inlined scope that is split into multiple instruction ranges.
473 // For now, use first instruction range and emit low_pc/high_pc pair and
474 // corresponding .debug_inlined section entry for this pair.
475 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
476 I = InlineInfo.find(InlinedSP);
478 if (I == InlineInfo.end()) {
479 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
480 InlinedSPNodes.push_back(InlinedSP);
482 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
484 DILocation DL(Scope->getInlinedAt());
485 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
486 GetOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
487 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
489 // Add name to the name table, we do this here because we're guaranteed
490 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
491 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
496 /// constructScopeDIE - Construct a DIE for this scope.
497 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
498 if (!Scope || !Scope->getScopeNode())
501 SmallVector<DIE *, 8> Children;
502 DIE *ObjectPointer = NULL;
504 // Collect arguments for current function.
505 if (LScopes.isCurrentFunctionScope(Scope))
506 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
507 if (DbgVariable *ArgDV = CurrentFnArguments[i])
509 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
510 Children.push_back(Arg);
511 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
514 // Collect lexical scope children first.
515 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
516 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
518 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
519 Children.push_back(Variable);
520 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
521 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
522 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
523 Children.push_back(Nested);
524 DIScope DS(Scope->getScopeNode());
525 DIE *ScopeDIE = NULL;
526 if (Scope->getInlinedAt())
527 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
528 else if (DS.isSubprogram()) {
529 ProcessedSPNodes.insert(DS);
530 if (Scope->isAbstractScope()) {
531 ScopeDIE = TheCU->getDIE(DS);
532 // Note down abstract DIE.
534 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
537 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
540 // There is no need to emit empty lexical block DIE.
541 if (Children.empty())
543 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
546 if (!ScopeDIE) return NULL;
549 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
550 E = Children.end(); I != E; ++I)
551 ScopeDIE->addChild(*I);
553 if (DS.isSubprogram() && ObjectPointer != NULL)
554 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
555 dwarf::DW_FORM_ref4, ObjectPointer);
557 if (DS.isSubprogram())
558 TheCU->addPubTypes(DISubprogram(DS));
563 /// GetOrCreateSourceID - Look up the source id with the given directory and
564 /// source file names. If none currently exists, create a new id and insert it
565 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
567 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
569 // If FE did not provide a file name, then assume stdin.
570 if (FileName.empty())
571 return GetOrCreateSourceID("<stdin>", StringRef());
573 // TODO: this might not belong here. See if we can factor this better.
574 if (DirName == CompilationDir)
577 unsigned SrcId = SourceIdMap.size()+1;
579 // We look up the file/dir pair by concatenating them with a zero byte.
580 SmallString<128> NamePair;
582 NamePair += '\0'; // Zero bytes are not allowed in paths.
583 NamePair += FileName;
585 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
586 if (Ent.getValue() != SrcId)
587 return Ent.getValue();
589 // Print out a .file directive to specify files for .loc directives.
590 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
595 /// constructCompileUnit - Create new CompileUnit for the given
596 /// metadata node with tag DW_TAG_compile_unit.
597 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
598 DICompileUnit DIUnit(N);
599 StringRef FN = DIUnit.getFilename();
600 CompilationDir = DIUnit.getDirectory();
601 unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
603 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
604 CompileUnit *NewCU = new CompileUnit(ID, DIUnit.getLanguage(), Die,
606 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
607 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
608 DIUnit.getLanguage());
609 NewCU->addString(Die, dwarf::DW_AT_name, FN);
610 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
612 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
613 // DW_AT_stmt_list is a offset of line number information for this
614 // compile unit in debug_line section.
615 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
616 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
617 Asm->GetTempSymbol("section_line"));
619 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
621 if (!CompilationDir.empty())
622 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
623 if (DIUnit.isOptimized())
624 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
626 StringRef Flags = DIUnit.getFlags();
628 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
630 if (unsigned RVer = DIUnit.getRunTimeVersion())
631 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
632 dwarf::DW_FORM_data1, RVer);
636 CUMap.insert(std::make_pair(N, NewCU));
640 /// construct SubprogramDIE - Construct subprogram DIE.
641 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
643 CompileUnit *&CURef = SPMap[N];
649 if (!SP.isDefinition())
650 // This is a method declaration which will be handled while constructing
654 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
657 TheCU->insertDIE(N, SubprogramDie);
659 // Add to context owner.
660 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
665 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
666 /// as llvm.dbg.enum and llvm.dbg.ty
667 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
668 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
669 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
670 const MDNode *N = NMD->getOperand(i);
671 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
672 constructSubprogramDIE(CU, N);
675 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
676 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
677 const MDNode *N = NMD->getOperand(i);
678 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
679 CU->createGlobalVariableDIE(N);
682 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
683 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
684 DIType Ty(NMD->getOperand(i));
685 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
686 CU->getOrCreateTypeDIE(Ty);
689 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
690 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
691 DIType Ty(NMD->getOperand(i));
692 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
693 CU->getOrCreateTypeDIE(Ty);
697 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
698 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
699 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
700 DebugInfoFinder DbgFinder;
701 DbgFinder.processModule(*M);
703 bool HasDebugInfo = false;
704 // Scan all the compile-units to see if there are any marked as the main
705 // unit. If not, we do not generate debug info.
706 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
707 E = DbgFinder.compile_unit_end(); I != E; ++I) {
708 if (DICompileUnit(*I).isMain()) {
713 if (!HasDebugInfo) return false;
715 // Create all the compile unit DIEs.
716 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
717 E = DbgFinder.compile_unit_end(); I != E; ++I)
718 constructCompileUnit(*I);
720 // Create DIEs for each global variable.
721 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
722 E = DbgFinder.global_variable_end(); I != E; ++I) {
723 const MDNode *N = *I;
724 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
725 CU->createGlobalVariableDIE(N);
728 // Create DIEs for each subprogram.
729 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
730 E = DbgFinder.subprogram_end(); I != E; ++I) {
731 const MDNode *N = *I;
732 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
733 constructSubprogramDIE(CU, N);
739 /// beginModule - Emit all Dwarf sections that should come prior to the
740 /// content. Create global DIEs and emit initial debug info sections.
741 /// This is invoked by the target AsmPrinter.
742 void DwarfDebug::beginModule(Module *M) {
743 if (DisableDebugInfoPrinting)
746 // If module has named metadata anchors then use them, otherwise scan the
747 // module using debug info finder to collect debug info.
748 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
750 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
751 DICompileUnit CUNode(CU_Nodes->getOperand(i));
752 CompileUnit *CU = constructCompileUnit(CUNode);
753 DIArray GVs = CUNode.getGlobalVariables();
754 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
755 CU->createGlobalVariableDIE(GVs.getElement(i));
756 DIArray SPs = CUNode.getSubprograms();
757 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
758 constructSubprogramDIE(CU, SPs.getElement(i));
759 DIArray EnumTypes = CUNode.getEnumTypes();
760 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
761 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
762 DIArray RetainedTypes = CUNode.getRetainedTypes();
763 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
764 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
766 } else if (!collectLegacyDebugInfo(M))
769 collectInfoFromNamedMDNodes(M);
771 // Tell MMI that we have debug info.
772 MMI->setDebugInfoAvailability(true);
774 // Emit initial sections.
777 // Prime section data.
778 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
781 /// endModule - Emit all Dwarf sections that should come after the content.
783 void DwarfDebug::endModule() {
784 if (!FirstCU) return;
785 const Module *M = MMI->getModule();
786 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
788 // Collect info for variables that were optimized out.
789 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
790 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
791 DICompileUnit TheCU(CU_Nodes->getOperand(i));
792 DIArray Subprograms = TheCU.getSubprograms();
793 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
794 DISubprogram SP(Subprograms.getElement(i));
795 if (ProcessedSPNodes.count(SP) != 0) continue;
796 if (!SP.Verify()) continue;
797 if (!SP.isDefinition()) continue;
798 DIArray Variables = SP.getVariables();
799 if (Variables.getNumElements() == 0) continue;
801 LexicalScope *Scope =
802 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
803 DeadFnScopeMap[SP] = Scope;
805 // Construct subprogram DIE and add variables DIEs.
806 CompileUnit *SPCU = CUMap.lookup(TheCU);
807 assert(SPCU && "Unable to find Compile Unit!");
808 constructSubprogramDIE(SPCU, SP);
809 DIE *ScopeDIE = SPCU->getDIE(SP);
810 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
811 DIVariable DV(Variables.getElement(vi));
812 if (!DV.Verify()) continue;
813 DbgVariable *NewVar = new DbgVariable(DV, NULL);
814 if (DIE *VariableDIE =
815 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
816 ScopeDIE->addChild(VariableDIE);
822 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
823 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
824 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
826 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
828 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
829 AE = AbstractSPDies.end(); AI != AE; ++AI) {
830 DIE *ISP = AI->second;
831 if (InlinedSubprogramDIEs.count(ISP))
833 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
836 // Emit DW_AT_containing_type attribute to connect types with their
837 // vtable holding type.
838 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
839 CUE = CUMap.end(); CUI != CUE; ++CUI) {
840 CompileUnit *TheCU = CUI->second;
841 TheCU->constructContainingTypeDIEs();
844 // Standard sections final addresses.
845 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
846 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
847 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
848 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
850 // End text sections.
851 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
852 Asm->OutStreamer.SwitchSection(SectionMap[i]);
853 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
856 // Compute DIE offsets and sizes.
857 computeSizeAndOffsets();
859 // Emit all the DIEs into a debug info section
862 // Corresponding abbreviations into a abbrev section.
865 // Emit info into the dwarf accelerator table sections.
866 if (useDwarfAccelTables()) {
869 emitAccelNamespaces();
873 // Emit info into a debug pubtypes section.
874 // TODO: When we don't need the option anymore we can
875 // remove all of the code that adds to the table.
876 if (useDarwinGDBCompat())
879 // Emit info into a debug loc section.
882 // Emit info into a debug aranges section.
885 // Emit info into a debug ranges section.
888 // Emit info into a debug macinfo section.
892 // TODO: When we don't need the option anymore we
893 // can remove all of the code that this section
895 if (useDarwinGDBCompat())
896 emitDebugInlineInfo();
898 // Emit info into a debug str section.
902 DeleteContainerSeconds(DeadFnScopeMap);
904 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
905 E = CUMap.end(); I != E; ++I)
907 FirstCU = NULL; // Reset for the next Module, if any.
910 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
911 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
913 LLVMContext &Ctx = DV->getContext();
914 // More then one inlined variable corresponds to one abstract variable.
915 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
916 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
918 return AbsDbgVariable;
920 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
924 AbsDbgVariable = new DbgVariable(Var, NULL);
925 addScopeVariable(Scope, AbsDbgVariable);
926 AbstractVariables[Var] = AbsDbgVariable;
927 return AbsDbgVariable;
930 /// addCurrentFnArgument - If Var is a current function argument then add
931 /// it to CurrentFnArguments list.
932 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
933 DbgVariable *Var, LexicalScope *Scope) {
934 if (!LScopes.isCurrentFunctionScope(Scope))
936 DIVariable DV = Var->getVariable();
937 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
939 unsigned ArgNo = DV.getArgNumber();
943 size_t Size = CurrentFnArguments.size();
945 CurrentFnArguments.resize(MF->getFunction()->arg_size());
946 // llvm::Function argument size is not good indicator of how many
947 // arguments does the function have at source level.
949 CurrentFnArguments.resize(ArgNo * 2);
950 CurrentFnArguments[ArgNo - 1] = Var;
954 /// collectVariableInfoFromMMITable - Collect variable information from
955 /// side table maintained by MMI.
957 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
958 SmallPtrSet<const MDNode *, 16> &Processed) {
959 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
960 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
961 VE = VMap.end(); VI != VE; ++VI) {
962 const MDNode *Var = VI->first;
964 Processed.insert(Var);
966 const std::pair<unsigned, DebugLoc> &VP = VI->second;
968 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
970 // If variable scope is not found then skip this variable.
974 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
975 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
976 RegVar->setFrameIndex(VP.first);
977 if (!addCurrentFnArgument(MF, RegVar, Scope))
978 addScopeVariable(Scope, RegVar);
980 AbsDbgVariable->setFrameIndex(VP.first);
984 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
985 /// DBG_VALUE instruction, is in a defined reg.
986 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
987 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
988 return MI->getNumOperands() == 3 &&
989 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
990 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
993 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
995 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
996 const MCSymbol *FLabel,
997 const MCSymbol *SLabel,
998 const MachineInstr *MI) {
999 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1001 if (MI->getNumOperands() != 3) {
1002 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1003 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1005 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1006 MachineLocation MLoc;
1007 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1008 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1010 if (MI->getOperand(0).isImm())
1011 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1012 if (MI->getOperand(0).isFPImm())
1013 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1014 if (MI->getOperand(0).isCImm())
1015 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1017 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1020 /// collectVariableInfo - Find variables for each lexical scope.
1022 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1023 SmallPtrSet<const MDNode *, 16> &Processed) {
1025 /// collection info from MMI table.
1026 collectVariableInfoFromMMITable(MF, Processed);
1028 for (SmallVectorImpl<const MDNode*>::const_iterator
1029 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1031 const MDNode *Var = *UVI;
1032 if (Processed.count(Var))
1035 // History contains relevant DBG_VALUE instructions for Var and instructions
1037 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1038 if (History.empty())
1040 const MachineInstr *MInsn = History.front();
1043 LexicalScope *Scope = NULL;
1044 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1045 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1046 Scope = LScopes.getCurrentFunctionScope();
1048 if (DV.getVersion() <= LLVMDebugVersion9)
1049 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1051 if (MDNode *IA = DV.getInlinedAt())
1052 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1054 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1057 // If variable scope is not found then skip this variable.
1061 Processed.insert(DV);
1062 assert(MInsn->isDebugValue() && "History must begin with debug value");
1063 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1064 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1065 if (!addCurrentFnArgument(MF, RegVar, Scope))
1066 addScopeVariable(Scope, RegVar);
1068 AbsVar->setMInsn(MInsn);
1070 // Simple ranges that are fully coalesced.
1071 if (History.size() <= 1 || (History.size() == 2 &&
1072 MInsn->isIdenticalTo(History.back()))) {
1073 RegVar->setMInsn(MInsn);
1077 // handle multiple DBG_VALUE instructions describing one variable.
1078 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1080 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1081 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1082 const MachineInstr *Begin = *HI;
1083 assert(Begin->isDebugValue() && "Invalid History entry");
1085 // Check if DBG_VALUE is truncating a range.
1086 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1087 && !Begin->getOperand(0).getReg())
1090 // Compute the range for a register location.
1091 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1092 const MCSymbol *SLabel = 0;
1095 // If Begin is the last instruction in History then its value is valid
1096 // until the end of the function.
1097 SLabel = FunctionEndSym;
1099 const MachineInstr *End = HI[1];
1100 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1101 << "\t" << *Begin << "\t" << *End << "\n");
1102 if (End->isDebugValue())
1103 SLabel = getLabelBeforeInsn(End);
1105 // End is a normal instruction clobbering the range.
1106 SLabel = getLabelAfterInsn(End);
1107 assert(SLabel && "Forgot label after clobber instruction");
1112 // The value is valid until the next DBG_VALUE or clobber.
1113 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1116 DotDebugLocEntries.push_back(DotDebugLocEntry());
1119 // Collect info for variables that were optimized out.
1120 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1121 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1122 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1123 DIVariable DV(Variables.getElement(i));
1124 if (!DV || !DV.Verify() || !Processed.insert(DV))
1126 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1127 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1131 /// getLabelBeforeInsn - Return Label preceding the instruction.
1132 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1133 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1134 assert(Label && "Didn't insert label before instruction");
1138 /// getLabelAfterInsn - Return Label immediately following the instruction.
1139 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1140 return LabelsAfterInsn.lookup(MI);
1143 /// beginInstruction - Process beginning of an instruction.
1144 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1145 // Check if source location changes, but ignore DBG_VALUE locations.
1146 if (!MI->isDebugValue()) {
1147 DebugLoc DL = MI->getDebugLoc();
1148 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1151 if (DL == PrologEndLoc) {
1152 Flags |= DWARF2_FLAG_PROLOGUE_END;
1153 PrologEndLoc = DebugLoc();
1155 if (PrologEndLoc.isUnknown())
1156 Flags |= DWARF2_FLAG_IS_STMT;
1158 if (!DL.isUnknown()) {
1159 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1160 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1162 recordSourceLine(0, 0, 0, 0);
1166 // Insert labels where requested.
1167 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1168 LabelsBeforeInsn.find(MI);
1171 if (I == LabelsBeforeInsn.end())
1174 // Label already assigned.
1179 PrevLabel = MMI->getContext().CreateTempSymbol();
1180 Asm->OutStreamer.EmitLabel(PrevLabel);
1182 I->second = PrevLabel;
1185 /// endInstruction - Process end of an instruction.
1186 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1187 // Don't create a new label after DBG_VALUE instructions.
1188 // They don't generate code.
1189 if (!MI->isDebugValue())
1192 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1193 LabelsAfterInsn.find(MI);
1196 if (I == LabelsAfterInsn.end())
1199 // Label already assigned.
1203 // We need a label after this instruction.
1205 PrevLabel = MMI->getContext().CreateTempSymbol();
1206 Asm->OutStreamer.EmitLabel(PrevLabel);
1208 I->second = PrevLabel;
1211 /// identifyScopeMarkers() -
1212 /// Each LexicalScope has first instruction and last instruction to mark
1213 /// beginning and end of a scope respectively. Create an inverse map that list
1214 /// scopes starts (and ends) with an instruction. One instruction may start (or
1215 /// end) multiple scopes. Ignore scopes that are not reachable.
1216 void DwarfDebug::identifyScopeMarkers() {
1217 SmallVector<LexicalScope *, 4> WorkList;
1218 WorkList.push_back(LScopes.getCurrentFunctionScope());
1219 while (!WorkList.empty()) {
1220 LexicalScope *S = WorkList.pop_back_val();
1222 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1223 if (!Children.empty())
1224 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1225 SE = Children.end(); SI != SE; ++SI)
1226 WorkList.push_back(*SI);
1228 if (S->isAbstractScope())
1231 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1234 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1235 RE = Ranges.end(); RI != RE; ++RI) {
1236 assert(RI->first && "InsnRange does not have first instruction!");
1237 assert(RI->second && "InsnRange does not have second instruction!");
1238 requestLabelBeforeInsn(RI->first);
1239 requestLabelAfterInsn(RI->second);
1244 /// getScopeNode - Get MDNode for DebugLoc's scope.
1245 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1246 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1247 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1248 return DL.getScope(Ctx);
1251 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1252 /// line number info for the function.
1253 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1254 const MDNode *Scope = getScopeNode(DL, Ctx);
1255 DISubprogram SP = getDISubprogram(Scope);
1257 // Check for number of operands since the compatibility is
1259 if (SP->getNumOperands() > 19)
1260 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1262 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1268 /// beginFunction - Gather pre-function debug information. Assumes being
1269 /// emitted immediately after the function entry point.
1270 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1271 if (!MMI->hasDebugInfo()) return;
1272 LScopes.initialize(*MF);
1273 if (LScopes.empty()) return;
1274 identifyScopeMarkers();
1276 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1277 Asm->getFunctionNumber());
1278 // Assumes in correct section after the entry point.
1279 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1281 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1283 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1284 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1285 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1287 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1289 bool AtBlockEntry = true;
1290 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1292 const MachineInstr *MI = II;
1294 if (MI->isDebugValue()) {
1295 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1297 // Keep track of user variables.
1299 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1301 // Variable is in a register, we need to check for clobbers.
1302 if (isDbgValueInDefinedReg(MI))
1303 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1305 // Check the history of this variable.
1306 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1307 if (History.empty()) {
1308 UserVariables.push_back(Var);
1309 // The first mention of a function argument gets the FunctionBeginSym
1310 // label, so arguments are visible when breaking at function entry.
1312 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1313 DISubprogram(getDISubprogram(DV.getContext()))
1314 .describes(MF->getFunction()))
1315 LabelsBeforeInsn[MI] = FunctionBeginSym;
1317 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1318 const MachineInstr *Prev = History.back();
1319 if (Prev->isDebugValue()) {
1320 // Coalesce identical entries at the end of History.
1321 if (History.size() >= 2 &&
1322 Prev->isIdenticalTo(History[History.size() - 2])) {
1323 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1325 << "\t" << *History[History.size() - 2] << "\n");
1329 // Terminate old register assignments that don't reach MI;
1330 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1331 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1332 isDbgValueInDefinedReg(Prev)) {
1333 // Previous register assignment needs to terminate at the end of
1335 MachineBasicBlock::const_iterator LastMI =
1336 PrevMBB->getLastNonDebugInstr();
1337 if (LastMI == PrevMBB->end()) {
1338 // Drop DBG_VALUE for empty range.
1339 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1340 << "\t" << *Prev << "\n");
1344 // Terminate after LastMI.
1345 History.push_back(LastMI);
1350 History.push_back(MI);
1352 // Not a DBG_VALUE instruction.
1354 AtBlockEntry = false;
1356 // First known non DBG_VALUE location marks beginning of function
1358 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1359 PrologEndLoc = MI->getDebugLoc();
1361 // Check if the instruction clobbers any registers with debug vars.
1362 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1363 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1364 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1366 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1367 AI.isValid(); ++AI) {
1369 const MDNode *Var = LiveUserVar[Reg];
1372 // Reg is now clobbered.
1373 LiveUserVar[Reg] = 0;
1375 // Was MD last defined by a DBG_VALUE referring to Reg?
1376 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1377 if (HistI == DbgValues.end())
1379 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1380 if (History.empty())
1382 const MachineInstr *Prev = History.back();
1383 // Sanity-check: Register assignments are terminated at the end of
1385 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1387 // Is the variable still in Reg?
1388 if (!isDbgValueInDefinedReg(Prev) ||
1389 Prev->getOperand(0).getReg() != Reg)
1391 // Var is clobbered. Make sure the next instruction gets a label.
1392 History.push_back(MI);
1399 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1401 SmallVectorImpl<const MachineInstr*> &History = I->second;
1402 if (History.empty())
1405 // Make sure the final register assignments are terminated.
1406 const MachineInstr *Prev = History.back();
1407 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1408 const MachineBasicBlock *PrevMBB = Prev->getParent();
1409 MachineBasicBlock::const_iterator LastMI =
1410 PrevMBB->getLastNonDebugInstr();
1411 if (LastMI == PrevMBB->end())
1412 // Drop DBG_VALUE for empty range.
1415 // Terminate after LastMI.
1416 History.push_back(LastMI);
1419 // Request labels for the full history.
1420 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1421 const MachineInstr *MI = History[i];
1422 if (MI->isDebugValue())
1423 requestLabelBeforeInsn(MI);
1425 requestLabelAfterInsn(MI);
1429 PrevInstLoc = DebugLoc();
1430 PrevLabel = FunctionBeginSym;
1432 // Record beginning of function.
1433 if (!PrologEndLoc.isUnknown()) {
1434 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1435 MF->getFunction()->getContext());
1436 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1437 FnStartDL.getScope(MF->getFunction()->getContext()),
1442 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1443 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1444 ScopeVariables[LS].push_back(Var);
1445 // Vars.push_back(Var);
1448 /// endFunction - Gather and emit post-function debug information.
1450 void DwarfDebug::endFunction(const MachineFunction *MF) {
1451 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1453 // Define end label for subprogram.
1454 FunctionEndSym = Asm->GetTempSymbol("func_end",
1455 Asm->getFunctionNumber());
1456 // Assumes in correct section after the entry point.
1457 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1459 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1460 collectVariableInfo(MF, ProcessedVars);
1462 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1463 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1464 assert(TheCU && "Unable to find compile unit!");
1466 // Construct abstract scopes.
1467 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1468 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1469 LexicalScope *AScope = AList[i];
1470 DISubprogram SP(AScope->getScopeNode());
1472 // Collect info for variables that were optimized out.
1473 DIArray Variables = SP.getVariables();
1474 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1475 DIVariable DV(Variables.getElement(i));
1476 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1478 // Check that DbgVariable for DV wasn't created earlier, when
1479 // findAbstractVariable() was called for inlined instance of DV.
1480 LLVMContext &Ctx = DV->getContext();
1481 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1482 if (AbstractVariables.lookup(CleanDV))
1484 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1485 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1488 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1489 constructScopeDIE(TheCU, AScope);
1492 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1494 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1495 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1497 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1498 MMI->getFrameMoves()));
1501 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1502 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1503 DeleteContainerPointers(I->second);
1504 ScopeVariables.clear();
1505 DeleteContainerPointers(CurrentFnArguments);
1506 UserVariables.clear();
1508 AbstractVariables.clear();
1509 LabelsBeforeInsn.clear();
1510 LabelsAfterInsn.clear();
1514 /// recordSourceLine - Register a source line with debug info. Returns the
1515 /// unique label that was emitted and which provides correspondence to
1516 /// the source line list.
1517 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1523 DIDescriptor Scope(S);
1525 if (Scope.isCompileUnit()) {
1526 DICompileUnit CU(S);
1527 Fn = CU.getFilename();
1528 Dir = CU.getDirectory();
1529 } else if (Scope.isFile()) {
1531 Fn = F.getFilename();
1532 Dir = F.getDirectory();
1533 } else if (Scope.isSubprogram()) {
1535 Fn = SP.getFilename();
1536 Dir = SP.getDirectory();
1537 } else if (Scope.isLexicalBlockFile()) {
1538 DILexicalBlockFile DBF(S);
1539 Fn = DBF.getFilename();
1540 Dir = DBF.getDirectory();
1541 } else if (Scope.isLexicalBlock()) {
1542 DILexicalBlock DB(S);
1543 Fn = DB.getFilename();
1544 Dir = DB.getDirectory();
1546 llvm_unreachable("Unexpected scope info");
1548 Src = GetOrCreateSourceID(Fn, Dir);
1550 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1553 //===----------------------------------------------------------------------===//
1555 //===----------------------------------------------------------------------===//
1557 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1560 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1561 // Get the children.
1562 const std::vector<DIE *> &Children = Die->getChildren();
1564 // Record the abbreviation.
1565 assignAbbrevNumber(Die->getAbbrev());
1567 // Get the abbreviation for this DIE.
1568 unsigned AbbrevNumber = Die->getAbbrevNumber();
1569 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1572 Die->setOffset(Offset);
1574 // Start the size with the size of abbreviation code.
1575 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1577 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1578 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1580 // Size the DIE attribute values.
1581 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1582 // Size attribute value.
1583 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1585 // Size the DIE children if any.
1586 if (!Children.empty()) {
1587 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1588 "Children flag not set");
1590 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1591 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1593 // End of children marker.
1594 Offset += sizeof(int8_t);
1597 Die->setSize(Offset - Die->getOffset());
1601 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1603 void DwarfDebug::computeSizeAndOffsets() {
1604 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1605 E = CUMap.end(); I != E; ++I) {
1606 // Compute size of compile unit header.
1608 sizeof(int32_t) + // Length of Compilation Unit Info
1609 sizeof(int16_t) + // DWARF version number
1610 sizeof(int32_t) + // Offset Into Abbrev. Section
1611 sizeof(int8_t); // Pointer Size (in bytes)
1612 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1616 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1617 /// the start of each one.
1618 void DwarfDebug::EmitSectionLabels() {
1619 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1621 // Dwarf sections base addresses.
1622 DwarfInfoSectionSym =
1623 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1624 DwarfAbbrevSectionSym =
1625 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1626 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1628 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1629 EmitSectionSym(Asm, MacroInfo);
1631 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1632 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1633 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1634 DwarfStrSectionSym =
1635 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1636 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1639 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1640 "section_debug_loc");
1642 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1643 EmitSectionSym(Asm, TLOF.getDataSection());
1646 /// emitDIE - Recursively emits a debug information entry.
1648 void DwarfDebug::emitDIE(DIE *Die) {
1649 // Get the abbreviation for this DIE.
1650 unsigned AbbrevNumber = Die->getAbbrevNumber();
1651 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1653 // Emit the code (index) for the abbreviation.
1654 if (Asm->isVerbose())
1655 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1656 Twine::utohexstr(Die->getOffset()) + ":0x" +
1657 Twine::utohexstr(Die->getSize()) + " " +
1658 dwarf::TagString(Abbrev->getTag()));
1659 Asm->EmitULEB128(AbbrevNumber);
1661 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1662 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1664 // Emit the DIE attribute values.
1665 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1666 unsigned Attr = AbbrevData[i].getAttribute();
1667 unsigned Form = AbbrevData[i].getForm();
1668 assert(Form && "Too many attributes for DIE (check abbreviation)");
1670 if (Asm->isVerbose())
1671 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1674 case dwarf::DW_AT_abstract_origin: {
1675 DIEEntry *E = cast<DIEEntry>(Values[i]);
1676 DIE *Origin = E->getEntry();
1677 unsigned Addr = Origin->getOffset();
1678 Asm->EmitInt32(Addr);
1681 case dwarf::DW_AT_ranges: {
1682 // DW_AT_range Value encodes offset in debug_range section.
1683 DIEInteger *V = cast<DIEInteger>(Values[i]);
1685 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1686 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1690 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1692 DwarfDebugRangeSectionSym,
1697 case dwarf::DW_AT_location: {
1698 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1699 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1700 Asm->EmitLabelReference(L->getValue(), 4);
1702 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1704 Values[i]->EmitValue(Asm, Form);
1708 case dwarf::DW_AT_accessibility: {
1709 if (Asm->isVerbose()) {
1710 DIEInteger *V = cast<DIEInteger>(Values[i]);
1711 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1713 Values[i]->EmitValue(Asm, Form);
1717 // Emit an attribute using the defined form.
1718 Values[i]->EmitValue(Asm, Form);
1723 // Emit the DIE children if any.
1724 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1725 const std::vector<DIE *> &Children = Die->getChildren();
1727 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1728 emitDIE(Children[j]);
1730 if (Asm->isVerbose())
1731 Asm->OutStreamer.AddComment("End Of Children Mark");
1736 /// emitDebugInfo - Emit the debug info section.
1738 void DwarfDebug::emitDebugInfo() {
1739 // Start debug info section.
1740 Asm->OutStreamer.SwitchSection(
1741 Asm->getObjFileLowering().getDwarfInfoSection());
1742 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1743 E = CUMap.end(); I != E; ++I) {
1744 CompileUnit *TheCU = I->second;
1745 DIE *Die = TheCU->getCUDie();
1747 // Emit the compile units header.
1748 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1751 // Emit size of content not including length itself
1752 unsigned ContentSize = Die->getSize() +
1753 sizeof(int16_t) + // DWARF version number
1754 sizeof(int32_t) + // Offset Into Abbrev. Section
1755 sizeof(int8_t); // Pointer Size (in bytes)
1757 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1758 Asm->EmitInt32(ContentSize);
1759 Asm->OutStreamer.AddComment("DWARF version number");
1760 Asm->EmitInt16(dwarf::DWARF_VERSION);
1761 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1762 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1763 DwarfAbbrevSectionSym);
1764 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1765 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1768 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1772 /// emitAbbreviations - Emit the abbreviation section.
1774 void DwarfDebug::emitAbbreviations() const {
1775 // Check to see if it is worth the effort.
1776 if (!Abbreviations.empty()) {
1777 // Start the debug abbrev section.
1778 Asm->OutStreamer.SwitchSection(
1779 Asm->getObjFileLowering().getDwarfAbbrevSection());
1781 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1783 // For each abbrevation.
1784 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1785 // Get abbreviation data
1786 const DIEAbbrev *Abbrev = Abbreviations[i];
1788 // Emit the abbrevations code (base 1 index.)
1789 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1791 // Emit the abbreviations data.
1795 // Mark end of abbreviations.
1796 Asm->EmitULEB128(0, "EOM(3)");
1798 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1802 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1803 /// the line matrix.
1805 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1806 // Define last address of section.
1807 Asm->OutStreamer.AddComment("Extended Op");
1810 Asm->OutStreamer.AddComment("Op size");
1811 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1812 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1813 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1815 Asm->OutStreamer.AddComment("Section end label");
1817 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1818 Asm->getTargetData().getPointerSize(),
1821 // Mark end of matrix.
1822 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1828 /// emitAccelNames - Emit visible names into a hashed accelerator table
1830 void DwarfDebug::emitAccelNames() {
1831 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1832 dwarf::DW_FORM_data4));
1833 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1834 E = CUMap.end(); I != E; ++I) {
1835 CompileUnit *TheCU = I->second;
1836 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1837 for (StringMap<std::vector<DIE*> >::const_iterator
1838 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1839 const char *Name = GI->getKeyData();
1840 const std::vector<DIE *> &Entities = GI->second;
1841 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1842 DE = Entities.end(); DI != DE; ++DI)
1843 AT.AddName(Name, (*DI));
1847 AT.FinalizeTable(Asm, "Names");
1848 Asm->OutStreamer.SwitchSection(
1849 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1850 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1851 Asm->OutStreamer.EmitLabel(SectionBegin);
1853 // Emit the full data.
1854 AT.Emit(Asm, SectionBegin, this);
1857 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1858 /// accelerator table section.
1859 void DwarfDebug::emitAccelObjC() {
1860 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1861 dwarf::DW_FORM_data4));
1862 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1863 E = CUMap.end(); I != E; ++I) {
1864 CompileUnit *TheCU = I->second;
1865 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1866 for (StringMap<std::vector<DIE*> >::const_iterator
1867 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1868 const char *Name = GI->getKeyData();
1869 const std::vector<DIE *> &Entities = GI->second;
1870 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1871 DE = Entities.end(); DI != DE; ++DI)
1872 AT.AddName(Name, (*DI));
1876 AT.FinalizeTable(Asm, "ObjC");
1877 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1878 .getDwarfAccelObjCSection());
1879 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1880 Asm->OutStreamer.EmitLabel(SectionBegin);
1882 // Emit the full data.
1883 AT.Emit(Asm, SectionBegin, this);
1886 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1888 void DwarfDebug::emitAccelNamespaces() {
1889 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1890 dwarf::DW_FORM_data4));
1891 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1892 E = CUMap.end(); I != E; ++I) {
1893 CompileUnit *TheCU = I->second;
1894 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
1895 for (StringMap<std::vector<DIE*> >::const_iterator
1896 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1897 const char *Name = GI->getKeyData();
1898 const std::vector<DIE *> &Entities = GI->second;
1899 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1900 DE = Entities.end(); DI != DE; ++DI)
1901 AT.AddName(Name, (*DI));
1905 AT.FinalizeTable(Asm, "namespac");
1906 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1907 .getDwarfAccelNamespaceSection());
1908 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1909 Asm->OutStreamer.EmitLabel(SectionBegin);
1911 // Emit the full data.
1912 AT.Emit(Asm, SectionBegin, this);
1915 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1916 void DwarfDebug::emitAccelTypes() {
1917 std::vector<DwarfAccelTable::Atom> Atoms;
1918 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1919 dwarf::DW_FORM_data4));
1920 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
1921 dwarf::DW_FORM_data2));
1922 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
1923 dwarf::DW_FORM_data1));
1924 DwarfAccelTable AT(Atoms);
1925 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1926 E = CUMap.end(); I != E; ++I) {
1927 CompileUnit *TheCU = I->second;
1928 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
1929 = TheCU->getAccelTypes();
1930 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
1931 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1932 const char *Name = GI->getKeyData();
1933 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
1934 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
1935 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
1936 AT.AddName(Name, (*DI).first, (*DI).second);
1940 AT.FinalizeTable(Asm, "types");
1941 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1942 .getDwarfAccelTypesSection());
1943 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1944 Asm->OutStreamer.EmitLabel(SectionBegin);
1946 // Emit the full data.
1947 AT.Emit(Asm, SectionBegin, this);
1950 void DwarfDebug::emitDebugPubTypes() {
1951 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1952 E = CUMap.end(); I != E; ++I) {
1953 CompileUnit *TheCU = I->second;
1954 // Start the dwarf pubtypes section.
1955 Asm->OutStreamer.SwitchSection(
1956 Asm->getObjFileLowering().getDwarfPubTypesSection());
1957 Asm->OutStreamer.AddComment("Length of Public Types Info");
1958 Asm->EmitLabelDifference(
1959 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1960 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1962 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1965 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1966 Asm->EmitInt16(dwarf::DWARF_VERSION);
1968 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1969 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1970 DwarfInfoSectionSym);
1972 Asm->OutStreamer.AddComment("Compilation Unit Length");
1973 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1974 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1977 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1978 for (StringMap<DIE*>::const_iterator
1979 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1980 const char *Name = GI->getKeyData();
1981 DIE *Entity = GI->second;
1983 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1984 Asm->EmitInt32(Entity->getOffset());
1986 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1987 // Emit the name with a terminating null byte.
1988 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1991 Asm->OutStreamer.AddComment("End Mark");
1993 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1998 /// emitDebugStr - Emit visible names into a debug str section.
2000 void DwarfDebug::emitDebugStr() {
2001 // Check to see if it is worth the effort.
2002 if (StringPool.empty()) return;
2004 // Start the dwarf str section.
2005 Asm->OutStreamer.SwitchSection(
2006 Asm->getObjFileLowering().getDwarfStrSection());
2008 // Get all of the string pool entries and put them in an array by their ID so
2009 // we can sort them.
2010 SmallVector<std::pair<unsigned,
2011 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2013 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2014 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2015 Entries.push_back(std::make_pair(I->second.second, &*I));
2017 array_pod_sort(Entries.begin(), Entries.end());
2019 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2020 // Emit a label for reference from debug information entries.
2021 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2023 // Emit the string itself with a terminating null byte.
2024 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2025 Entries[i].second->getKeyLength()+1),
2030 /// emitDebugLoc - Emit visible names into a debug loc section.
2032 void DwarfDebug::emitDebugLoc() {
2033 if (DotDebugLocEntries.empty())
2036 for (SmallVector<DotDebugLocEntry, 4>::iterator
2037 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2039 DotDebugLocEntry &Entry = *I;
2040 if (I + 1 != DotDebugLocEntries.end())
2044 // Start the dwarf loc section.
2045 Asm->OutStreamer.SwitchSection(
2046 Asm->getObjFileLowering().getDwarfLocSection());
2047 unsigned char Size = Asm->getTargetData().getPointerSize();
2048 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2050 for (SmallVector<DotDebugLocEntry, 4>::iterator
2051 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2052 I != E; ++I, ++index) {
2053 DotDebugLocEntry &Entry = *I;
2054 if (Entry.isMerged()) continue;
2055 if (Entry.isEmpty()) {
2056 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2057 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2058 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2060 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2061 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2062 DIVariable DV(Entry.Variable);
2063 Asm->OutStreamer.AddComment("Loc expr size");
2064 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2065 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2066 Asm->EmitLabelDifference(end, begin, 2);
2067 Asm->OutStreamer.EmitLabel(begin);
2068 if (Entry.isInt()) {
2069 DIBasicType BTy(DV.getType());
2071 (BTy.getEncoding() == dwarf::DW_ATE_signed
2072 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2073 Asm->OutStreamer.AddComment("DW_OP_consts");
2074 Asm->EmitInt8(dwarf::DW_OP_consts);
2075 Asm->EmitSLEB128(Entry.getInt());
2077 Asm->OutStreamer.AddComment("DW_OP_constu");
2078 Asm->EmitInt8(dwarf::DW_OP_constu);
2079 Asm->EmitULEB128(Entry.getInt());
2081 } else if (Entry.isLocation()) {
2082 if (!DV.hasComplexAddress())
2084 Asm->EmitDwarfRegOp(Entry.Loc);
2086 // Complex address entry.
2087 unsigned N = DV.getNumAddrElements();
2089 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2090 if (Entry.Loc.getOffset()) {
2092 Asm->EmitDwarfRegOp(Entry.Loc);
2093 Asm->OutStreamer.AddComment("DW_OP_deref");
2094 Asm->EmitInt8(dwarf::DW_OP_deref);
2095 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2096 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2097 Asm->EmitSLEB128(DV.getAddrElement(1));
2099 // If first address element is OpPlus then emit
2100 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2101 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2102 Asm->EmitDwarfRegOp(Loc);
2106 Asm->EmitDwarfRegOp(Entry.Loc);
2109 // Emit remaining complex address elements.
2110 for (; i < N; ++i) {
2111 uint64_t Element = DV.getAddrElement(i);
2112 if (Element == DIBuilder::OpPlus) {
2113 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2114 Asm->EmitULEB128(DV.getAddrElement(++i));
2115 } else if (Element == DIBuilder::OpDeref) {
2116 if (!Entry.Loc.isReg())
2117 Asm->EmitInt8(dwarf::DW_OP_deref);
2119 llvm_unreachable("unknown Opcode found in complex address");
2123 // else ... ignore constant fp. There is not any good way to
2124 // to represent them here in dwarf.
2125 Asm->OutStreamer.EmitLabel(end);
2130 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2132 void DwarfDebug::EmitDebugARanges() {
2133 // Start the dwarf aranges section.
2134 Asm->OutStreamer.SwitchSection(
2135 Asm->getObjFileLowering().getDwarfARangesSection());
2138 /// emitDebugRanges - Emit visible names into a debug ranges section.
2140 void DwarfDebug::emitDebugRanges() {
2141 // Start the dwarf ranges section.
2142 Asm->OutStreamer.SwitchSection(
2143 Asm->getObjFileLowering().getDwarfRangesSection());
2144 unsigned char Size = Asm->getTargetData().getPointerSize();
2145 for (SmallVector<const MCSymbol *, 8>::iterator
2146 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2149 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2151 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2155 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2157 void DwarfDebug::emitDebugMacInfo() {
2158 if (const MCSection *LineInfo =
2159 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2160 // Start the dwarf macinfo section.
2161 Asm->OutStreamer.SwitchSection(LineInfo);
2165 /// emitDebugInlineInfo - Emit inline info using following format.
2167 /// 1. length of section
2168 /// 2. Dwarf version number
2169 /// 3. address size.
2171 /// Entries (one "entry" for each function that was inlined):
2173 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2174 /// otherwise offset into __debug_str for regular function name.
2175 /// 2. offset into __debug_str section for regular function name.
2176 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2177 /// instances for the function.
2179 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2180 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2181 /// __debug_info section, and the low_pc is the starting address for the
2182 /// inlining instance.
2183 void DwarfDebug::emitDebugInlineInfo() {
2184 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2190 Asm->OutStreamer.SwitchSection(
2191 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2193 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2194 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2195 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2197 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2199 Asm->OutStreamer.AddComment("Dwarf Version");
2200 Asm->EmitInt16(dwarf::DWARF_VERSION);
2201 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2202 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2204 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2205 E = InlinedSPNodes.end(); I != E; ++I) {
2207 const MDNode *Node = *I;
2208 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2209 = InlineInfo.find(Node);
2210 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2211 DISubprogram SP(Node);
2212 StringRef LName = SP.getLinkageName();
2213 StringRef Name = SP.getName();
2215 Asm->OutStreamer.AddComment("MIPS linkage name");
2217 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2219 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2220 DwarfStrSectionSym);
2222 Asm->OutStreamer.AddComment("Function name");
2223 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2224 Asm->EmitULEB128(Labels.size(), "Inline count");
2226 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2227 LE = Labels.end(); LI != LE; ++LI) {
2228 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2229 Asm->EmitInt32(LI->second->getOffset());
2231 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2232 Asm->OutStreamer.EmitSymbolValue(LI->first,
2233 Asm->getTargetData().getPointerSize(),0);
2237 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));