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."),
57 static cl::opt<bool> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
58 cl::desc("Output prototype dwarf accelerator tables."),
61 static cl::opt<bool> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
62 cl::desc("Compatibility with Darwin gdb."),
66 const char *DWARFGroupName = "DWARF Emission";
67 const char *DbgTimerName = "DWARF Debug Writer";
68 } // end anonymous namespace
70 //===----------------------------------------------------------------------===//
72 /// Configuration values for initial hash set sizes (log2).
74 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
78 DIType DbgVariable::getType() const {
79 DIType Ty = Var.getType();
80 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
82 if (Var.isBlockByrefVariable()) {
83 /* Byref variables, in Blocks, are declared by the programmer as
84 "SomeType VarName;", but the compiler creates a
85 __Block_byref_x_VarName struct, and gives the variable VarName
86 either the struct, or a pointer to the struct, as its type. This
87 is necessary for various behind-the-scenes things the compiler
88 needs to do with by-reference variables in blocks.
90 However, as far as the original *programmer* is concerned, the
91 variable should still have type 'SomeType', as originally declared.
93 The following function dives into the __Block_byref_x_VarName
94 struct to find the original type of the variable. This will be
95 passed back to the code generating the type for the Debug
96 Information Entry for the variable 'VarName'. 'VarName' will then
97 have the original type 'SomeType' in its debug information.
99 The original type 'SomeType' will be the type of the field named
100 'VarName' inside the __Block_byref_x_VarName struct.
102 NOTE: In order for this to not completely fail on the debugger
103 side, the Debug Information Entry for the variable VarName needs to
104 have a DW_AT_location that tells the debugger how to unwind through
105 the pointers and __Block_byref_x_VarName struct to find the actual
106 value of the variable. The function addBlockByrefType does this. */
108 unsigned tag = Ty.getTag();
110 if (tag == dwarf::DW_TAG_pointer_type) {
111 DIDerivedType DTy = DIDerivedType(Ty);
112 subType = DTy.getTypeDerivedFrom();
115 DICompositeType blockStruct = DICompositeType(subType);
116 DIArray Elements = blockStruct.getTypeArray();
118 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
119 DIDescriptor Element = Elements.getElement(i);
120 DIDerivedType DT = DIDerivedType(Element);
121 if (getName() == DT.getName())
122 return (DT.getTypeDerivedFrom());
128 } // end llvm namespace
130 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
131 : Asm(A), MMI(Asm->MMI), FirstCU(0),
132 AbbreviationsSet(InitAbbreviationsSetSize),
133 SourceIdMap(DIEValueAllocator), StringPool(DIEValueAllocator),
135 NextStringPoolNumber = 0;
137 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
138 DwarfStrSectionSym = TextSectionSym = 0;
139 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
140 FunctionBeginSym = FunctionEndSym = 0;
142 // Turn on accelerator tables and older gdb compatibility
144 if (Triple(M->getTargetTriple()).isOSDarwin()) {
145 DwarfAccelTables = true;
146 DarwinGDBCompat = true;
150 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
154 DwarfDebug::~DwarfDebug() {
157 /// EmitSectionSym - Switch to the specified MCSection and emit an assembler
158 /// temporary label to it if SymbolStem is specified.
159 static MCSymbol *EmitSectionSym(AsmPrinter *Asm, const MCSection *Section,
160 const char *SymbolStem = 0) {
161 Asm->OutStreamer.SwitchSection(Section);
162 if (!SymbolStem) return 0;
164 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
165 Asm->OutStreamer.EmitLabel(TmpSym);
169 MCSymbol *DwarfDebug::getStringPool() {
170 return Asm->GetTempSymbol("section_str");
173 MCSymbol *DwarfDebug::getStringPoolEntry(StringRef Str) {
174 std::pair<MCSymbol*, unsigned> &Entry = StringPool[Str];
175 if (Entry.first) return Entry.first;
177 Entry.second = NextStringPoolNumber++;
178 return Entry.first = Asm->GetTempSymbol("string", Entry.second);
181 /// assignAbbrevNumber - Define a unique number for the abbreviation.
183 void DwarfDebug::assignAbbrevNumber(DIEAbbrev &Abbrev) {
184 // Profile the node so that we can make it unique.
188 // Check the set for priors.
189 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
191 // If it's newly added.
192 if (InSet == &Abbrev) {
193 // Add to abbreviation list.
194 Abbreviations.push_back(&Abbrev);
196 // Assign the vector position + 1 as its number.
197 Abbrev.setNumber(Abbreviations.size());
199 // Assign existing abbreviation number.
200 Abbrev.setNumber(InSet->getNumber());
204 /// getRealLinkageName - If special LLVM prefix that is used to inform the asm
205 /// printer to not emit usual symbol prefix before the symbol name is used then
206 /// return linkage name after skipping this special LLVM prefix.
207 static StringRef getRealLinkageName(StringRef LinkageName) {
209 if (LinkageName.startswith(StringRef(&One, 1)))
210 return LinkageName.substr(1);
214 static bool isObjCClass(StringRef Name) {
215 return Name.startswith("+") || Name.startswith("-");
218 static bool hasObjCCategory(StringRef Name) {
219 if (!isObjCClass(Name)) return false;
221 size_t pos = Name.find(')');
222 if (pos != std::string::npos) {
223 if (Name[pos+1] != ' ') return false;
229 static void getObjCClassCategory(StringRef In, StringRef &Class,
230 StringRef &Category) {
231 if (!hasObjCCategory(In)) {
232 Class = In.slice(In.find('[') + 1, In.find(' '));
237 Class = In.slice(In.find('[') + 1, In.find('('));
238 Category = In.slice(In.find('[') + 1, In.find(' '));
242 static StringRef getObjCMethodName(StringRef In) {
243 return In.slice(In.find(' ') + 1, In.find(']'));
246 // Add the various names to the Dwarf accelerator table names.
247 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
249 if (!SP.isDefinition()) return;
251 TheCU->addAccelName(SP.getName(), Die);
253 // If the linkage name is different than the name, go ahead and output
254 // that as well into the name table.
255 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
256 TheCU->addAccelName(SP.getLinkageName(), Die);
258 // If this is an Objective-C selector name add it to the ObjC accelerator
260 if (isObjCClass(SP.getName())) {
261 StringRef Class, Category;
262 getObjCClassCategory(SP.getName(), Class, Category);
263 TheCU->addAccelObjC(Class, Die);
265 TheCU->addAccelObjC(Category, Die);
266 // Also add the base method name to the name table.
267 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
271 /// updateSubprogramScopeDIE - Find DIE for the given subprogram and
272 /// attach appropriate DW_AT_low_pc and DW_AT_high_pc attributes.
273 /// If there are global variables in this scope then create and insert
274 /// DIEs for these variables.
275 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
276 const MDNode *SPNode) {
277 DIE *SPDie = SPCU->getDIE(SPNode);
279 assert(SPDie && "Unable to find subprogram DIE!");
280 DISubprogram SP(SPNode);
282 DISubprogram SPDecl = SP.getFunctionDeclaration();
283 if (!SPDecl.isSubprogram()) {
284 // There is not any need to generate specification DIE for a function
285 // defined at compile unit level. If a function is defined inside another
286 // function then gdb prefers the definition at top level and but does not
287 // expect specification DIE in parent function. So avoid creating
288 // specification DIE for a function defined inside a function.
289 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
290 !SP.getContext().isFile() &&
291 !isSubprogramContext(SP.getContext())) {
292 SPCU->addUInt(SPDie, dwarf::DW_AT_declaration, dwarf::DW_FORM_flag, 1);
295 DICompositeType SPTy = SP.getType();
296 DIArray Args = SPTy.getTypeArray();
297 unsigned SPTag = SPTy.getTag();
298 if (SPTag == dwarf::DW_TAG_subroutine_type)
299 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
300 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
301 DIType ATy = DIType(DIType(Args.getElement(i)));
302 SPCU->addType(Arg, ATy);
303 if (ATy.isArtificial())
304 SPCU->addUInt(Arg, dwarf::DW_AT_artificial, dwarf::DW_FORM_flag, 1);
305 SPDie->addChild(Arg);
307 DIE *SPDeclDie = SPDie;
308 SPDie = new DIE(dwarf::DW_TAG_subprogram);
309 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, dwarf::DW_FORM_ref4,
314 // Pick up abstract subprogram DIE.
315 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
316 SPDie = new DIE(dwarf::DW_TAG_subprogram);
317 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
318 dwarf::DW_FORM_ref4, AbsSPDIE);
322 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
323 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
324 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
325 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
326 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
327 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
328 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
330 // Add name to the name table, we do this here because we're guaranteed
331 // to have concrete versions of our DW_TAG_subprogram nodes.
332 addSubprogramNames(SPCU, SP, SPDie);
337 /// constructLexicalScope - Construct new DW_TAG_lexical_block
338 /// for this scope and attach DW_AT_low_pc/DW_AT_high_pc labels.
339 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
340 LexicalScope *Scope) {
341 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
342 if (Scope->isAbstractScope())
345 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
349 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
350 if (Ranges.size() > 1) {
351 // .debug_range section has not been laid out yet. Emit offset in
352 // .debug_range as a uint, size 4, for now. emitDIE will handle
353 // DW_AT_ranges appropriately.
354 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
355 DebugRangeSymbols.size()
356 * Asm->getTargetData().getPointerSize());
357 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
358 RE = Ranges.end(); RI != RE; ++RI) {
359 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
360 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
362 DebugRangeSymbols.push_back(NULL);
363 DebugRangeSymbols.push_back(NULL);
367 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
368 const MCSymbol *End = getLabelAfterInsn(RI->second);
370 if (End == 0) return 0;
372 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
373 assert(End->isDefined() && "Invalid end label for an inlined scope!");
375 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
376 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
381 /// constructInlinedScopeDIE - This scope represents inlined body of
382 /// a function. Construct DIE to represent this concrete inlined copy
384 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
385 LexicalScope *Scope) {
386 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
387 assert(Ranges.empty() == false &&
388 "LexicalScope does not have instruction markers!");
390 if (!Scope->getScopeNode())
392 DIScope DS(Scope->getScopeNode());
393 DISubprogram InlinedSP = getDISubprogram(DS);
394 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
396 DEBUG(dbgs() << "Unable to find original DIE for inlined subprogram.");
400 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
401 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
402 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
404 if (StartLabel == 0 || EndLabel == 0) {
405 llvm_unreachable("Unexpected Start and End labels for a inlined scope!");
407 assert(StartLabel->isDefined() &&
408 "Invalid starting label for an inlined scope!");
409 assert(EndLabel->isDefined() &&
410 "Invalid end label for an inlined scope!");
412 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
413 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
414 dwarf::DW_FORM_ref4, OriginDIE);
416 if (Ranges.size() > 1) {
417 // .debug_range section has not been laid out yet. Emit offset in
418 // .debug_range as a uint, size 4, for now. emitDIE will handle
419 // DW_AT_ranges appropriately.
420 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
421 DebugRangeSymbols.size()
422 * Asm->getTargetData().getPointerSize());
423 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
424 RE = Ranges.end(); RI != RE; ++RI) {
425 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
426 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
428 DebugRangeSymbols.push_back(NULL);
429 DebugRangeSymbols.push_back(NULL);
431 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
433 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
437 InlinedSubprogramDIEs.insert(OriginDIE);
439 // Track the start label for this inlined function.
440 //.debug_inlined section specification does not clearly state how
441 // to emit inlined scope that is split into multiple instruction ranges.
442 // For now, use first instruction range and emit low_pc/high_pc pair and
443 // corresponding .debug_inlined section entry for this pair.
444 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
445 I = InlineInfo.find(InlinedSP);
447 if (I == InlineInfo.end()) {
448 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
449 InlinedSPNodes.push_back(InlinedSP);
451 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
453 DILocation DL(Scope->getInlinedAt());
454 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
455 GetOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
456 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
458 // Add name to the name table, we do this here because we're guaranteed
459 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
460 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
465 /// constructScopeDIE - Construct a DIE for this scope.
466 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
467 if (!Scope || !Scope->getScopeNode())
470 SmallVector<DIE *, 8> Children;
472 // Collect arguments for current function.
473 if (LScopes.isCurrentFunctionScope(Scope))
474 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
475 if (DbgVariable *ArgDV = CurrentFnArguments[i])
477 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope()))
478 Children.push_back(Arg);
480 // Collect lexical scope children first.
481 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
482 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
484 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope()))
485 Children.push_back(Variable);
486 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
487 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
488 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
489 Children.push_back(Nested);
490 DIScope DS(Scope->getScopeNode());
491 DIE *ScopeDIE = NULL;
492 if (Scope->getInlinedAt())
493 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
494 else if (DS.isSubprogram()) {
495 ProcessedSPNodes.insert(DS);
496 if (Scope->isAbstractScope()) {
497 ScopeDIE = TheCU->getDIE(DS);
498 // Note down abstract DIE.
500 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
503 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
506 // There is no need to emit empty lexical block DIE.
507 if (Children.empty())
509 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
512 if (!ScopeDIE) return NULL;
515 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
516 E = Children.end(); I != E; ++I)
517 ScopeDIE->addChild(*I);
519 if (DS.isSubprogram())
520 TheCU->addPubTypes(DISubprogram(DS));
525 /// GetOrCreateSourceID - Look up the source id with the given directory and
526 /// source file names. If none currently exists, create a new id and insert it
527 /// in the SourceIds map. This can update DirectoryNames and SourceFileNames
529 unsigned DwarfDebug::GetOrCreateSourceID(StringRef FileName,
531 // If FE did not provide a file name, then assume stdin.
532 if (FileName.empty())
533 return GetOrCreateSourceID("<stdin>", StringRef());
535 // TODO: this might not belong here. See if we can factor this better.
536 if (DirName == CompilationDir)
539 unsigned SrcId = SourceIdMap.size()+1;
541 // We look up the file/dir pair by concatenating them with a zero byte.
542 SmallString<128> NamePair;
544 NamePair += '\0'; // Zero bytes are not allowed in paths.
545 NamePair += FileName;
547 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
548 if (Ent.getValue() != SrcId)
549 return Ent.getValue();
551 // Print out a .file directive to specify files for .loc directives.
552 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
557 /// constructCompileUnit - Create new CompileUnit for the given
558 /// metadata node with tag DW_TAG_compile_unit.
559 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
560 DICompileUnit DIUnit(N);
561 StringRef FN = DIUnit.getFilename();
562 CompilationDir = DIUnit.getDirectory();
563 unsigned ID = GetOrCreateSourceID(FN, CompilationDir);
565 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
566 CompileUnit *NewCU = new CompileUnit(ID, DIUnit.getLanguage(), Die, Asm, this);
567 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
568 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
569 DIUnit.getLanguage());
570 NewCU->addString(Die, dwarf::DW_AT_name, FN);
571 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
573 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
574 // DW_AT_stmt_list is a offset of line number information for this
575 // compile unit in debug_line section.
576 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
577 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
578 Asm->GetTempSymbol("section_line"));
580 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
582 if (!CompilationDir.empty())
583 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
584 if (DIUnit.isOptimized())
585 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_optimized, dwarf::DW_FORM_flag, 1);
587 StringRef Flags = DIUnit.getFlags();
589 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
591 if (unsigned RVer = DIUnit.getRunTimeVersion())
592 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
593 dwarf::DW_FORM_data1, RVer);
597 CUMap.insert(std::make_pair(N, NewCU));
601 /// construct SubprogramDIE - Construct subprogram DIE.
602 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
604 CompileUnit *&CURef = SPMap[N];
610 if (!SP.isDefinition())
611 // This is a method declaration which will be handled while constructing
615 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
618 TheCU->insertDIE(N, SubprogramDie);
620 // Add to context owner.
621 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
626 /// collectInfoFromNamedMDNodes - Collect debug info from named mdnodes such
627 /// as llvm.dbg.enum and llvm.dbg.ty
628 void DwarfDebug::collectInfoFromNamedMDNodes(Module *M) {
629 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
630 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
631 const MDNode *N = NMD->getOperand(i);
632 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
633 constructSubprogramDIE(CU, N);
636 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
637 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
638 const MDNode *N = NMD->getOperand(i);
639 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
640 CU->createGlobalVariableDIE(N);
643 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
644 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
645 DIType Ty(NMD->getOperand(i));
646 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
647 CU->getOrCreateTypeDIE(Ty);
650 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
651 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
652 DIType Ty(NMD->getOperand(i));
653 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
654 CU->getOrCreateTypeDIE(Ty);
658 /// collectLegacyDebugInfo - Collect debug info using DebugInfoFinder.
659 /// FIXME - Remove this when dragon-egg and llvm-gcc switch to DIBuilder.
660 bool DwarfDebug::collectLegacyDebugInfo(Module *M) {
661 DebugInfoFinder DbgFinder;
662 DbgFinder.processModule(*M);
664 bool HasDebugInfo = false;
665 // Scan all the compile-units to see if there are any marked as the main
666 // unit. If not, we do not generate debug info.
667 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
668 E = DbgFinder.compile_unit_end(); I != E; ++I) {
669 if (DICompileUnit(*I).isMain()) {
674 if (!HasDebugInfo) return false;
676 // Create all the compile unit DIEs.
677 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
678 E = DbgFinder.compile_unit_end(); I != E; ++I)
679 constructCompileUnit(*I);
681 // Create DIEs for each global variable.
682 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
683 E = DbgFinder.global_variable_end(); I != E; ++I) {
684 const MDNode *N = *I;
685 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
686 CU->createGlobalVariableDIE(N);
689 // Create DIEs for each subprogram.
690 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
691 E = DbgFinder.subprogram_end(); I != E; ++I) {
692 const MDNode *N = *I;
693 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
694 constructSubprogramDIE(CU, N);
700 /// beginModule - Emit all Dwarf sections that should come prior to the
701 /// content. Create global DIEs and emit initial debug info sections.
702 /// This is invoked by the target AsmPrinter.
703 void DwarfDebug::beginModule(Module *M) {
704 if (DisableDebugInfoPrinting)
707 // If module has named metadata anchors then use them, otherwise scan the
708 // module using debug info finder to collect debug info.
709 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
711 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
712 DICompileUnit CUNode(CU_Nodes->getOperand(i));
713 CompileUnit *CU = constructCompileUnit(CUNode);
714 DIArray GVs = CUNode.getGlobalVariables();
715 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
716 CU->createGlobalVariableDIE(GVs.getElement(i));
717 DIArray SPs = CUNode.getSubprograms();
718 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
719 constructSubprogramDIE(CU, SPs.getElement(i));
720 DIArray EnumTypes = CUNode.getEnumTypes();
721 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
722 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
723 DIArray RetainedTypes = CUNode.getRetainedTypes();
724 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
725 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
727 } else if (!collectLegacyDebugInfo(M))
730 collectInfoFromNamedMDNodes(M);
732 // Tell MMI that we have debug info.
733 MMI->setDebugInfoAvailability(true);
735 // Emit initial sections.
738 // Prime section data.
739 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
742 /// endModule - Emit all Dwarf sections that should come after the content.
744 void DwarfDebug::endModule() {
745 if (!FirstCU) return;
746 const Module *M = MMI->getModule();
747 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
749 // Collect info for variables that were optimized out.
750 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
751 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
752 DICompileUnit TheCU(CU_Nodes->getOperand(i));
753 DIArray Subprograms = TheCU.getSubprograms();
754 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
755 DISubprogram SP(Subprograms.getElement(i));
756 if (ProcessedSPNodes.count(SP) != 0) continue;
757 if (!SP.Verify()) continue;
758 if (!SP.isDefinition()) continue;
759 DIArray Variables = SP.getVariables();
760 if (Variables.getNumElements() == 0) continue;
762 LexicalScope *Scope =
763 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
764 DeadFnScopeMap[SP] = Scope;
766 // Construct subprogram DIE and add variables DIEs.
767 CompileUnit *SPCU = CUMap.lookup(TheCU);
768 assert(SPCU && "Unable to find Compile Unit!");
769 constructSubprogramDIE(SPCU, SP);
770 DIE *ScopeDIE = SPCU->getDIE(SP);
771 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
772 DIVariable DV(Variables.getElement(vi));
773 if (!DV.Verify()) continue;
774 DbgVariable *NewVar = new DbgVariable(DV, NULL);
775 if (DIE *VariableDIE =
776 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
777 ScopeDIE->addChild(VariableDIE);
783 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
784 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
785 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
787 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
789 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
790 AE = AbstractSPDies.end(); AI != AE; ++AI) {
791 DIE *ISP = AI->second;
792 if (InlinedSubprogramDIEs.count(ISP))
794 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
797 // Emit DW_AT_containing_type attribute to connect types with their
798 // vtable holding type.
799 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
800 CUE = CUMap.end(); CUI != CUE; ++CUI) {
801 CompileUnit *TheCU = CUI->second;
802 TheCU->constructContainingTypeDIEs();
805 // Standard sections final addresses.
806 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
807 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
808 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
809 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
811 // End text sections.
812 for (unsigned i = 1, N = SectionMap.size(); i <= N; ++i) {
813 Asm->OutStreamer.SwitchSection(SectionMap[i]);
814 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", i));
817 // Compute DIE offsets and sizes.
818 computeSizeAndOffsets();
820 // Emit all the DIEs into a debug info section
823 // Corresponding abbreviations into a abbrev section.
826 // Emit info into the dwarf accelerator table sections.
827 if (DwarfAccelTables) {
830 emitAccelNamespaces();
834 // Emit info into a debug pubtypes section.
835 // TODO: When we don't need the option anymore we can
836 // remove all of the code that adds to the table.
840 // Emit info into a debug loc section.
843 // Emit info into a debug aranges section.
846 // Emit info into a debug ranges section.
849 // Emit info into a debug macinfo section.
853 // TODO: When we don't need the option anymore we
854 // can remove all of the code that this section
857 emitDebugInlineInfo();
859 // Emit info into a debug str section.
863 DeleteContainerSeconds(DeadFnScopeMap);
865 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
866 E = CUMap.end(); I != E; ++I)
868 FirstCU = NULL; // Reset for the next Module, if any.
871 /// findAbstractVariable - Find abstract variable, if any, associated with Var.
872 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
874 LLVMContext &Ctx = DV->getContext();
875 // More then one inlined variable corresponds to one abstract variable.
876 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
877 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
879 return AbsDbgVariable;
881 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
885 AbsDbgVariable = new DbgVariable(Var, NULL);
886 addScopeVariable(Scope, AbsDbgVariable);
887 AbstractVariables[Var] = AbsDbgVariable;
888 return AbsDbgVariable;
891 /// addCurrentFnArgument - If Var is a current function argument then add
892 /// it to CurrentFnArguments list.
893 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
894 DbgVariable *Var, LexicalScope *Scope) {
895 if (!LScopes.isCurrentFunctionScope(Scope))
897 DIVariable DV = Var->getVariable();
898 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
900 unsigned ArgNo = DV.getArgNumber();
904 size_t Size = CurrentFnArguments.size();
906 CurrentFnArguments.resize(MF->getFunction()->arg_size());
907 // llvm::Function argument size is not good indicator of how many
908 // arguments does the function have at source level.
910 CurrentFnArguments.resize(ArgNo * 2);
911 CurrentFnArguments[ArgNo - 1] = Var;
915 /// collectVariableInfoFromMMITable - Collect variable information from
916 /// side table maintained by MMI.
918 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
919 SmallPtrSet<const MDNode *, 16> &Processed) {
920 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
921 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
922 VE = VMap.end(); VI != VE; ++VI) {
923 const MDNode *Var = VI->first;
925 Processed.insert(Var);
927 const std::pair<unsigned, DebugLoc> &VP = VI->second;
929 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
931 // If variable scope is not found then skip this variable.
935 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
936 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
937 RegVar->setFrameIndex(VP.first);
938 if (!addCurrentFnArgument(MF, RegVar, Scope))
939 addScopeVariable(Scope, RegVar);
941 AbsDbgVariable->setFrameIndex(VP.first);
945 /// isDbgValueInDefinedReg - Return true if debug value, encoded by
946 /// DBG_VALUE instruction, is in a defined reg.
947 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
948 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
949 return MI->getNumOperands() == 3 &&
950 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
951 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
954 /// getDebugLocEntry - Get .debug_loc entry for the instruction range starting
956 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
957 const MCSymbol *FLabel,
958 const MCSymbol *SLabel,
959 const MachineInstr *MI) {
960 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
962 if (MI->getNumOperands() != 3) {
963 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
964 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
966 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
967 MachineLocation MLoc;
968 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
969 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
971 if (MI->getOperand(0).isImm())
972 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
973 if (MI->getOperand(0).isFPImm())
974 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
975 if (MI->getOperand(0).isCImm())
976 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
978 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
981 /// collectVariableInfo - Find variables for each lexical scope.
983 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
984 SmallPtrSet<const MDNode *, 16> &Processed) {
986 /// collection info from MMI table.
987 collectVariableInfoFromMMITable(MF, Processed);
989 for (SmallVectorImpl<const MDNode*>::const_iterator
990 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
992 const MDNode *Var = *UVI;
993 if (Processed.count(Var))
996 // History contains relevant DBG_VALUE instructions for Var and instructions
998 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1001 const MachineInstr *MInsn = History.front();
1004 LexicalScope *Scope = NULL;
1005 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1006 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1007 Scope = LScopes.getCurrentFunctionScope();
1009 if (DV.getVersion() <= LLVMDebugVersion9)
1010 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1012 if (MDNode *IA = DV.getInlinedAt())
1013 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1015 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1018 // If variable scope is not found then skip this variable.
1022 Processed.insert(DV);
1023 assert(MInsn->isDebugValue() && "History must begin with debug value");
1024 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1025 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1026 if (!addCurrentFnArgument(MF, RegVar, Scope))
1027 addScopeVariable(Scope, RegVar);
1029 AbsVar->setMInsn(MInsn);
1031 // Simple ranges that are fully coalesced.
1032 if (History.size() <= 1 || (History.size() == 2 &&
1033 MInsn->isIdenticalTo(History.back()))) {
1034 RegVar->setMInsn(MInsn);
1038 // handle multiple DBG_VALUE instructions describing one variable.
1039 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1041 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1042 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1043 const MachineInstr *Begin = *HI;
1044 assert(Begin->isDebugValue() && "Invalid History entry");
1046 // Check if DBG_VALUE is truncating a range.
1047 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1048 && !Begin->getOperand(0).getReg())
1051 // Compute the range for a register location.
1052 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1053 const MCSymbol *SLabel = 0;
1056 // If Begin is the last instruction in History then its value is valid
1057 // until the end of the function.
1058 SLabel = FunctionEndSym;
1060 const MachineInstr *End = HI[1];
1061 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1062 << "\t" << *Begin << "\t" << *End << "\n");
1063 if (End->isDebugValue())
1064 SLabel = getLabelBeforeInsn(End);
1066 // End is a normal instruction clobbering the range.
1067 SLabel = getLabelAfterInsn(End);
1068 assert(SLabel && "Forgot label after clobber instruction");
1073 // The value is valid until the next DBG_VALUE or clobber.
1074 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1077 DotDebugLocEntries.push_back(DotDebugLocEntry());
1080 // Collect info for variables that were optimized out.
1081 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1082 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1083 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1084 DIVariable DV(Variables.getElement(i));
1085 if (!DV || !DV.Verify() || !Processed.insert(DV))
1087 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1088 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1092 /// getLabelBeforeInsn - Return Label preceding the instruction.
1093 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1094 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1095 assert(Label && "Didn't insert label before instruction");
1099 /// getLabelAfterInsn - Return Label immediately following the instruction.
1100 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1101 return LabelsAfterInsn.lookup(MI);
1104 /// beginInstruction - Process beginning of an instruction.
1105 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1106 // Check if source location changes, but ignore DBG_VALUE locations.
1107 if (!MI->isDebugValue()) {
1108 DebugLoc DL = MI->getDebugLoc();
1109 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1112 if (DL == PrologEndLoc) {
1113 Flags |= DWARF2_FLAG_PROLOGUE_END;
1114 PrologEndLoc = DebugLoc();
1116 if (PrologEndLoc.isUnknown())
1117 Flags |= DWARF2_FLAG_IS_STMT;
1119 if (!DL.isUnknown()) {
1120 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1121 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1123 recordSourceLine(0, 0, 0, 0);
1127 // Insert labels where requested.
1128 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1129 LabelsBeforeInsn.find(MI);
1132 if (I == LabelsBeforeInsn.end())
1135 // Label already assigned.
1140 PrevLabel = MMI->getContext().CreateTempSymbol();
1141 Asm->OutStreamer.EmitLabel(PrevLabel);
1143 I->second = PrevLabel;
1146 /// endInstruction - Process end of an instruction.
1147 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1148 // Don't create a new label after DBG_VALUE instructions.
1149 // They don't generate code.
1150 if (!MI->isDebugValue())
1153 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1154 LabelsAfterInsn.find(MI);
1157 if (I == LabelsAfterInsn.end())
1160 // Label already assigned.
1164 // We need a label after this instruction.
1166 PrevLabel = MMI->getContext().CreateTempSymbol();
1167 Asm->OutStreamer.EmitLabel(PrevLabel);
1169 I->second = PrevLabel;
1172 /// identifyScopeMarkers() -
1173 /// Each LexicalScope has first instruction and last instruction to mark
1174 /// beginning and end of a scope respectively. Create an inverse map that list
1175 /// scopes starts (and ends) with an instruction. One instruction may start (or
1176 /// end) multiple scopes. Ignore scopes that are not reachable.
1177 void DwarfDebug::identifyScopeMarkers() {
1178 SmallVector<LexicalScope *, 4> WorkList;
1179 WorkList.push_back(LScopes.getCurrentFunctionScope());
1180 while (!WorkList.empty()) {
1181 LexicalScope *S = WorkList.pop_back_val();
1183 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1184 if (!Children.empty())
1185 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1186 SE = Children.end(); SI != SE; ++SI)
1187 WorkList.push_back(*SI);
1189 if (S->isAbstractScope())
1192 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1195 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1196 RE = Ranges.end(); RI != RE; ++RI) {
1197 assert(RI->first && "InsnRange does not have first instruction!");
1198 assert(RI->second && "InsnRange does not have second instruction!");
1199 requestLabelBeforeInsn(RI->first);
1200 requestLabelAfterInsn(RI->second);
1205 /// getScopeNode - Get MDNode for DebugLoc's scope.
1206 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1207 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1208 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1209 return DL.getScope(Ctx);
1212 /// getFnDebugLoc - Walk up the scope chain of given debug loc and find
1213 /// line number info for the function.
1214 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1215 const MDNode *Scope = getScopeNode(DL, Ctx);
1216 DISubprogram SP = getDISubprogram(Scope);
1218 // Check for number of operands since the compatibility is
1220 if (SP->getNumOperands() > 19)
1221 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1223 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1229 /// beginFunction - Gather pre-function debug information. Assumes being
1230 /// emitted immediately after the function entry point.
1231 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1232 if (!MMI->hasDebugInfo()) return;
1233 LScopes.initialize(*MF);
1234 if (LScopes.empty()) return;
1235 identifyScopeMarkers();
1237 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1238 Asm->getFunctionNumber());
1239 // Assumes in correct section after the entry point.
1240 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1242 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1244 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1245 /// LiveUserVar - Map physreg numbers to the MDNode they contain.
1246 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1248 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1250 bool AtBlockEntry = true;
1251 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1253 const MachineInstr *MI = II;
1255 if (MI->isDebugValue()) {
1256 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1258 // Keep track of user variables.
1260 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1262 // Variable is in a register, we need to check for clobbers.
1263 if (isDbgValueInDefinedReg(MI))
1264 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1266 // Check the history of this variable.
1267 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1268 if (History.empty()) {
1269 UserVariables.push_back(Var);
1270 // The first mention of a function argument gets the FunctionBeginSym
1271 // label, so arguments are visible when breaking at function entry.
1273 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1274 DISubprogram(getDISubprogram(DV.getContext()))
1275 .describes(MF->getFunction()))
1276 LabelsBeforeInsn[MI] = FunctionBeginSym;
1278 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1279 const MachineInstr *Prev = History.back();
1280 if (Prev->isDebugValue()) {
1281 // Coalesce identical entries at the end of History.
1282 if (History.size() >= 2 &&
1283 Prev->isIdenticalTo(History[History.size() - 2])) {
1284 DEBUG(dbgs() << "Coalesce identical DBG_VALUE entries:\n"
1286 << "\t" << *History[History.size() - 2] << "\n");
1290 // Terminate old register assignments that don't reach MI;
1291 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1292 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1293 isDbgValueInDefinedReg(Prev)) {
1294 // Previous register assignment needs to terminate at the end of
1296 MachineBasicBlock::const_iterator LastMI =
1297 PrevMBB->getLastNonDebugInstr();
1298 if (LastMI == PrevMBB->end()) {
1299 // Drop DBG_VALUE for empty range.
1300 DEBUG(dbgs() << "Drop DBG_VALUE for empty range:\n"
1301 << "\t" << *Prev << "\n");
1305 // Terminate after LastMI.
1306 History.push_back(LastMI);
1311 History.push_back(MI);
1313 // Not a DBG_VALUE instruction.
1315 AtBlockEntry = false;
1317 // First known non DBG_VALUE location marks beginning of function
1319 if (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown())
1320 PrologEndLoc = MI->getDebugLoc();
1322 // Check if the instruction clobbers any registers with debug vars.
1323 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1324 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1325 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1327 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1328 AI.isValid(); ++AI) {
1330 const MDNode *Var = LiveUserVar[Reg];
1333 // Reg is now clobbered.
1334 LiveUserVar[Reg] = 0;
1336 // Was MD last defined by a DBG_VALUE referring to Reg?
1337 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1338 if (HistI == DbgValues.end())
1340 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1341 if (History.empty())
1343 const MachineInstr *Prev = History.back();
1344 // Sanity-check: Register assignments are terminated at the end of
1346 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1348 // Is the variable still in Reg?
1349 if (!isDbgValueInDefinedReg(Prev) ||
1350 Prev->getOperand(0).getReg() != Reg)
1352 // Var is clobbered. Make sure the next instruction gets a label.
1353 History.push_back(MI);
1360 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1362 SmallVectorImpl<const MachineInstr*> &History = I->second;
1363 if (History.empty())
1366 // Make sure the final register assignments are terminated.
1367 const MachineInstr *Prev = History.back();
1368 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1369 const MachineBasicBlock *PrevMBB = Prev->getParent();
1370 MachineBasicBlock::const_iterator LastMI =
1371 PrevMBB->getLastNonDebugInstr();
1372 if (LastMI == PrevMBB->end())
1373 // Drop DBG_VALUE for empty range.
1376 // Terminate after LastMI.
1377 History.push_back(LastMI);
1380 // Request labels for the full history.
1381 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1382 const MachineInstr *MI = History[i];
1383 if (MI->isDebugValue())
1384 requestLabelBeforeInsn(MI);
1386 requestLabelAfterInsn(MI);
1390 PrevInstLoc = DebugLoc();
1391 PrevLabel = FunctionBeginSym;
1393 // Record beginning of function.
1394 if (!PrologEndLoc.isUnknown()) {
1395 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1396 MF->getFunction()->getContext());
1397 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1398 FnStartDL.getScope(MF->getFunction()->getContext()),
1399 DWARF2_LINE_DEFAULT_IS_STMT ? DWARF2_FLAG_IS_STMT : 0);
1403 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1404 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1405 ScopeVariables[LS].push_back(Var);
1406 // Vars.push_back(Var);
1409 /// endFunction - Gather and emit post-function debug information.
1411 void DwarfDebug::endFunction(const MachineFunction *MF) {
1412 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1414 // Define end label for subprogram.
1415 FunctionEndSym = Asm->GetTempSymbol("func_end",
1416 Asm->getFunctionNumber());
1417 // Assumes in correct section after the entry point.
1418 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1420 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1421 collectVariableInfo(MF, ProcessedVars);
1423 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1424 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1425 assert(TheCU && "Unable to find compile unit!");
1427 // Construct abstract scopes.
1428 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1429 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1430 LexicalScope *AScope = AList[i];
1431 DISubprogram SP(AScope->getScopeNode());
1433 // Collect info for variables that were optimized out.
1434 DIArray Variables = SP.getVariables();
1435 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1436 DIVariable DV(Variables.getElement(i));
1437 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1439 // Check that DbgVariable for DV wasn't created earlier, when
1440 // findAbstractVariable() was called for inlined instance of DV.
1441 LLVMContext &Ctx = DV->getContext();
1442 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1443 if (AbstractVariables.lookup(CleanDV))
1445 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1446 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1449 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1450 constructScopeDIE(TheCU, AScope);
1453 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1455 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1456 TheCU->addUInt(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr,
1457 dwarf::DW_FORM_flag, 1);
1459 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1460 MMI->getFrameMoves()));
1463 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1464 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1465 DeleteContainerPointers(I->second);
1466 ScopeVariables.clear();
1467 DeleteContainerPointers(CurrentFnArguments);
1468 UserVariables.clear();
1470 AbstractVariables.clear();
1471 LabelsBeforeInsn.clear();
1472 LabelsAfterInsn.clear();
1476 /// recordSourceLine - Register a source line with debug info. Returns the
1477 /// unique label that was emitted and which provides correspondence to
1478 /// the source line list.
1479 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1485 DIDescriptor Scope(S);
1487 if (Scope.isCompileUnit()) {
1488 DICompileUnit CU(S);
1489 Fn = CU.getFilename();
1490 Dir = CU.getDirectory();
1491 } else if (Scope.isFile()) {
1493 Fn = F.getFilename();
1494 Dir = F.getDirectory();
1495 } else if (Scope.isSubprogram()) {
1497 Fn = SP.getFilename();
1498 Dir = SP.getDirectory();
1499 } else if (Scope.isLexicalBlockFile()) {
1500 DILexicalBlockFile DBF(S);
1501 Fn = DBF.getFilename();
1502 Dir = DBF.getDirectory();
1503 } else if (Scope.isLexicalBlock()) {
1504 DILexicalBlock DB(S);
1505 Fn = DB.getFilename();
1506 Dir = DB.getDirectory();
1508 llvm_unreachable("Unexpected scope info");
1510 Src = GetOrCreateSourceID(Fn, Dir);
1512 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1515 //===----------------------------------------------------------------------===//
1517 //===----------------------------------------------------------------------===//
1519 /// computeSizeAndOffset - Compute the size and offset of a DIE.
1522 DwarfDebug::computeSizeAndOffset(DIE *Die, unsigned Offset, bool Last) {
1523 // Get the children.
1524 const std::vector<DIE *> &Children = Die->getChildren();
1526 // Record the abbreviation.
1527 assignAbbrevNumber(Die->getAbbrev());
1529 // Get the abbreviation for this DIE.
1530 unsigned AbbrevNumber = Die->getAbbrevNumber();
1531 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1534 Die->setOffset(Offset);
1536 // Start the size with the size of abbreviation code.
1537 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1539 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1540 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1542 // Size the DIE attribute values.
1543 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1544 // Size attribute value.
1545 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1547 // Size the DIE children if any.
1548 if (!Children.empty()) {
1549 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1550 "Children flag not set");
1552 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1553 Offset = computeSizeAndOffset(Children[j], Offset, (j + 1) == M);
1555 // End of children marker.
1556 Offset += sizeof(int8_t);
1559 Die->setSize(Offset - Die->getOffset());
1563 /// computeSizeAndOffsets - Compute the size and offset of all the DIEs.
1565 void DwarfDebug::computeSizeAndOffsets() {
1566 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1567 E = CUMap.end(); I != E; ++I) {
1568 // Compute size of compile unit header.
1570 sizeof(int32_t) + // Length of Compilation Unit Info
1571 sizeof(int16_t) + // DWARF version number
1572 sizeof(int32_t) + // Offset Into Abbrev. Section
1573 sizeof(int8_t); // Pointer Size (in bytes)
1574 computeSizeAndOffset(I->second->getCUDie(), Offset, true);
1578 /// EmitSectionLabels - Emit initial Dwarf sections with a label at
1579 /// the start of each one.
1580 void DwarfDebug::EmitSectionLabels() {
1581 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1583 // Dwarf sections base addresses.
1584 DwarfInfoSectionSym =
1585 EmitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1586 DwarfAbbrevSectionSym =
1587 EmitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1588 EmitSectionSym(Asm, TLOF.getDwarfARangesSection());
1590 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1591 EmitSectionSym(Asm, MacroInfo);
1593 EmitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1594 EmitSectionSym(Asm, TLOF.getDwarfLocSection());
1595 EmitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1596 DwarfStrSectionSym =
1597 EmitSectionSym(Asm, TLOF.getDwarfStrSection(), "section_str");
1598 DwarfDebugRangeSectionSym = EmitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1601 DwarfDebugLocSectionSym = EmitSectionSym(Asm, TLOF.getDwarfLocSection(),
1602 "section_debug_loc");
1604 TextSectionSym = EmitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1605 EmitSectionSym(Asm, TLOF.getDataSection());
1608 /// emitDIE - Recursively emits a debug information entry.
1610 void DwarfDebug::emitDIE(DIE *Die) {
1611 // Get the abbreviation for this DIE.
1612 unsigned AbbrevNumber = Die->getAbbrevNumber();
1613 const DIEAbbrev *Abbrev = Abbreviations[AbbrevNumber - 1];
1615 // Emit the code (index) for the abbreviation.
1616 if (Asm->isVerbose())
1617 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1618 Twine::utohexstr(Die->getOffset()) + ":0x" +
1619 Twine::utohexstr(Die->getSize()) + " " +
1620 dwarf::TagString(Abbrev->getTag()));
1621 Asm->EmitULEB128(AbbrevNumber);
1623 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1624 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1626 // Emit the DIE attribute values.
1627 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1628 unsigned Attr = AbbrevData[i].getAttribute();
1629 unsigned Form = AbbrevData[i].getForm();
1630 assert(Form && "Too many attributes for DIE (check abbreviation)");
1632 if (Asm->isVerbose())
1633 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1636 case dwarf::DW_AT_abstract_origin: {
1637 DIEEntry *E = cast<DIEEntry>(Values[i]);
1638 DIE *Origin = E->getEntry();
1639 unsigned Addr = Origin->getOffset();
1640 Asm->EmitInt32(Addr);
1643 case dwarf::DW_AT_ranges: {
1644 // DW_AT_range Value encodes offset in debug_range section.
1645 DIEInteger *V = cast<DIEInteger>(Values[i]);
1647 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1648 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1652 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1654 DwarfDebugRangeSectionSym,
1659 case dwarf::DW_AT_location: {
1660 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1661 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1662 Asm->EmitLabelReference(L->getValue(), 4);
1664 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1666 Values[i]->EmitValue(Asm, Form);
1670 case dwarf::DW_AT_accessibility: {
1671 if (Asm->isVerbose()) {
1672 DIEInteger *V = cast<DIEInteger>(Values[i]);
1673 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1675 Values[i]->EmitValue(Asm, Form);
1679 // Emit an attribute using the defined form.
1680 Values[i]->EmitValue(Asm, Form);
1685 // Emit the DIE children if any.
1686 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1687 const std::vector<DIE *> &Children = Die->getChildren();
1689 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1690 emitDIE(Children[j]);
1692 if (Asm->isVerbose())
1693 Asm->OutStreamer.AddComment("End Of Children Mark");
1698 /// emitDebugInfo - Emit the debug info section.
1700 void DwarfDebug::emitDebugInfo() {
1701 // Start debug info section.
1702 Asm->OutStreamer.SwitchSection(
1703 Asm->getObjFileLowering().getDwarfInfoSection());
1704 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1705 E = CUMap.end(); I != E; ++I) {
1706 CompileUnit *TheCU = I->second;
1707 DIE *Die = TheCU->getCUDie();
1709 // Emit the compile units header.
1710 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_begin",
1713 // Emit size of content not including length itself
1714 unsigned ContentSize = Die->getSize() +
1715 sizeof(int16_t) + // DWARF version number
1716 sizeof(int32_t) + // Offset Into Abbrev. Section
1717 sizeof(int8_t); // Pointer Size (in bytes)
1719 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1720 Asm->EmitInt32(ContentSize);
1721 Asm->OutStreamer.AddComment("DWARF version number");
1722 Asm->EmitInt16(dwarf::DWARF_VERSION);
1723 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1724 Asm->EmitSectionOffset(Asm->GetTempSymbol("abbrev_begin"),
1725 DwarfAbbrevSectionSym);
1726 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1727 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
1730 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("info_end", TheCU->getID()));
1734 /// emitAbbreviations - Emit the abbreviation section.
1736 void DwarfDebug::emitAbbreviations() const {
1737 // Check to see if it is worth the effort.
1738 if (!Abbreviations.empty()) {
1739 // Start the debug abbrev section.
1740 Asm->OutStreamer.SwitchSection(
1741 Asm->getObjFileLowering().getDwarfAbbrevSection());
1743 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_begin"));
1745 // For each abbrevation.
1746 for (unsigned i = 0, N = Abbreviations.size(); i < N; ++i) {
1747 // Get abbreviation data
1748 const DIEAbbrev *Abbrev = Abbreviations[i];
1750 // Emit the abbrevations code (base 1 index.)
1751 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1753 // Emit the abbreviations data.
1757 // Mark end of abbreviations.
1758 Asm->EmitULEB128(0, "EOM(3)");
1760 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("abbrev_end"));
1764 /// emitEndOfLineMatrix - Emit the last address of the section and the end of
1765 /// the line matrix.
1767 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1768 // Define last address of section.
1769 Asm->OutStreamer.AddComment("Extended Op");
1772 Asm->OutStreamer.AddComment("Op size");
1773 Asm->EmitInt8(Asm->getTargetData().getPointerSize() + 1);
1774 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1775 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1777 Asm->OutStreamer.AddComment("Section end label");
1779 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1780 Asm->getTargetData().getPointerSize(),
1783 // Mark end of matrix.
1784 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1790 /// emitAccelNames - Emit visible names into a hashed accelerator table
1792 void DwarfDebug::emitAccelNames() {
1793 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1794 dwarf::DW_FORM_data4));
1795 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1796 E = CUMap.end(); I != E; ++I) {
1797 CompileUnit *TheCU = I->second;
1798 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1799 for (StringMap<std::vector<DIE*> >::const_iterator
1800 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1801 const char *Name = GI->getKeyData();
1802 const std::vector<DIE *> &Entities = GI->second;
1803 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1804 DE = Entities.end(); DI != DE; ++DI)
1805 AT.AddName(Name, (*DI));
1809 AT.FinalizeTable(Asm, "Names");
1810 Asm->OutStreamer.SwitchSection(
1811 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1812 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1813 Asm->OutStreamer.EmitLabel(SectionBegin);
1815 // Emit the full data.
1816 AT.Emit(Asm, SectionBegin, this);
1819 /// emitAccelObjC - Emit objective C classes and categories into a hashed
1820 /// accelerator table section.
1821 void DwarfDebug::emitAccelObjC() {
1822 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1823 dwarf::DW_FORM_data4));
1824 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1825 E = CUMap.end(); I != E; ++I) {
1826 CompileUnit *TheCU = I->second;
1827 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1828 for (StringMap<std::vector<DIE*> >::const_iterator
1829 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1830 const char *Name = GI->getKeyData();
1831 const std::vector<DIE *> &Entities = GI->second;
1832 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1833 DE = Entities.end(); DI != DE; ++DI)
1834 AT.AddName(Name, (*DI));
1838 AT.FinalizeTable(Asm, "ObjC");
1839 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1840 .getDwarfAccelObjCSection());
1841 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
1842 Asm->OutStreamer.EmitLabel(SectionBegin);
1844 // Emit the full data.
1845 AT.Emit(Asm, SectionBegin, this);
1848 /// emitAccelNamespace - Emit namespace dies into a hashed accelerator
1850 void DwarfDebug::emitAccelNamespaces() {
1851 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1852 dwarf::DW_FORM_data4));
1853 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1854 E = CUMap.end(); I != E; ++I) {
1855 CompileUnit *TheCU = I->second;
1856 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
1857 for (StringMap<std::vector<DIE*> >::const_iterator
1858 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1859 const char *Name = GI->getKeyData();
1860 const std::vector<DIE *> &Entities = GI->second;
1861 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1862 DE = Entities.end(); DI != DE; ++DI)
1863 AT.AddName(Name, (*DI));
1867 AT.FinalizeTable(Asm, "namespac");
1868 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1869 .getDwarfAccelNamespaceSection());
1870 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
1871 Asm->OutStreamer.EmitLabel(SectionBegin);
1873 // Emit the full data.
1874 AT.Emit(Asm, SectionBegin, this);
1877 /// emitAccelTypes() - Emit type dies into a hashed accelerator table.
1878 void DwarfDebug::emitAccelTypes() {
1879 std::vector<DwarfAccelTable::Atom> Atoms;
1880 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1881 dwarf::DW_FORM_data4));
1882 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
1883 dwarf::DW_FORM_data2));
1884 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
1885 dwarf::DW_FORM_data1));
1886 DwarfAccelTable AT(Atoms);
1887 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1888 E = CUMap.end(); I != E; ++I) {
1889 CompileUnit *TheCU = I->second;
1890 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
1891 = TheCU->getAccelTypes();
1892 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
1893 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1894 const char *Name = GI->getKeyData();
1895 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
1896 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
1897 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
1898 AT.AddName(Name, (*DI).first, (*DI).second);
1902 AT.FinalizeTable(Asm, "types");
1903 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
1904 .getDwarfAccelTypesSection());
1905 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
1906 Asm->OutStreamer.EmitLabel(SectionBegin);
1908 // Emit the full data.
1909 AT.Emit(Asm, SectionBegin, this);
1912 void DwarfDebug::emitDebugPubTypes() {
1913 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1914 E = CUMap.end(); I != E; ++I) {
1915 CompileUnit *TheCU = I->second;
1916 // Start the dwarf pubtypes section.
1917 Asm->OutStreamer.SwitchSection(
1918 Asm->getObjFileLowering().getDwarfPubTypesSection());
1919 Asm->OutStreamer.AddComment("Length of Public Types Info");
1920 Asm->EmitLabelDifference(
1921 Asm->GetTempSymbol("pubtypes_end", TheCU->getID()),
1922 Asm->GetTempSymbol("pubtypes_begin", TheCU->getID()), 4);
1924 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
1927 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
1928 Asm->EmitInt16(dwarf::DWARF_VERSION);
1930 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1931 Asm->EmitSectionOffset(Asm->GetTempSymbol("info_begin", TheCU->getID()),
1932 DwarfInfoSectionSym);
1934 Asm->OutStreamer.AddComment("Compilation Unit Length");
1935 Asm->EmitLabelDifference(Asm->GetTempSymbol("info_end", TheCU->getID()),
1936 Asm->GetTempSymbol("info_begin", TheCU->getID()),
1939 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
1940 for (StringMap<DIE*>::const_iterator
1941 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
1942 const char *Name = GI->getKeyData();
1943 DIE *Entity = GI->second;
1945 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
1946 Asm->EmitInt32(Entity->getOffset());
1948 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
1949 // Emit the name with a terminating null byte.
1950 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
1953 Asm->OutStreamer.AddComment("End Mark");
1955 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
1960 /// emitDebugStr - Emit visible names into a debug str section.
1962 void DwarfDebug::emitDebugStr() {
1963 // Check to see if it is worth the effort.
1964 if (StringPool.empty()) return;
1966 // Start the dwarf str section.
1967 Asm->OutStreamer.SwitchSection(
1968 Asm->getObjFileLowering().getDwarfStrSection());
1970 // Get all of the string pool entries and put them in an array by their ID so
1971 // we can sort them.
1972 SmallVector<std::pair<unsigned,
1973 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
1975 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
1976 I = StringPool.begin(), E = StringPool.end(); I != E; ++I)
1977 Entries.push_back(std::make_pair(I->second.second, &*I));
1979 array_pod_sort(Entries.begin(), Entries.end());
1981 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
1982 // Emit a label for reference from debug information entries.
1983 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
1985 // Emit the string itself with a terminating null byte.
1986 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
1987 Entries[i].second->getKeyLength()+1),
1992 /// emitDebugLoc - Emit visible names into a debug loc section.
1994 void DwarfDebug::emitDebugLoc() {
1995 if (DotDebugLocEntries.empty())
1998 for (SmallVector<DotDebugLocEntry, 4>::iterator
1999 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2001 DotDebugLocEntry &Entry = *I;
2002 if (I + 1 != DotDebugLocEntries.end())
2006 // Start the dwarf loc section.
2007 Asm->OutStreamer.SwitchSection(
2008 Asm->getObjFileLowering().getDwarfLocSection());
2009 unsigned char Size = Asm->getTargetData().getPointerSize();
2010 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2012 for (SmallVector<DotDebugLocEntry, 4>::iterator
2013 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2014 I != E; ++I, ++index) {
2015 DotDebugLocEntry &Entry = *I;
2016 if (Entry.isMerged()) continue;
2017 if (Entry.isEmpty()) {
2018 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2019 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2020 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2022 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2023 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2024 DIVariable DV(Entry.Variable);
2025 Asm->OutStreamer.AddComment("Loc expr size");
2026 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2027 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2028 Asm->EmitLabelDifference(end, begin, 2);
2029 Asm->OutStreamer.EmitLabel(begin);
2030 if (Entry.isInt()) {
2031 DIBasicType BTy(DV.getType());
2033 (BTy.getEncoding() == dwarf::DW_ATE_signed
2034 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2035 Asm->OutStreamer.AddComment("DW_OP_consts");
2036 Asm->EmitInt8(dwarf::DW_OP_consts);
2037 Asm->EmitSLEB128(Entry.getInt());
2039 Asm->OutStreamer.AddComment("DW_OP_constu");
2040 Asm->EmitInt8(dwarf::DW_OP_constu);
2041 Asm->EmitULEB128(Entry.getInt());
2043 } else if (Entry.isLocation()) {
2044 if (!DV.hasComplexAddress())
2046 Asm->EmitDwarfRegOp(Entry.Loc);
2048 // Complex address entry.
2049 unsigned N = DV.getNumAddrElements();
2051 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2052 if (Entry.Loc.getOffset()) {
2054 Asm->EmitDwarfRegOp(Entry.Loc);
2055 Asm->OutStreamer.AddComment("DW_OP_deref");
2056 Asm->EmitInt8(dwarf::DW_OP_deref);
2057 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2058 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2059 Asm->EmitSLEB128(DV.getAddrElement(1));
2061 // If first address element is OpPlus then emit
2062 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2063 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2064 Asm->EmitDwarfRegOp(Loc);
2068 Asm->EmitDwarfRegOp(Entry.Loc);
2071 // Emit remaining complex address elements.
2072 for (; i < N; ++i) {
2073 uint64_t Element = DV.getAddrElement(i);
2074 if (Element == DIBuilder::OpPlus) {
2075 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2076 Asm->EmitULEB128(DV.getAddrElement(++i));
2077 } else if (Element == DIBuilder::OpDeref) {
2078 if (!Entry.Loc.isReg())
2079 Asm->EmitInt8(dwarf::DW_OP_deref);
2081 llvm_unreachable("unknown Opcode found in complex address");
2085 // else ... ignore constant fp. There is not any good way to
2086 // to represent them here in dwarf.
2087 Asm->OutStreamer.EmitLabel(end);
2092 /// EmitDebugARanges - Emit visible names into a debug aranges section.
2094 void DwarfDebug::EmitDebugARanges() {
2095 // Start the dwarf aranges section.
2096 Asm->OutStreamer.SwitchSection(
2097 Asm->getObjFileLowering().getDwarfARangesSection());
2100 /// emitDebugRanges - Emit visible names into a debug ranges section.
2102 void DwarfDebug::emitDebugRanges() {
2103 // Start the dwarf ranges section.
2104 Asm->OutStreamer.SwitchSection(
2105 Asm->getObjFileLowering().getDwarfRangesSection());
2106 unsigned char Size = Asm->getTargetData().getPointerSize();
2107 for (SmallVector<const MCSymbol *, 8>::iterator
2108 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2111 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2113 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2117 /// emitDebugMacInfo - Emit visible names into a debug macinfo section.
2119 void DwarfDebug::emitDebugMacInfo() {
2120 if (const MCSection *LineInfo =
2121 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2122 // Start the dwarf macinfo section.
2123 Asm->OutStreamer.SwitchSection(LineInfo);
2127 /// emitDebugInlineInfo - Emit inline info using following format.
2129 /// 1. length of section
2130 /// 2. Dwarf version number
2131 /// 3. address size.
2133 /// Entries (one "entry" for each function that was inlined):
2135 /// 1. offset into __debug_str section for MIPS linkage name, if exists;
2136 /// otherwise offset into __debug_str for regular function name.
2137 /// 2. offset into __debug_str section for regular function name.
2138 /// 3. an unsigned LEB128 number indicating the number of distinct inlining
2139 /// instances for the function.
2141 /// The rest of the entry consists of a {die_offset, low_pc} pair for each
2142 /// inlined instance; the die_offset points to the inlined_subroutine die in the
2143 /// __debug_info section, and the low_pc is the starting address for the
2144 /// inlining instance.
2145 void DwarfDebug::emitDebugInlineInfo() {
2146 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2152 Asm->OutStreamer.SwitchSection(
2153 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2155 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2156 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2157 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2159 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2161 Asm->OutStreamer.AddComment("Dwarf Version");
2162 Asm->EmitInt16(dwarf::DWARF_VERSION);
2163 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2164 Asm->EmitInt8(Asm->getTargetData().getPointerSize());
2166 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2167 E = InlinedSPNodes.end(); I != E; ++I) {
2169 const MDNode *Node = *I;
2170 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2171 = InlineInfo.find(Node);
2172 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2173 DISubprogram SP(Node);
2174 StringRef LName = SP.getLinkageName();
2175 StringRef Name = SP.getName();
2177 Asm->OutStreamer.AddComment("MIPS linkage name");
2179 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2181 Asm->EmitSectionOffset(getStringPoolEntry(getRealLinkageName(LName)),
2182 DwarfStrSectionSym);
2184 Asm->OutStreamer.AddComment("Function name");
2185 Asm->EmitSectionOffset(getStringPoolEntry(Name), DwarfStrSectionSym);
2186 Asm->EmitULEB128(Labels.size(), "Inline count");
2188 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2189 LE = Labels.end(); LI != LE; ++LI) {
2190 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2191 Asm->EmitInt32(LI->second->getOffset());
2193 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2194 Asm->OutStreamer.EmitSymbolValue(LI->first,
2195 Asm->getTargetData().getPointerSize(),0);
2199 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));