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/DataLayout.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 // If we're updating an abstract DIE, then we will be adding the children and
311 // object pointer later on. But what we don't want to do is process the
312 // concrete DIE twice.
313 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
314 // Pick up abstract subprogram DIE.
315 SPDie = new DIE(dwarf::DW_TAG_subprogram);
316 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
317 dwarf::DW_FORM_ref4, AbsSPDIE);
320 DISubprogram SPDecl = SP.getFunctionDeclaration();
321 if (!SPDecl.isSubprogram()) {
322 // There is not any need to generate specification DIE for a function
323 // defined at compile unit level. If a function is defined inside another
324 // function then gdb prefers the definition at top level and but does not
325 // expect specification DIE in parent function. So avoid creating
326 // specification DIE for a function defined inside a function.
327 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
328 !SP.getContext().isFile() &&
329 !isSubprogramContext(SP.getContext())) {
330 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
333 DICompositeType SPTy = SP.getType();
334 DIArray Args = SPTy.getTypeArray();
335 unsigned SPTag = SPTy.getTag();
336 if (SPTag == dwarf::DW_TAG_subroutine_type)
337 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
338 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
339 DIType ATy = DIType(Args.getElement(i));
340 SPCU->addType(Arg, ATy);
341 if (ATy.isArtificial())
342 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
343 if (ATy.isObjectPointer())
344 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
345 dwarf::DW_FORM_ref4, Arg);
346 SPDie->addChild(Arg);
348 DIE *SPDeclDie = SPDie;
349 SPDie = new DIE(dwarf::DW_TAG_subprogram);
350 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
357 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
358 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
359 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
360 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
361 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
362 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
363 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
365 // Add name to the name table, we do this here because we're guaranteed
366 // to have concrete versions of our DW_TAG_subprogram nodes.
367 addSubprogramNames(SPCU, SP, SPDie);
372 /// constructLexicalScope - Construct new DW_TAG_lexical_block
373 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
374 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
375 LexicalScope *Scope) {
376 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
377 if (Scope->isAbstractScope())
380 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
384 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
385 if (Ranges.size() > 1) {
386 // .debug_range section has not been laid out yet. Emit offset in
387 // .debug_range as a uint, size 4, for now. emitDIE will handle
388 // DW_AT_ranges appropriately.
389 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
390 DebugRangeSymbols.size()
391 * Asm->getDataLayout().getPointerSize());
392 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
393 RE = Ranges.end(); RI != RE; ++RI) {
394 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
395 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
397 DebugRangeSymbols.push_back(NULL);
398 DebugRangeSymbols.push_back(NULL);
402 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
403 const MCSymbol *End = getLabelAfterInsn(RI->second);
405 if (End == 0) return 0;
407 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
408 assert(End->isDefined() && "Invalid end label for an inlined scope!");
410 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
411 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
416 /// constructInlinedScopeDIE - This scope represents inlined body of
417 /// a function. Construct DIE to represent this concrete inlined copy
419 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
420 LexicalScope *Scope) {
421 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
422 assert(Ranges.empty() == false &&
423 "LexicalScope does not have instruction markers!");
425 if (!Scope->getScopeNode())
427 DIScope DS(Scope->getScopeNode());
428 DISubprogram InlinedSP = getDISubprogram(DS);
429 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
431 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
435 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
436 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
437 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
439 if (StartLabel == 0 || EndLabel == 0) {
440 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
442 assert(StartLabel->isDefined() &&
443 "Invalid starting label for an inlined scope!");
444 assert(EndLabel->isDefined() &&
445 "Invalid end label for an inlined scope!");
447 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
448 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
449 dwarf::DW_FORM_ref4, OriginDIE);
451 if (Ranges.size() > 1) {
452 // .debug_range section has not been laid out yet. Emit offset in
453 // .debug_range as a uint, size 4, for now. emitDIE will handle
454 // DW_AT_ranges appropriately.
455 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
456 DebugRangeSymbols.size()
457 * Asm->getDataLayout().getPointerSize());
458 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
459 RE = Ranges.end(); RI != RE; ++RI) {
460 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
461 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
463 DebugRangeSymbols.push_back(NULL);
464 DebugRangeSymbols.push_back(NULL);
466 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
468 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
472 InlinedSubprogramDIEs.insert(OriginDIE);
474 // Track the start label for this inlined function.
475 //.debug_inlined section specification does not clearly state how
476 // to emit inlined scope that is split into multiple instruction ranges.
477 // For now, use first instruction range and emit low_pc/high_pc pair and
478 // corresponding .debug_inlined section entry for this pair.
479 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
480 I = InlineInfo.find(InlinedSP);
482 if (I == InlineInfo.end()) {
483 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
484 InlinedSPNodes.push_back(InlinedSP);
486 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
488 DILocation DL(Scope->getInlinedAt());
489 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
490 GetOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
491 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
493 // Add name to the name table, we do this here because we're guaranteed
494 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
495 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
500 /// constructScopeDIE - Construct a DIE for this scope.
501 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
502 if (!Scope || !Scope->getScopeNode())
505 SmallVector<DIE *, 8> Children;
506 DIE *ObjectPointer = NULL;
508 // Collect arguments for current function.
509 if (LScopes.isCurrentFunctionScope(Scope))
510 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
511 if (DbgVariable *ArgDV = CurrentFnArguments[i])
513 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
514 Children.push_back(Arg);
515 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
518 // Collect lexical scope children first.
519 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
520 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
522 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
523 Children.push_back(Variable);
524 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
526 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
527 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
528 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
529 Children.push_back(Nested);
530 DIScope DS(Scope->getScopeNode());
531 DIE *ScopeDIE = NULL;
532 if (Scope->getInlinedAt())
533 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
534 else if (DS.isSubprogram()) {
535 ProcessedSPNodes.insert(DS);
536 if (Scope->isAbstractScope()) {
537 ScopeDIE = TheCU->getDIE(DS);
538 // Note down abstract DIE.
540 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
543 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
546 // There is no need to emit empty lexical block DIE.
547 if (Children.empty())
549 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
552 if (!ScopeDIE) return NULL;
555 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
556 E = Children.end(); I != E; ++I)
557 ScopeDIE->addChild(*I);
559 if (DS.isSubprogram() && ObjectPointer != NULL)
560 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
561 dwarf::DW_FORM_ref4, ObjectPointer);
563 if (DS.isSubprogram())
564 TheCU->addPubTypes(DISubprogram(DS));
569 /// GetOrCreateSourceID - Look up the source id with the given directory and
570 /// source file names. If none currently exists, create a new id and insert it
571 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
573 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
575 // If FE did not provide a file name, then assume stdin.
576 if (FileName.empty())
577 return GetOrCreateSourceID("<stdin>", StringRef());
579 // TODO: this might not belong here. See if we can factor this better.
580 if (DirName == CompilationDir)
583 unsigned SrcId = SourceIdMap.size()+1;
585 // We look up the file/dir pair by concatenating them with a zero byte.
586 SmallString<128> NamePair;
588 NamePair += '\0'; // Zero bytes are not allowed in paths.
589 NamePair += FileName;
591 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
592 if (Ent.getValue() != SrcId)
593 return Ent.getValue();
595 // Print out a .file directive to specify files for .loc directives.
596 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
601 /// constructCompileUnit - Create new CompileUnit for the given
602 /// metadata node with tag DW_TAG_compile_unit.
603 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
604 DICompileUnit DIUnit(N);
605 StringRef FN = DIUnit.getFilename();
606 CompilationDir = DIUnit.getDirectory();
607 unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
609 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
610 CompileUnit *NewCU = new CompileUnit(ID, DIUnit.getLanguage(), Die,
612 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
613 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
614 DIUnit.getLanguage());
615 NewCU->addString(Die, dwarf::DW_AT_name, FN);
616 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
618 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
619 // DW_AT_stmt_list is a offset of line number information for this
620 // compile unit in debug_line section.
621 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
622 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
623 Asm->GetTempSymbol("section_line"));
625 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
627 if (!CompilationDir.empty())
628 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
629 if (DIUnit.isOptimized())
630 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
632 StringRef Flags = DIUnit.getFlags();
634 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
636 if (unsigned RVer = DIUnit.getRunTimeVersion())
637 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
638 dwarf::DW_FORM_data1, RVer);
642 CUMap.insert(std::make_pair(N, NewCU));
646 /// construct SubprogramDIE - Construct subprogram DIE.
647 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
649 CompileUnit *&CURef = SPMap[N];
655 if (!SP.isDefinition())
656 // This is a method declaration which will be handled while constructing
660 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
663 TheCU->insertDIE(N, SubprogramDie);
665 // Add to context owner.
666 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
671 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
672 /// as llvm.dbg.enum and llvm.dbg.ty
673 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
674 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
675 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
676 const MDNode *N = NMD->getOperand(i);
677 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
678 constructSubprogramDIE(CU, N);
681 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
682 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
683 const MDNode *N = NMD->getOperand(i);
684 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
685 CU->createGlobalVariableDIE(N);
688 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
689 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
690 DIType Ty(NMD->getOperand(i));
691 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
692 CU->getOrCreateTypeDIE(Ty);
695 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
696 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
697 DIType Ty(NMD->getOperand(i));
698 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
699 CU->getOrCreateTypeDIE(Ty);
703 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
704 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
705 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
706 DebugInfoFinder DbgFinder;
707 DbgFinder.processModule(*M);
709 bool HasDebugInfo = false;
710 // Scan all the compile-units to see if there are any marked as the main
711 // unit. If not, we do not generate debug info.
712 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
713 E = DbgFinder.compile_unit_end(); I != E; ++I) {
714 if (DICompileUnit(*I).isMain()) {
719 if (!HasDebugInfo) return false;
721 // Create all the compile unit DIEs.
722 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
723 E = DbgFinder.compile_unit_end(); I != E; ++I)
724 constructCompileUnit(*I);
726 // Create DIEs for each global variable.
727 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
728 E = DbgFinder.global_variable_end(); I != E; ++I) {
729 const MDNode *N = *I;
730 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
731 CU->createGlobalVariableDIE(N);
734 // Create DIEs for each subprogram.
735 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
736 E = DbgFinder.subprogram_end(); I != E; ++I) {
737 const MDNode *N = *I;
738 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
739 constructSubprogramDIE(CU, N);
745 /// beginModule - Emit all Dwarf sections that should come prior to the
746 /// content. Create global DIEs and emit initial debug info sections.
747 /// This is invoked by the target AsmPrinter.
748 void DwarfDebug::beginModule(Module *M) {
749 if (DisableDebugInfoPrinting)
752 // If module has named metadata anchors then use them, otherwise scan the
753 // module using debug info finder to collect debug info.
754 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
756 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
757 DICompileUnit CUNode(CU_Nodes->getOperand(i));
758 CompileUnit *CU = constructCompileUnit(CUNode);
759 DIArray GVs = CUNode.getGlobalVariables();
760 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
761 CU->createGlobalVariableDIE(GVs.getElement(i));
762 DIArray SPs = CUNode.getSubprograms();
763 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
764 constructSubprogramDIE(CU, SPs.getElement(i));
765 DIArray EnumTypes = CUNode.getEnumTypes();
766 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
767 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
768 DIArray RetainedTypes = CUNode.getRetainedTypes();
769 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
770 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
772 } else if (!collectLegacyDebugInfo(M))
775 collectInfoFromNamedMDNodes(M);
777 // Tell MMI that we have debug info.
778 MMI->setDebugInfoAvailability(true);
780 // Emit initial sections.
783 // Prime section data.
784 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
787 /// endModule - Emit all Dwarf sections that should come after the content.
789 void DwarfDebug::endModule() {
790 if (!FirstCU) return;
791 const Module *M = MMI->getModule();
792 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
794 // Collect info for variables that were optimized out.
795 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
796 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
797 DICompileUnit TheCU(CU_Nodes->getOperand(i));
798 DIArray Subprograms = TheCU.getSubprograms();
799 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
800 DISubprogram SP(Subprograms.getElement(i));
801 if (ProcessedSPNodes.count(SP) != 0) continue;
802 if (!SP.Verify()) continue;
803 if (!SP.isDefinition()) continue;
804 DIArray Variables = SP.getVariables();
805 if (Variables.getNumElements() == 0) continue;
807 LexicalScope *Scope =
808 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
809 DeadFnScopeMap[SP] = Scope;
811 // Construct subprogram DIE and add variables DIEs.
812 CompileUnit *SPCU = CUMap.lookup(TheCU);
813 assert(SPCU && "Unable to find Compile Unit!");
814 constructSubprogramDIE(SPCU, SP);
815 DIE *ScopeDIE = SPCU->getDIE(SP);
816 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
817 DIVariable DV(Variables.getElement(vi));
818 if (!DV.Verify()) continue;
819 DbgVariable *NewVar = new DbgVariable(DV, NULL);
820 if (DIE *VariableDIE =
821 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
822 ScopeDIE->addChild(VariableDIE);
828 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
829 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
830 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
832 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
834 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
835 AE = AbstractSPDies.end(); AI != AE; ++AI) {
836 DIE *ISP = AI->second;
837 if (InlinedSubprogramDIEs.count(ISP))
839 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
842 // Emit DW_AT_containing_type attribute to connect types with their
843 // vtable holding type.
844 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
845 CUE = CUMap.end(); CUI != CUE; ++CUI) {
846 CompileUnit *TheCU = CUI->second;
847 TheCU->constructContainingTypeDIEs();
850 // Standard sections final addresses.
851 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
852 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
853 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
854 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
856 // End text sections.
857 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
858 Asm->OutStreamer.SwitchSection(SectionMap[I]);
859 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
862 // Compute DIE offsets and sizes.
863 computeSizeAndOffsets();
865 // Emit all the DIEs into a debug info section
868 // Corresponding abbreviations into a abbrev section.
871 // Emit info into the dwarf accelerator table sections.
872 if (useDwarfAccelTables()) {
875 emitAccelNamespaces();
879 // Emit info into a debug pubtypes section.
880 // TODO: When we don't need the option anymore we can
881 // remove all of the code that adds to the table.
882 if (useDarwinGDBCompat())
885 // Emit info into a debug loc section.
888 // Emit info into a debug aranges section.
891 // Emit info into a debug ranges section.
894 // Emit info into a debug macinfo section.
898 // TODO: When we don't need the option anymore we
899 // can remove all of the code that this section
901 if (useDarwinGDBCompat())
902 emitDebugInlineInfo();
904 // Emit info into a debug str section.
908 DeleteContainerSeconds(DeadFnScopeMap);
910 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
911 E = CUMap.end(); I != E; ++I)
913 FirstCU = NULL; // Reset for the next Module, if any.
916 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
917 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
919 LLVMContext &Ctx = DV->getContext();
920 // More then one inlined variable corresponds to one abstract variable.
921 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
922 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
924 return AbsDbgVariable;
926 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
930 AbsDbgVariable = new DbgVariable(Var, NULL);
931 addScopeVariable(Scope, AbsDbgVariable);
932 AbstractVariables[Var] = AbsDbgVariable;
933 return AbsDbgVariable;
936 /// addCurrentFnArgument - If Var is a current function argument then add
937 /// it to CurrentFnArguments list.
938 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
939 DbgVariable *Var, LexicalScope *Scope) {
940 if (!LScopes.isCurrentFunctionScope(Scope))
942 DIVariable DV = Var->getVariable();
943 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
945 unsigned ArgNo = DV.getArgNumber();
949 size_t Size = CurrentFnArguments.size();
951 CurrentFnArguments.resize(MF->getFunction()->arg_size());
952 // llvm::Function argument size is not good indicator of how many
953 // arguments does the function have at source level.
955 CurrentFnArguments.resize(ArgNo * 2);
956 CurrentFnArguments[ArgNo - 1] = Var;
960 /// collectVariableInfoFromMMITable - Collect variable information from
961 /// side table maintained by MMI.
963 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
964 SmallPtrSet<const MDNode *, 16> &Processed) {
965 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
966 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
967 VE = VMap.end(); VI != VE; ++VI) {
968 const MDNode *Var = VI->first;
970 Processed.insert(Var);
972 const std::pair<unsigned, DebugLoc> &VP = VI->second;
974 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
976 // If variable scope is not found then skip this variable.
980 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
981 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
982 RegVar->setFrameIndex(VP.first);
983 if (!addCurrentFnArgument(MF, RegVar, Scope))
984 addScopeVariable(Scope, RegVar);
986 AbsDbgVariable->setFrameIndex(VP.first);
990 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
991 /// DBG_VALUE instruction, is in a defined reg.
992 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
993 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
994 return MI->getNumOperands() == 3 &&
995 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
996 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
999 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
1001 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1002 const MCSymbol *FLabel,
1003 const MCSymbol *SLabel,
1004 const MachineInstr *MI) {
1005 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1007 if (MI->getNumOperands() != 3) {
1008 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1009 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1011 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1012 MachineLocation MLoc;
1013 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1014 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1016 if (MI->getOperand(0).isImm())
1017 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1018 if (MI->getOperand(0).isFPImm())
1019 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1020 if (MI->getOperand(0).isCImm())
1021 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1023 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1026 /// collectVariableInfo - Find variables for each lexical scope.
1028 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1029 SmallPtrSet<const MDNode *, 16> &Processed) {
1031 /// collection info from MMI table.
1032 collectVariableInfoFromMMITable(MF, Processed);
1034 for (SmallVectorImpl<const MDNode*>::const_iterator
1035 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1037 const MDNode *Var = *UVI;
1038 if (Processed.count(Var))
1041 // History contains relevant DBG_VALUE instructions for Var and instructions
1043 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1044 if (History.empty())
1046 const MachineInstr *MInsn = History.front();
1049 LexicalScope *Scope = NULL;
1050 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1051 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1052 Scope = LScopes.getCurrentFunctionScope();
1054 if (DV.getVersion() <= LLVMDebugVersion9)
1055 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1057 if (MDNode *IA = DV.getInlinedAt())
1058 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1060 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1063 // If variable scope is not found then skip this variable.
1067 Processed.insert(DV);
1068 assert(MInsn->isDebugValue() && "History must begin with debug value");
1069 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1070 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1071 if (!addCurrentFnArgument(MF, RegVar, Scope))
1072 addScopeVariable(Scope, RegVar);
1074 AbsVar->setMInsn(MInsn);
1076 // Simplify ranges that are fully coalesced.
1077 if (History.size() <= 1 || (History.size() == 2 &&
1078 MInsn->isIdenticalTo(History.back()))) {
1079 RegVar->setMInsn(MInsn);
1083 // handle multiple DBG_VALUE instructions describing one variable.
1084 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1086 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1087 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1088 const MachineInstr *Begin = *HI;
1089 assert(Begin->isDebugValue() && "Invalid History entry");
1091 // Check if DBG_VALUE is truncating a range.
1092 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1093 && !Begin->getOperand(0).getReg())
1096 // Compute the range for a register location.
1097 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1098 const MCSymbol *SLabel = 0;
1101 // If Begin is the last instruction in History then its value is valid
1102 // until the end of the function.
1103 SLabel = FunctionEndSym;
1105 const MachineInstr *End = HI[1];
1106 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1107 << "\t" << *Begin << "\t" << *End << "\n");
1108 if (End->isDebugValue())
1109 SLabel = getLabelBeforeInsn(End);
1111 // End is a normal instruction clobbering the range.
1112 SLabel = getLabelAfterInsn(End);
1113 assert(SLabel && "Forgot label after clobber instruction");
1118 // The value is valid until the next DBG_VALUE or clobber.
1119 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1122 DotDebugLocEntries.push_back(DotDebugLocEntry());
1125 // Collect info for variables that were optimized out.
1126 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1127 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1128 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1129 DIVariable DV(Variables.getElement(i));
1130 if (!DV || !DV.Verify() || !Processed.insert(DV))
1132 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1133 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1137 /// getLabelBeforeInsn - Return Label preceding the instruction.
1138 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1139 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1140 assert(Label && "Didn't insert label before instruction");
1144 /// getLabelAfterInsn - Return Label immediately following the instruction.
1145 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1146 return LabelsAfterInsn.lookup(MI);
1149 /// beginInstruction - Process beginning of an instruction.
1150 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1151 // Check if source location changes, but ignore DBG_VALUE locations.
1152 if (!MI->isDebugValue()) {
1153 DebugLoc DL = MI->getDebugLoc();
1154 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1157 if (DL == PrologEndLoc) {
1158 Flags |= DWARF2_FLAG_PROLOGUE_END;
1159 PrologEndLoc = DebugLoc();
1161 if (PrologEndLoc.isUnknown())
1162 Flags |= DWARF2_FLAG_IS_STMT;
1164 if (!DL.isUnknown()) {
1165 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1166 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1168 recordSourceLine(0, 0, 0, 0);
1172 // Insert labels where requested.
1173 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1174 LabelsBeforeInsn.find(MI);
1177 if (I == LabelsBeforeInsn.end())
1180 // Label already assigned.
1185 PrevLabel = MMI->getContext().CreateTempSymbol();
1186 Asm->OutStreamer.EmitLabel(PrevLabel);
1188 I->second = PrevLabel;
1191 /// endInstruction - Process end of an instruction.
1192 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1193 // Don't create a new label after DBG_VALUE instructions.
1194 // They don't generate code.
1195 if (!MI->isDebugValue())
1198 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1199 LabelsAfterInsn.find(MI);
1202 if (I == LabelsAfterInsn.end())
1205 // Label already assigned.
1209 // We need a label after this instruction.
1211 PrevLabel = MMI->getContext().CreateTempSymbol();
1212 Asm->OutStreamer.EmitLabel(PrevLabel);
1214 I->second = PrevLabel;
1217 /// identifyScopeMarkers() -
1218 /// Each LexicalScope has first instruction and last instruction to mark
1219 /// beginning and end of a scope respectively. Create an inverse map that list
1220 /// scopes starts (and ends) with an instruction. One instruction may start (or
1221 /// end) multiple scopes. Ignore scopes that are not reachable.
1222 void DwarfDebug::identifyScopeMarkers() {
1223 SmallVector<LexicalScope *, 4> WorkList;
1224 WorkList.push_back(LScopes.getCurrentFunctionScope());
1225 while (!WorkList.empty()) {
1226 LexicalScope *S = WorkList.pop_back_val();
1228 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1229 if (!Children.empty())
1230 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1231 SE = Children.end(); SI != SE; ++SI)
1232 WorkList.push_back(*SI);
1234 if (S->isAbstractScope())
1237 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1240 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1241 RE = Ranges.end(); RI != RE; ++RI) {
1242 assert(RI->first && "InsnRange does not have first instruction!");
1243 assert(RI->second && "InsnRange does not have second instruction!");
1244 requestLabelBeforeInsn(RI->first);
1245 requestLabelAfterInsn(RI->second);
1250 /// getScopeNode - Get MDNode for DebugLoc's scope.
1251 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1252 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1253 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1254 return DL.getScope(Ctx);
1257 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1258 /// line number info for the function.
1259 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1260 const MDNode *Scope = getScopeNode(DL, Ctx);
1261 DISubprogram SP = getDISubprogram(Scope);
1263 // Check for number of operands since the compatibility is
1265 if (SP->getNumOperands() > 19)
1266 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1268 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1274 /// beginFunction - Gather pre-function debug information. Assumes being
1275 /// emitted immediately after the function entry point.
1276 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1277 if (!MMI->hasDebugInfo()) return;
1278 LScopes.initialize(*MF);
1279 if (LScopes.empty()) return;
1280 identifyScopeMarkers();
1282 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1283 Asm->getFunctionNumber());
1284 // Assumes in correct section after the entry point.
1285 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1287 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1289 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1290 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1291 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1293 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1295 bool AtBlockEntry = true;
1296 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1298 const MachineInstr *MI = II;
1300 if (MI->isDebugValue()) {
1301 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1303 // Keep track of user variables.
1305 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1307 // Variable is in a register, we need to check for clobbers.
1308 if (isDbgValueInDefinedReg(MI))
1309 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1311 // Check the history of this variable.
1312 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1313 if (History.empty()) {
1314 UserVariables.push_back(Var);
1315 // The first mention of a function argument gets the FunctionBeginSym
1316 // label, so arguments are visible when breaking at function entry.
1318 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1319 DISubprogram(getDISubprogram(DV.getContext()))
1320 .describes(MF->getFunction()))
1321 LabelsBeforeInsn[MI] = FunctionBeginSym;
1323 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1324 const MachineInstr *Prev = History.back();
1325 if (Prev->isDebugValue()) {
1326 // Coalesce identical entries at the end of History.
1327 if (History.size() >= 2 &&
1328 Prev->isIdenticalTo(History[History.size() - 2])) {
1329 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1331 << "\t" << *History[History.size() - 2] << "\n");
1335 // Terminate old register assignments that don't reach MI;
1336 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1337 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1338 isDbgValueInDefinedReg(Prev)) {
1339 // Previous register assignment needs to terminate at the end of
1341 MachineBasicBlock::const_iterator LastMI =
1342 PrevMBB->getLastNonDebugInstr();
1343 if (LastMI == PrevMBB->end()) {
1344 // Drop DBG_VALUE for empty range.
1345 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1346 << "\t" << *Prev << "\n");
1350 // Terminate after LastMI.
1351 History.push_back(LastMI);
1356 History.push_back(MI);
1358 // Not a DBG_VALUE instruction.
1360 AtBlockEntry = false;
1362 // First known non-DBG_VALUE and non-frame setup location marks
1363 // the beginning of the function body.
1364 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1365 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1366 PrologEndLoc = MI->getDebugLoc();
1368 // Check if the instruction clobbers any registers with debug vars.
1369 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1370 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1371 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1373 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1374 AI.isValid(); ++AI) {
1376 const MDNode *Var = LiveUserVar[Reg];
1379 // Reg is now clobbered.
1380 LiveUserVar[Reg] = 0;
1382 // Was MD last defined by a DBG_VALUE referring to Reg?
1383 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1384 if (HistI == DbgValues.end())
1386 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1387 if (History.empty())
1389 const MachineInstr *Prev = History.back();
1390 // Sanity-check: Register assignments are terminated at the end of
1392 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1394 // Is the variable still in Reg?
1395 if (!isDbgValueInDefinedReg(Prev) ||
1396 Prev->getOperand(0).getReg() != Reg)
1398 // Var is clobbered. Make sure the next instruction gets a label.
1399 History.push_back(MI);
1406 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1408 SmallVectorImpl<const MachineInstr*> &History = I->second;
1409 if (History.empty())
1412 // Make sure the final register assignments are terminated.
1413 const MachineInstr *Prev = History.back();
1414 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1415 const MachineBasicBlock *PrevMBB = Prev->getParent();
1416 MachineBasicBlock::const_iterator LastMI =
1417 PrevMBB->getLastNonDebugInstr();
1418 if (LastMI == PrevMBB->end())
1419 // Drop DBG_VALUE for empty range.
1422 // Terminate after LastMI.
1423 History.push_back(LastMI);
1426 // Request labels for the full history.
1427 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1428 const MachineInstr *MI = History[i];
1429 if (MI->isDebugValue())
1430 requestLabelBeforeInsn(MI);
1432 requestLabelAfterInsn(MI);
1436 PrevInstLoc = DebugLoc();
1437 PrevLabel = FunctionBeginSym;
1439 // Record beginning of function.
1440 if (!PrologEndLoc.isUnknown()) {
1441 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1442 MF->getFunction()->getContext());
1443 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1444 FnStartDL.getScope(MF->getFunction()->getContext()),
1449 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1450 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1451 ScopeVariables[LS].push_back(Var);
1452 // Vars.push_back(Var);
1455 /// endFunction - Gather and emit post-function debug information.
1457 void DwarfDebug::endFunction(const MachineFunction *MF) {
1458 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1460 // Define end label for subprogram.
1461 FunctionEndSym = Asm->GetTempSymbol("func_end",
1462 Asm->getFunctionNumber());
1463 // Assumes in correct section after the entry point.
1464 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1466 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1467 collectVariableInfo(MF, ProcessedVars);
1469 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1470 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1471 assert(TheCU && "Unable to find compile unit!");
1473 // Construct abstract scopes.
1474 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1475 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1476 LexicalScope *AScope = AList[i];
1477 DISubprogram SP(AScope->getScopeNode());
1479 // Collect info for variables that were optimized out.
1480 DIArray Variables = SP.getVariables();
1481 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1482 DIVariable DV(Variables.getElement(i));
1483 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1485 // Check that DbgVariable for DV wasn't created earlier, when
1486 // findAbstractVariable() was called for inlined instance of DV.
1487 LLVMContext &Ctx = DV->getContext();
1488 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1489 if (AbstractVariables.lookup(CleanDV))
1491 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1492 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1495 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1496 constructScopeDIE(TheCU, AScope);
1499 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1501 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1502 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1504 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1505 MMI->getFrameMoves()));
1508 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1509 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1510 DeleteContainerPointers(I->second);
1511 ScopeVariables.clear();
1512 DeleteContainerPointers(CurrentFnArguments);
1513 UserVariables.clear();
1515 AbstractVariables.clear();
1516 LabelsBeforeInsn.clear();
1517 LabelsAfterInsn.clear();
1521 /// recordSourceLine - Register a source line with debug info. Returns the
1522 /// unique label that was emitted and which provides correspondence to
1523 /// the source line list.
1524 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1530 DIDescriptor Scope(S);
1532 if (Scope.isCompileUnit()) {
1533 DICompileUnit CU(S);
1534 Fn = CU.getFilename();
1535 Dir = CU.getDirectory();
1536 } else if (Scope.isFile()) {
1538 Fn = F.getFilename();
1539 Dir = F.getDirectory();
1540 } else if (Scope.isSubprogram()) {
1542 Fn = SP.getFilename();
1543 Dir = SP.getDirectory();
1544 } else if (Scope.isLexicalBlockFile()) {
1545 DILexicalBlockFile DBF(S);
1546 Fn = DBF.getFilename();
1547 Dir = DBF.getDirectory();
1548 } else if (Scope.isLexicalBlock()) {
1549 DILexicalBlock DB(S);
1550 Fn = DB.getFilename();
1551 Dir = DB.getDirectory();
1553 llvm_unreachable("Unexpected scope info");
1555 Src = GetOrCreateSourceID(Fn, Dir);
1557 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1560 //===----------------------------------------------------------------------===//
1562 //===----------------------------------------------------------------------===//
1564 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1567 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1568 // Get the children.
1569 const std::vector<DIE *> &Children = Die->getChildren();
1571 // Record the abbreviation.
1572 assignAbbrevNumber(Die->getAbbrev());
1574 // Get the abbreviation for this DIE.
1575 unsigned AbbrevNumber = Die->getAbbrevNumber();
1576 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1579 Die->setOffset(Offset);
1581 // Start the size with the size of abbreviation code.
1582 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1584 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1585 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1587 // Size the DIE attribute values.
1588 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1589 // Size attribute value.
1590 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1592 // Size the DIE children if any.
1593 if (!Children.empty()) {
1594 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1595 "Children flag not set");
1597 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1598 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1600 // End of children marker.
1601 Offset += sizeof(int8_t);
1604 Die->setSize(Offset - Die->getOffset());
1608 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1610 void DwarfDebug::computeSizeAndOffsets() {
1611 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1612 E = CUMap.end(); I != E; ++I) {
1613 // Compute size of compile unit header.
1615 sizeof(int32_t) + // Length of Compilation Unit Info
1616 sizeof(int16_t) + // DWARF version number
1617 sizeof(int32_t) + // Offset Into Abbrev. Section
1618 sizeof(int8_t); // Pointer Size (in bytes)
1619 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1623 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1624 /// the start of each one.
1625 void DwarfDebug::EmitSectionLabels() {
1626 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1628 // Dwarf sections base addresses.
1629 DwarfInfoSectionSym =
1630 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1631 DwarfAbbrevSectionSym =
1632 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1633 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1635 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1636 EmitSectionSym(Asm, MacroInfo);
1638 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1639 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1640 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1641 DwarfStrSectionSym =
1642 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1643 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1646 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1647 "section_debug_loc");
1649 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1650 EmitSectionSym(Asm, TLOF.getDataSection());
1653 /// emitDIE - Recursively emits a debug information entry.
1655 void DwarfDebug::emitDIE(DIE *Die) {
1656 // Get the abbreviation for this DIE.
1657 unsigned AbbrevNumber = Die->getAbbrevNumber();
1658 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1660 // Emit the code (index) for the abbreviation.
1661 if (Asm->isVerbose())
1662 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1663 Twine::utohexstr(Die->getOffset()) + ":0x" +
1664 Twine::utohexstr(Die->getSize()) + " " +
1665 dwarf::TagString(Abbrev->getTag()));
1666 Asm->EmitULEB128(AbbrevNumber);
1668 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1669 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1671 // Emit the DIE attribute values.
1672 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1673 unsigned Attr = AbbrevData[i].getAttribute();
1674 unsigned Form = AbbrevData[i].getForm();
1675 assert(Form && "Too many attributes for DIE (check abbreviation)");
1677 if (Asm->isVerbose())
1678 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1681 case dwarf::DW_AT_abstract_origin: {
1682 DIEEntry *E = cast<DIEEntry>(Values[i]);
1683 DIE *Origin = E->getEntry();
1684 unsigned Addr = Origin->getOffset();
1685 Asm->EmitInt32(Addr);
1688 case dwarf::DW_AT_ranges: {
1689 // DW_AT_range Value encodes offset in debug_range section.
1690 DIEInteger *V = cast<DIEInteger>(Values[i]);
1692 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1693 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1697 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1699 DwarfDebugRangeSectionSym,
1704 case dwarf::DW_AT_location: {
1705 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1706 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1707 Asm->EmitLabelReference(L->getValue(), 4);
1709 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1711 Values[i]->EmitValue(Asm, Form);
1715 case dwarf::DW_AT_accessibility: {
1716 if (Asm->isVerbose()) {
1717 DIEInteger *V = cast<DIEInteger>(Values[i]);
1718 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1720 Values[i]->EmitValue(Asm, Form);
1724 // Emit an attribute using the defined form.
1725 Values[i]->EmitValue(Asm, Form);
1730 // Emit the DIE children if any.
1731 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1732 const std::vector<DIE *> &Children = Die->getChildren();
1734 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1735 emitDIE(Children[j]);
1737 if (Asm->isVerbose())
1738 Asm->OutStreamer.AddComment("End Of Children Mark");
1743 /// emitDebugInfo - Emit the debug info section.
1745 void DwarfDebug::emitDebugInfo() {
1746 // Start debug info section.
1747 Asm->OutStreamer.SwitchSection(
1748 Asm->getObjFileLowering().getDwarfInfoSection());
1749 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1750 E = CUMap.end(); I != E; ++I) {
1751 CompileUnit *TheCU = I->second;
1752 DIE *Die = TheCU->getCUDie();
1754 // Emit the compile units header.
1755 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1758 // Emit size of content not including length itself
1759 unsigned ContentSize = Die->getSize() +
1760 sizeof(int16_t) + // DWARF version number
1761 sizeof(int32_t) + // Offset Into Abbrev. Section
1762 sizeof(int8_t); // Pointer Size (in bytes)
1764 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1765 Asm->EmitInt32(ContentSize);
1766 Asm->OutStreamer.AddComment("DWARF version number");
1767 Asm->EmitInt16(dwarf::DWARF_VERSION);
1768 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1769 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1770 DwarfAbbrevSectionSym);
1771 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1772 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1775 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1779 /// emitAbbreviations - Emit the abbreviation section.
1781 void DwarfDebug::emitAbbreviations() const {
1782 // Check to see if it is worth the effort.
1783 if (!Abbreviations.empty()) {
1784 // Start the debug abbrev section.
1785 Asm->OutStreamer.SwitchSection(
1786 Asm->getObjFileLowering().getDwarfAbbrevSection());
1788 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1790 // For each abbrevation.
1791 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1792 // Get abbreviation data
1793 const DIEAbbrev *Abbrev = Abbreviations[i];
1795 // Emit the abbrevations code (base 1 index.)
1796 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1798 // Emit the abbreviations data.
1802 // Mark end of abbreviations.
1803 Asm->EmitULEB128(0, "EOM(3)");
1805 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1809 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1810 /// the line matrix.
1812 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1813 // Define last address of section.
1814 Asm->OutStreamer.AddComment("Extended Op");
1817 Asm->OutStreamer.AddComment("Op size");
1818 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1819 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1820 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1822 Asm->OutStreamer.AddComment("Section end label");
1824 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1825 Asm->getDataLayout().getPointerSize(),
1828 // Mark end of matrix.
1829 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1835 /// emitAccelNames - Emit visible names into a hashed accelerator table
1837 void DwarfDebug::emitAccelNames() {
1838 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1839 dwarf::DW_FORM_data4));
1840 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1841 E = CUMap.end(); I != E; ++I) {
1842 CompileUnit *TheCU = I->second;
1843 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1844 for (StringMap<std::vector<DIE*> >::const_iterator
1845 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1846 const char *Name = GI->getKeyData();
1847 const std::vector<DIE *> &Entities = GI->second;
1848 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1849 DE = Entities.end(); DI != DE; ++DI)
1850 AT.AddName(Name, (*DI));
1854 AT.FinalizeTable(Asm, "Names");
1855 Asm->OutStreamer.SwitchSection(
1856 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1857 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1858 Asm->OutStreamer.EmitLabel(SectionBegin);
1860 // Emit the full data.
1861 AT.Emit(Asm, SectionBegin, this);
1864 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1865 /// accelerator table section.
1866 void DwarfDebug::emitAccelObjC() {
1867 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1868 dwarf::DW_FORM_data4));
1869 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1870 E = CUMap.end(); I != E; ++I) {
1871 CompileUnit *TheCU = I->second;
1872 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1873 for (StringMap<std::vector<DIE*> >::const_iterator
1874 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1875 const char *Name = GI->getKeyData();
1876 const std::vector<DIE *> &Entities = GI->second;
1877 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1878 DE = Entities.end(); DI != DE; ++DI)
1879 AT.AddName(Name, (*DI));
1883 AT.FinalizeTable(Asm, "ObjC");
1884 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1885 .getDwarfAccelObjCSection());
1886 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1887 Asm->OutStreamer.EmitLabel(SectionBegin);
1889 // Emit the full data.
1890 AT.Emit(Asm, SectionBegin, this);
1893 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1895 void DwarfDebug::emitAccelNamespaces() {
1896 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1897 dwarf::DW_FORM_data4));
1898 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1899 E = CUMap.end(); I != E; ++I) {
1900 CompileUnit *TheCU = I->second;
1901 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
1902 for (StringMap<std::vector<DIE*> >::const_iterator
1903 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1904 const char *Name = GI->getKeyData();
1905 const std::vector<DIE *> &Entities = GI->second;
1906 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1907 DE = Entities.end(); DI != DE; ++DI)
1908 AT.AddName(Name, (*DI));
1912 AT.FinalizeTable(Asm, "namespac");
1913 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1914 .getDwarfAccelNamespaceSection());
1915 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1916 Asm->OutStreamer.EmitLabel(SectionBegin);
1918 // Emit the full data.
1919 AT.Emit(Asm, SectionBegin, this);
1922 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1923 void DwarfDebug::emitAccelTypes() {
1924 std::vector<DwarfAccelTable::Atom> Atoms;
1925 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1926 dwarf::DW_FORM_data4));
1927 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
1928 dwarf::DW_FORM_data2));
1929 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
1930 dwarf::DW_FORM_data1));
1931 DwarfAccelTable AT(Atoms);
1932 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1933 E = CUMap.end(); I != E; ++I) {
1934 CompileUnit *TheCU = I->second;
1935 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
1936 = TheCU->getAccelTypes();
1937 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
1938 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1939 const char *Name = GI->getKeyData();
1940 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
1941 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
1942 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
1943 AT.AddName(Name, (*DI).first, (*DI).second);
1947 AT.FinalizeTable(Asm, "types");
1948 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1949 .getDwarfAccelTypesSection());
1950 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1951 Asm->OutStreamer.EmitLabel(SectionBegin);
1953 // Emit the full data.
1954 AT.Emit(Asm, SectionBegin, this);
1957 void DwarfDebug::emitDebugPubTypes() {
1958 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1959 E = CUMap.end(); I != E; ++I) {
1960 CompileUnit *TheCU = I->second;
1961 // Start the dwarf pubtypes section.
1962 Asm->OutStreamer.SwitchSection(
1963 Asm->getObjFileLowering().getDwarfPubTypesSection());
1964 Asm->OutStreamer.AddComment("Length of Public Types Info");
1965 Asm->EmitLabelDifference(
1966 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1967 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1969 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1972 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1973 Asm->EmitInt16(dwarf::DWARF_VERSION);
1975 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1976 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1977 DwarfInfoSectionSym);
1979 Asm->OutStreamer.AddComment("Compilation Unit Length");
1980 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1981 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1984 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1985 for (StringMap<DIE*>::const_iterator
1986 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1987 const char *Name = GI->getKeyData();
1988 DIE *Entity = GI->second;
1990 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1991 Asm->EmitInt32(Entity->getOffset());
1993 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1994 // Emit the name with a terminating null byte.
1995 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1998 Asm->OutStreamer.AddComment("End Mark");
2000 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2005 /// emitDebugStr - Emit visible names into a debug str section.
2007 void DwarfDebug::emitDebugStr() {
2008 // Check to see if it is worth the effort.
2009 if (StringPool.empty()) return;
2011 // Start the dwarf str section.
2012 Asm->OutStreamer.SwitchSection(
2013 Asm->getObjFileLowering().getDwarfStrSection());
2015 // Get all of the string pool entries and put them in an array by their ID so
2016 // we can sort them.
2017 SmallVector<std::pair<unsigned,
2018 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2020 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2021 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
2022 Entries.push_back(std::make_pair(I->second.second, &*I));
2024 array_pod_sort(Entries.begin(), Entries.end());
2026 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2027 // Emit a label for reference from debug information entries.
2028 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2030 // Emit the string itself with a terminating null byte.
2031 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2032 Entries[i].second->getKeyLength()+1),
2037 /// emitDebugLoc - Emit visible names into a debug loc section.
2039 void DwarfDebug::emitDebugLoc() {
2040 if (DotDebugLocEntries.empty())
2043 for (SmallVector<DotDebugLocEntry, 4>::iterator
2044 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2046 DotDebugLocEntry &Entry = *I;
2047 if (I + 1 != DotDebugLocEntries.end())
2051 // Start the dwarf loc section.
2052 Asm->OutStreamer.SwitchSection(
2053 Asm->getObjFileLowering().getDwarfLocSection());
2054 unsigned char Size = Asm->getDataLayout().getPointerSize();
2055 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2057 for (SmallVector<DotDebugLocEntry, 4>::iterator
2058 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2059 I != E; ++I, ++index) {
2060 DotDebugLocEntry &Entry = *I;
2061 if (Entry.isMerged()) continue;
2062 if (Entry.isEmpty()) {
2063 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2064 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2065 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2067 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2068 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2069 DIVariable DV(Entry.Variable);
2070 Asm->OutStreamer.AddComment("Loc expr size");
2071 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2072 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2073 Asm->EmitLabelDifference(end, begin, 2);
2074 Asm->OutStreamer.EmitLabel(begin);
2075 if (Entry.isInt()) {
2076 DIBasicType BTy(DV.getType());
2078 (BTy.getEncoding() == dwarf::DW_ATE_signed
2079 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2080 Asm->OutStreamer.AddComment("DW_OP_consts");
2081 Asm->EmitInt8(dwarf::DW_OP_consts);
2082 Asm->EmitSLEB128(Entry.getInt());
2084 Asm->OutStreamer.AddComment("DW_OP_constu");
2085 Asm->EmitInt8(dwarf::DW_OP_constu);
2086 Asm->EmitULEB128(Entry.getInt());
2088 } else if (Entry.isLocation()) {
2089 if (!DV.hasComplexAddress())
2091 Asm->EmitDwarfRegOp(Entry.Loc);
2093 // Complex address entry.
2094 unsigned N = DV.getNumAddrElements();
2096 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2097 if (Entry.Loc.getOffset()) {
2099 Asm->EmitDwarfRegOp(Entry.Loc);
2100 Asm->OutStreamer.AddComment("DW_OP_deref");
2101 Asm->EmitInt8(dwarf::DW_OP_deref);
2102 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2103 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2104 Asm->EmitSLEB128(DV.getAddrElement(1));
2106 // If first address element is OpPlus then emit
2107 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2108 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2109 Asm->EmitDwarfRegOp(Loc);
2113 Asm->EmitDwarfRegOp(Entry.Loc);
2116 // Emit remaining complex address elements.
2117 for (; i < N; ++i) {
2118 uint64_t Element = DV.getAddrElement(i);
2119 if (Element == DIBuilder::OpPlus) {
2120 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2121 Asm->EmitULEB128(DV.getAddrElement(++i));
2122 } else if (Element == DIBuilder::OpDeref) {
2123 if (!Entry.Loc.isReg())
2124 Asm->EmitInt8(dwarf::DW_OP_deref);
2126 llvm_unreachable("unknown Opcode found in complex address");
2130 // else ... ignore constant fp. There is not any good way to
2131 // to represent them here in dwarf.
2132 Asm->OutStreamer.EmitLabel(end);
2137 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2139 void DwarfDebug::EmitDebugARanges() {
2140 // Start the dwarf aranges section.
2141 Asm->OutStreamer.SwitchSection(
2142 Asm->getObjFileLowering().getDwarfARangesSection());
2145 /// emitDebugRanges - Emit visible names into a debug ranges section.
2147 void DwarfDebug::emitDebugRanges() {
2148 // Start the dwarf ranges section.
2149 Asm->OutStreamer.SwitchSection(
2150 Asm->getObjFileLowering().getDwarfRangesSection());
2151 unsigned char Size = Asm->getDataLayout().getPointerSize();
2152 for (SmallVector<const MCSymbol *, 8>::iterator
2153 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2156 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2158 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2162 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2164 void DwarfDebug::emitDebugMacInfo() {
2165 if (const MCSection *LineInfo =
2166 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2167 // Start the dwarf macinfo section.
2168 Asm->OutStreamer.SwitchSection(LineInfo);
2172 /// emitDebugInlineInfo - Emit inline info using following format.
2174 /// 1. length of section
2175 /// 2. Dwarf version number
2176 /// 3. address size.
2178 /// Entries (one "entry" for each function that was inlined):
2180 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2181 /// otherwise offset into __debug_str for regular function name.
2182 /// 2. offset into __debug_str section for regular function name.
2183 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2184 /// instances for the function.
2186 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2187 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2188 /// __debug_info section, and the low_pc is the starting address for the
2189 /// inlining instance.
2190 void DwarfDebug::emitDebugInlineInfo() {
2191 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2197 Asm->OutStreamer.SwitchSection(
2198 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2200 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2201 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2202 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2204 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2206 Asm->OutStreamer.AddComment("Dwarf Version");
2207 Asm->EmitInt16(dwarf::DWARF_VERSION);
2208 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2209 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2211 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2212 E = InlinedSPNodes.end(); I != E; ++I) {
2214 const MDNode *Node = *I;
2215 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2216 = InlineInfo.find(Node);
2217 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2218 DISubprogram SP(Node);
2219 StringRef LName = SP.getLinkageName();
2220 StringRef Name = SP.getName();
2222 Asm->OutStreamer.AddComment("MIPS linkage name");
2224 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2226 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2227 DwarfStrSectionSym);
2229 Asm->OutStreamer.AddComment("Function name");
2230 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2231 Asm->EmitULEB128(Labels.size(), "Inline count");
2233 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2234 LE = Labels.end(); LI != LE; ++LI) {
2235 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2236 Asm->EmitInt32(LI->second->getOffset());
2238 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2239 Asm->OutStreamer.EmitSymbolValue(LI->first,
2240 Asm->getDataLayout().getPointerSize(),0);
2244 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));