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/ADT/STLExtras.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/DIBuilder.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/MC/MCAsmInfo.h"
32 #include "llvm/MC/MCSection.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/Timer.h"
41 #include "llvm/Support/ValueHandle.h"
42 #include "llvm/Target/TargetFrameLowering.h"
43 #include "llvm/Target/TargetLoweringObjectFile.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 #include "llvm/Target/TargetRegisterInfo.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"),
81 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
82 cl::desc("Output prototype dwarf split debug info."),
84 clEnumVal(Default, "Default for platform"),
85 clEnumVal(Enable, "Enabled"),
86 clEnumVal(Disable, "Disabled"),
91 const char *DWARFGroupName = "DWARF Emission";
92 const char *DbgTimerName = "DWARF Debug Writer";
93 } // end anonymous namespace
95 //===----------------------------------------------------------------------===//
97 // Configuration values for initial hash set sizes (log2).
99 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
103 DIType DbgVariable::getType() const {
104 DIType Ty = Var.getType();
105 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
106 // addresses instead.
107 if (Var.isBlockByrefVariable()) {
108 /* Byref variables, in Blocks, are declared by the programmer as
109 "SomeType VarName;", but the compiler creates a
110 __Block_byref_x_VarName struct, and gives the variable VarName
111 either the struct, or a pointer to the struct, as its type. This
112 is necessary for various behind-the-scenes things the compiler
113 needs to do with by-reference variables in blocks.
115 However, as far as the original *programmer* is concerned, the
116 variable should still have type 'SomeType', as originally declared.
118 The following function dives into the __Block_byref_x_VarName
119 struct to find the original type of the variable. This will be
120 passed back to the code generating the type for the Debug
121 Information Entry for the variable 'VarName'. 'VarName' will then
122 have the original type 'SomeType' in its debug information.
124 The original type 'SomeType' will be the type of the field named
125 'VarName' inside the __Block_byref_x_VarName struct.
127 NOTE: In order for this to not completely fail on the debugger
128 side, the Debug Information Entry for the variable VarName needs to
129 have a DW_AT_location that tells the debugger how to unwind through
130 the pointers and __Block_byref_x_VarName struct to find the actual
131 value of the variable. The function addBlockByrefType does this. */
133 unsigned tag = Ty.getTag();
135 if (tag == dwarf::DW_TAG_pointer_type) {
136 DIDerivedType DTy = DIDerivedType(Ty);
137 subType = DTy.getTypeDerivedFrom();
140 DICompositeType blockStruct = DICompositeType(subType);
141 DIArray Elements = blockStruct.getTypeArray();
143 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
144 DIDescriptor Element = Elements.getElement(i);
145 DIDerivedType DT = DIDerivedType(Element);
146 if (getName() == DT.getName())
147 return (DT.getTypeDerivedFrom());
153 } // end llvm namespace
155 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
156 : Asm(A), MMI(Asm->MMI), FirstCU(0),
157 AbbreviationsSet(InitAbbreviationsSetSize),
158 SourceIdMap(DIEValueAllocator), InfoStringPool(DIEValueAllocator),
159 PrevLabel(NULL), GlobalCUIndexCount(0),
160 InfoHolder(A, &AbbreviationsSet, &Abbreviations,
161 &InfoStringPool, "info_string"),
163 SkeletonAbbrevSet(InitAbbreviationsSetSize),
164 SkeletonStringPool(DIEValueAllocator),
165 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs,
166 &SkeletonStringPool, "skel_string") {
168 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
169 DwarfStrSectionSym = TextSectionSym = 0;
170 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
171 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
172 FunctionBeginSym = FunctionEndSym = 0;
174 // Turn on accelerator tables and older gdb compatibility
176 bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
177 if (DarwinGDBCompat == Default) {
179 IsDarwinGDBCompat = true;
181 IsDarwinGDBCompat = false;
183 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
185 if (DwarfAccelTables == Default) {
187 HasDwarfAccelTables = true;
189 HasDwarfAccelTables = false;
191 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
193 if (SplitDwarf == Default)
194 HasSplitDwarf = false;
196 HasSplitDwarf = SplitDwarf == Enable ? true : false;
199 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
203 DwarfDebug::~DwarfDebug() {
206 // Switch to the specified MCSection and emit an assembler
207 // temporary label to it if SymbolStem is specified.
208 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
209 const char *SymbolStem = 0) {
210 Asm->OutStreamer.SwitchSection(Section);
211 if (!SymbolStem) return 0;
213 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
214 Asm->OutStreamer.EmitLabel(TmpSym);
218 MCSymbol *DwarfUnits::getStringPoolSym() {
219 return Asm->GetTempSymbol(StringPref);
222 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
223 std::pair<MCSymbol*, unsigned> &Entry =
224 StringPool->GetOrCreateValue(Str).getValue();
225 if (Entry.first) return Entry.first;
227 Entry.second = NextStringPoolNumber++;
228 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
231 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
232 std::pair<MCSymbol*, unsigned> &Entry =
233 StringPool->GetOrCreateValue(Str).getValue();
234 if (Entry.first) return Entry.second;
236 Entry.second = NextStringPoolNumber++;
237 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
241 // Define a unique number for the abbreviation.
243 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
244 // Profile the node so that we can make it unique.
248 // Check the set for priors.
249 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
251 // If it's newly added.
252 if (InSet == &Abbrev) {
253 // Add to abbreviation list.
254 Abbreviations->push_back(&Abbrev);
256 // Assign the vector position + 1 as its number.
257 Abbrev.setNumber(Abbreviations->size());
259 // Assign existing abbreviation number.
260 Abbrev.setNumber(InSet->getNumber());
264 // If special LLVM prefix that is used to inform the asm
265 // printer to not emit usual symbol prefix before the symbol name is used then
266 // return linkage name after skipping this special LLVM prefix.
267 static StringRef getRealLinkageName(StringRef LinkageName) {
269 if (LinkageName.startswith(StringRef(&One, 1)))
270 return LinkageName.substr(1);
274 static bool isObjCClass(StringRef Name) {
275 return Name.startswith("+") || Name.startswith("-");
278 static bool hasObjCCategory(StringRef Name) {
279 if (!isObjCClass(Name)) return false;
281 size_t pos = Name.find(')');
282 if (pos != std::string::npos) {
283 if (Name[pos+1] != ' ') return false;
289 static void getObjCClassCategory(StringRef In, StringRef &Class,
290 StringRef &Category) {
291 if (!hasObjCCategory(In)) {
292 Class = In.slice(In.find('[') + 1, In.find(' '));
297 Class = In.slice(In.find('[') + 1, In.find('('));
298 Category = In.slice(In.find('[') + 1, In.find(' '));
302 static StringRef getObjCMethodName(StringRef In) {
303 return In.slice(In.find(' ') + 1, In.find(']'));
306 // Add the various names to the Dwarf accelerator table names.
307 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
309 if (!SP.isDefinition()) return;
311 TheCU->addAccelName(SP.getName(), Die);
313 // If the linkage name is different than the name, go ahead and output
314 // that as well into the name table.
315 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
316 TheCU->addAccelName(SP.getLinkageName(), Die);
318 // If this is an Objective-C selector name add it to the ObjC accelerator
320 if (isObjCClass(SP.getName())) {
321 StringRef Class, Category;
322 getObjCClassCategory(SP.getName(), Class, Category);
323 TheCU->addAccelObjC(Class, Die);
325 TheCU->addAccelObjC(Category, Die);
326 // Also add the base method name to the name table.
327 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
331 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
332 // and DW_AT_high_pc attributes. If there are global variables in this
333 // scope then create and insert DIEs for these variables.
334 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
335 const MDNode *SPNode) {
336 DIE *SPDie = SPCU->getDIE(SPNode);
338 assert(SPDie && "Unable to find subprogram DIE!");
339 DISubprogram SP(SPNode);
341 // If we're updating an abstract DIE, then we will be adding the children and
342 // object pointer later on. But what we don't want to do is process the
343 // concrete DIE twice.
344 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
345 // Pick up abstract subprogram DIE.
346 SPDie = new DIE(dwarf::DW_TAG_subprogram);
347 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
348 dwarf::DW_FORM_ref4, AbsSPDIE);
351 DISubprogram SPDecl = SP.getFunctionDeclaration();
352 if (!SPDecl.isSubprogram()) {
353 // There is not any need to generate specification DIE for a function
354 // defined at compile unit level. If a function is defined inside another
355 // function then gdb prefers the definition at top level and but does not
356 // expect specification DIE in parent function. So avoid creating
357 // specification DIE for a function defined inside a function.
358 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
359 !SP.getContext().isFile() &&
360 !isSubprogramContext(SP.getContext())) {
361 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
364 DICompositeType SPTy = SP.getType();
365 DIArray Args = SPTy.getTypeArray();
366 unsigned SPTag = SPTy.getTag();
367 if (SPTag == dwarf::DW_TAG_subroutine_type)
368 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
369 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
370 DIType ATy = DIType(Args.getElement(i));
371 SPCU->addType(Arg, ATy);
372 if (ATy.isArtificial())
373 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
374 if (ATy.isObjectPointer())
375 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
376 dwarf::DW_FORM_ref4, Arg);
377 SPDie->addChild(Arg);
379 DIE *SPDeclDie = SPDie;
380 SPDie = new DIE(dwarf::DW_TAG_subprogram);
381 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
382 dwarf::DW_FORM_ref4, SPDeclDie);
388 SPCU->addLabel(SPDie, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
389 Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber()));
390 SPCU->addLabel(SPDie, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
391 Asm->GetTempSymbol("func_end", Asm->getFunctionNumber()));
392 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
393 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
394 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
396 // Add name to the name table, we do this here because we're guaranteed
397 // to have concrete versions of our DW_TAG_subprogram nodes.
398 addSubprogramNames(SPCU, SP, SPDie);
403 // Construct new DW_TAG_lexical_block for this scope and attach
404 // DW_AT_low_pc/DW_AT_high_pc labels.
405 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
406 LexicalScope *Scope) {
407 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
408 if (Scope->isAbstractScope())
411 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
415 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
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->getDataLayout().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);
433 const MCSymbol *Start = getLabelBeforeInsn(RI->first);
434 const MCSymbol *End = getLabelAfterInsn(RI->second);
436 if (End == 0) return 0;
438 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
439 assert(End->isDefined() && "Invalid end label for an inlined scope!");
441 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, Start);
442 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr, End);
447 // This scope represents inlined body of a function. Construct DIE to
448 // represent this concrete inlined copy of the function.
449 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
450 LexicalScope *Scope) {
451 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
452 assert(Ranges.empty() == false &&
453 "LexicalScope does not have instruction markers!");
455 if (!Scope->getScopeNode())
457 DIScope DS(Scope->getScopeNode());
458 DISubprogram InlinedSP = getDISubprogram(DS);
459 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
461 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
465 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
466 const MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
467 const MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
469 if (StartLabel == 0 || EndLabel == 0) {
470 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
472 assert(StartLabel->isDefined() &&
473 "Invalid starting label for an inlined scope!");
474 assert(EndLabel->isDefined() &&
475 "Invalid end label for an inlined scope!");
477 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
478 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
479 dwarf::DW_FORM_ref4, OriginDIE);
481 if (Ranges.size() > 1) {
482 // .debug_range section has not been laid out yet. Emit offset in
483 // .debug_range as a uint, size 4, for now. emitDIE will handle
484 // DW_AT_ranges appropriately.
485 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
486 DebugRangeSymbols.size()
487 * Asm->getDataLayout().getPointerSize());
488 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
489 RE = Ranges.end(); RI != RE; ++RI) {
490 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
491 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
493 DebugRangeSymbols.push_back(NULL);
494 DebugRangeSymbols.push_back(NULL);
496 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
498 TheCU->addLabel(ScopeDIE, dwarf::DW_AT_high_pc, dwarf::DW_FORM_addr,
502 InlinedSubprogramDIEs.insert(OriginDIE);
504 // Track the start label for this inlined function.
505 //.debug_inlined section specification does not clearly state how
506 // to emit inlined scope that is split into multiple instruction ranges.
507 // For now, use first instruction range and emit low_pc/high_pc pair and
508 // corresponding .debug_inlined section entry for this pair.
509 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
510 I = InlineInfo.find(InlinedSP);
512 if (I == InlineInfo.end()) {
513 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
514 InlinedSPNodes.push_back(InlinedSP);
516 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
518 DILocation DL(Scope->getInlinedAt());
519 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
520 getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
521 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
523 // Add name to the name table, we do this here because we're guaranteed
524 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
525 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
530 // Construct a DIE for this scope.
531 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
532 if (!Scope || !Scope->getScopeNode())
535 SmallVector<DIE *, 8> Children;
536 DIE *ObjectPointer = NULL;
538 // Collect arguments for current function.
539 if (LScopes.isCurrentFunctionScope(Scope))
540 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
541 if (DbgVariable *ArgDV = CurrentFnArguments[i])
543 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
544 Children.push_back(Arg);
545 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
548 // Collect lexical scope children first.
549 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
550 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
552 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
553 Children.push_back(Variable);
554 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
556 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
557 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
558 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
559 Children.push_back(Nested);
560 DIScope DS(Scope->getScopeNode());
561 DIE *ScopeDIE = NULL;
562 if (Scope->getInlinedAt())
563 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
564 else if (DS.isSubprogram()) {
565 ProcessedSPNodes.insert(DS);
566 if (Scope->isAbstractScope()) {
567 ScopeDIE = TheCU->getDIE(DS);
568 // Note down abstract DIE.
570 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
573 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
576 // There is no need to emit empty lexical block DIE.
577 if (Children.empty())
579 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
582 if (!ScopeDIE) return NULL;
585 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
586 E = Children.end(); I != E; ++I)
587 ScopeDIE->addChild(*I);
589 if (DS.isSubprogram() && ObjectPointer != NULL)
590 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
591 dwarf::DW_FORM_ref4, ObjectPointer);
593 if (DS.isSubprogram())
594 TheCU->addPubTypes(DISubprogram(DS));
599 // Look up the source id with the given directory and source file names.
600 // If none currently exists, create a new id and insert it in the
601 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
603 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
605 // If FE did not provide a file name, then assume stdin.
606 if (FileName.empty())
607 return getOrCreateSourceID("<stdin>", StringRef());
609 // TODO: this might not belong here. See if we can factor this better.
610 if (DirName == CompilationDir)
613 unsigned SrcId = SourceIdMap.size()+1;
615 // We look up the file/dir pair by concatenating them with a zero byte.
616 SmallString<128> NamePair;
618 NamePair += '\0'; // Zero bytes are not allowed in paths.
619 NamePair += FileName;
621 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
622 if (Ent.getValue() != SrcId)
623 return Ent.getValue();
625 // Print out a .file directive to specify files for .loc directives.
626 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
631 // Create new CompileUnit for the given metadata node with tag
632 // DW_TAG_compile_unit.
633 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
634 DICompileUnit DIUnit(N);
635 StringRef FN = DIUnit.getFilename();
636 CompilationDir = DIUnit.getDirectory();
637 // Call this to emit a .file directive if it wasn't emitted for the source
638 // file this CU comes from yet.
639 getOrCreateSourceID(FN, CompilationDir);
641 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
642 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
643 DIUnit.getLanguage(), Die, Asm,
645 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
646 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
647 DIUnit.getLanguage());
648 NewCU->addString(Die, dwarf::DW_AT_name, FN);
649 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
651 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
652 // DW_AT_stmt_list is a offset of line number information for this
653 // compile unit in debug_line section.
654 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
655 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
656 Asm->GetTempSymbol("section_line"));
658 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
660 if (!CompilationDir.empty())
661 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
662 if (DIUnit.isOptimized())
663 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
665 StringRef Flags = DIUnit.getFlags();
667 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
669 if (unsigned RVer = DIUnit.getRunTimeVersion())
670 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
671 dwarf::DW_FORM_data1, RVer);
675 if (useSplitDwarf() && !SkeletonCU)
676 SkeletonCU = constructSkeletonCU(N);
678 InfoHolder.addUnit(NewCU);
680 CUMap.insert(std::make_pair(N, NewCU));
684 // Construct subprogram DIE.
685 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
687 CompileUnit *&CURef = SPMap[N];
693 if (!SP.isDefinition())
694 // This is a method declaration which will be handled while constructing
698 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
701 TheCU->insertDIE(N, SubprogramDie);
703 // Add to context owner.
704 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
709 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
710 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
711 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
712 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
713 const MDNode *N = NMD->getOperand(i);
714 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
715 constructSubprogramDIE(CU, N);
718 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
719 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
720 const MDNode *N = NMD->getOperand(i);
721 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
722 CU->createGlobalVariableDIE(N);
725 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
726 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
727 DIType Ty(NMD->getOperand(i));
728 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
729 CU->getOrCreateTypeDIE(Ty);
732 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
733 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
734 DIType Ty(NMD->getOperand(i));
735 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
736 CU->getOrCreateTypeDIE(Ty);
740 // Collect debug info using DebugInfoFinder.
741 // FIXME - Remove this when dragonegg switches to DIBuilder.
742 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
743 DebugInfoFinder DbgFinder;
744 DbgFinder.processModule(*M);
746 bool HasDebugInfo = false;
747 // Scan all the compile-units to see if there are any marked as the main
748 // unit. If not, we do not generate debug info.
749 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
750 E = DbgFinder.compile_unit_end(); I != E; ++I) {
751 if (DICompileUnit(*I).isMain()) {
756 if (!HasDebugInfo) return false;
758 // Create all the compile unit DIEs.
759 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
760 E = DbgFinder.compile_unit_end(); I != E; ++I)
761 constructCompileUnit(*I);
763 // Create DIEs for each global variable.
764 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
765 E = DbgFinder.global_variable_end(); I != E; ++I) {
766 const MDNode *N = *I;
767 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
768 CU->createGlobalVariableDIE(N);
771 // Create DIEs for each subprogram.
772 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
773 E = DbgFinder.subprogram_end(); I != E; ++I) {
774 const MDNode *N = *I;
775 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
776 constructSubprogramDIE(CU, N);
782 // Emit all Dwarf sections that should come prior to the content. Create
783 // global DIEs and emit initial debug info sections. This is invoked by
784 // the target AsmPrinter.
785 void DwarfDebug::beginModule() {
786 if (DisableDebugInfoPrinting)
789 const Module *M = MMI->getModule();
791 // If module has named metadata anchors then use them, otherwise scan the
792 // module using debug info finder to collect debug info.
793 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
795 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
796 DICompileUnit CUNode(CU_Nodes->getOperand(i));
797 CompileUnit *CU = constructCompileUnit(CUNode);
798 DIArray GVs = CUNode.getGlobalVariables();
799 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
800 CU->createGlobalVariableDIE(GVs.getElement(i));
801 DIArray SPs = CUNode.getSubprograms();
802 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
803 constructSubprogramDIE(CU, SPs.getElement(i));
804 DIArray EnumTypes = CUNode.getEnumTypes();
805 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
806 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
807 DIArray RetainedTypes = CUNode.getRetainedTypes();
808 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
809 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
811 } else if (!collectLegacyDebugInfo(M))
814 collectInfoFromNamedMDNodes(M);
816 // Tell MMI that we have debug info.
817 MMI->setDebugInfoAvailability(true);
819 // Prime section data.
820 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
823 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
824 void DwarfDebug::computeInlinedDIEs() {
825 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
826 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
827 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
829 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
831 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
832 AE = AbstractSPDies.end(); AI != AE; ++AI) {
833 DIE *ISP = AI->second;
834 if (InlinedSubprogramDIEs.count(ISP))
836 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
840 // Collect info for variables that were optimized out.
841 void DwarfDebug::collectDeadVariables() {
842 const Module *M = MMI->getModule();
843 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
845 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
846 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
847 DICompileUnit TheCU(CU_Nodes->getOperand(i));
848 DIArray Subprograms = TheCU.getSubprograms();
849 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
850 DISubprogram SP(Subprograms.getElement(i));
851 if (ProcessedSPNodes.count(SP) != 0) continue;
852 if (!SP.Verify()) continue;
853 if (!SP.isDefinition()) continue;
854 DIArray Variables = SP.getVariables();
855 if (Variables.getNumElements() == 0) continue;
857 LexicalScope *Scope =
858 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
859 DeadFnScopeMap[SP] = Scope;
861 // Construct subprogram DIE and add variables DIEs.
862 CompileUnit *SPCU = CUMap.lookup(TheCU);
863 assert(SPCU && "Unable to find Compile Unit!");
864 constructSubprogramDIE(SPCU, SP);
865 DIE *ScopeDIE = SPCU->getDIE(SP);
866 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
867 DIVariable DV(Variables.getElement(vi));
868 if (!DV.Verify()) continue;
869 DbgVariable *NewVar = new DbgVariable(DV, NULL);
870 if (DIE *VariableDIE =
871 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
872 ScopeDIE->addChild(VariableDIE);
877 DeleteContainerSeconds(DeadFnScopeMap);
880 void DwarfDebug::finalizeModuleInfo() {
881 // Collect info for variables that were optimized out.
882 collectDeadVariables();
884 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
885 computeInlinedDIEs();
887 // Emit DW_AT_containing_type attribute to connect types with their
888 // vtable holding type.
889 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
890 CUE = CUMap.end(); CUI != CUE; ++CUI) {
891 CompileUnit *TheCU = CUI->second;
892 TheCU->constructContainingTypeDIEs();
895 // Compute DIE offsets and sizes.
896 InfoHolder.computeSizeAndOffsets();
898 SkeletonHolder.computeSizeAndOffsets();
901 void DwarfDebug::endSections() {
902 // Standard sections final addresses.
903 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
904 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
905 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
906 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
908 // End text sections.
909 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
910 Asm->OutStreamer.SwitchSection(SectionMap[I]);
911 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
915 // Emit all Dwarf sections that should come after the content.
916 void DwarfDebug::endModule() {
918 if (!FirstCU) return;
920 // End any existing sections.
921 // TODO: Does this need to happen?
924 // Finalize the debug info for the module.
925 finalizeModuleInfo();
927 // Emit initial sections.
930 if (!useSplitDwarf()) {
931 // Emit all the DIEs into a debug info section.
934 // Corresponding abbreviations into a abbrev section.
937 // Emit info into a debug loc section.
940 // Emit info into a debug aranges section.
943 // Emit info into a debug ranges section.
946 // Emit info into a debug macinfo section.
950 // TODO: When we don't need the option anymore we
951 // can remove all of the code that this section
953 if (useDarwinGDBCompat())
954 emitDebugInlineInfo();
956 // TODO: Fill this in for separated debug sections and separate
957 // out information into new sections.
959 // Emit the debug info section and compile units.
963 // Corresponding abbreviations into a abbrev section.
965 emitDebugAbbrevDWO();
967 // Emit info into a debug loc section.
970 // Emit info into a debug aranges section.
973 // Emit info into a debug ranges section.
976 // Emit info into a debug macinfo section.
980 // TODO: When we don't need the option anymore we
981 // can remove all of the code that this section
983 if (useDarwinGDBCompat())
984 emitDebugInlineInfo();
987 // Emit info into the dwarf accelerator table sections.
988 if (useDwarfAccelTables()) {
991 emitAccelNamespaces();
995 // Emit info into a debug pubtypes section.
996 // TODO: When we don't need the option anymore we can
997 // remove all of the code that adds to the table.
998 if (useDarwinGDBCompat())
1001 // Finally emit string information into a string table.
1003 if (useSplitDwarf())
1008 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1009 E = CUMap.end(); I != E; ++I)
1014 // Reset these for the next Module if we have one.
1019 // Find abstract variable, if any, associated with Var.
1020 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1021 DebugLoc ScopeLoc) {
1022 LLVMContext &Ctx = DV->getContext();
1023 // More then one inlined variable corresponds to one abstract variable.
1024 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1025 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1027 return AbsDbgVariable;
1029 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1033 AbsDbgVariable = new DbgVariable(Var, NULL);
1034 addScopeVariable(Scope, AbsDbgVariable);
1035 AbstractVariables[Var] = AbsDbgVariable;
1036 return AbsDbgVariable;
1039 // If Var is a current function argument then add it to CurrentFnArguments list.
1040 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1041 DbgVariable *Var, LexicalScope *Scope) {
1042 if (!LScopes.isCurrentFunctionScope(Scope))
1044 DIVariable DV = Var->getVariable();
1045 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1047 unsigned ArgNo = DV.getArgNumber();
1051 size_t Size = CurrentFnArguments.size();
1053 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1054 // llvm::Function argument size is not good indicator of how many
1055 // arguments does the function have at source level.
1057 CurrentFnArguments.resize(ArgNo * 2);
1058 CurrentFnArguments[ArgNo - 1] = Var;
1062 // Collect variable information from side table maintained by MMI.
1064 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1065 SmallPtrSet<const MDNode *, 16> &Processed) {
1066 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1067 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1068 VE = VMap.end(); VI != VE; ++VI) {
1069 const MDNode *Var = VI->first;
1071 Processed.insert(Var);
1073 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1075 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1077 // If variable scope is not found then skip this variable.
1081 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1082 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1083 RegVar->setFrameIndex(VP.first);
1084 if (!addCurrentFnArgument(MF, RegVar, Scope))
1085 addScopeVariable(Scope, RegVar);
1087 AbsDbgVariable->setFrameIndex(VP.first);
1091 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1093 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1094 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1095 return MI->getNumOperands() == 3 &&
1096 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1097 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1100 // Get .debug_loc entry for the instruction range starting at MI.
1101 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1102 const MCSymbol *FLabel,
1103 const MCSymbol *SLabel,
1104 const MachineInstr *MI) {
1105 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1107 if (MI->getNumOperands() != 3) {
1108 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1109 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1111 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1112 MachineLocation MLoc;
1113 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1114 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1116 if (MI->getOperand(0).isImm())
1117 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1118 if (MI->getOperand(0).isFPImm())
1119 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1120 if (MI->getOperand(0).isCImm())
1121 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1123 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1126 // Find variables for each lexical scope.
1128 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1129 SmallPtrSet<const MDNode *, 16> &Processed) {
1131 // collection info from MMI table.
1132 collectVariableInfoFromMMITable(MF, Processed);
1134 for (SmallVectorImpl<const MDNode*>::const_iterator
1135 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1137 const MDNode *Var = *UVI;
1138 if (Processed.count(Var))
1141 // History contains relevant DBG_VALUE instructions for Var and instructions
1143 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1144 if (History.empty())
1146 const MachineInstr *MInsn = History.front();
1149 LexicalScope *Scope = NULL;
1150 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1151 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1152 Scope = LScopes.getCurrentFunctionScope();
1154 if (DV.getVersion() <= LLVMDebugVersion9)
1155 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1157 if (MDNode *IA = DV.getInlinedAt())
1158 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1160 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1163 // If variable scope is not found then skip this variable.
1167 Processed.insert(DV);
1168 assert(MInsn->isDebugValue() && "History must begin with debug value");
1169 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1170 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1171 if (!addCurrentFnArgument(MF, RegVar, Scope))
1172 addScopeVariable(Scope, RegVar);
1174 AbsVar->setMInsn(MInsn);
1176 // Simplify ranges that are fully coalesced.
1177 if (History.size() <= 1 || (History.size() == 2 &&
1178 MInsn->isIdenticalTo(History.back()))) {
1179 RegVar->setMInsn(MInsn);
1183 // handle multiple DBG_VALUE instructions describing one variable.
1184 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1186 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1187 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1188 const MachineInstr *Begin = *HI;
1189 assert(Begin->isDebugValue() && "Invalid History entry");
1191 // Check if DBG_VALUE is truncating a range.
1192 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1193 && !Begin->getOperand(0).getReg())
1196 // Compute the range for a register location.
1197 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1198 const MCSymbol *SLabel = 0;
1201 // If Begin is the last instruction in History then its value is valid
1202 // until the end of the function.
1203 SLabel = FunctionEndSym;
1205 const MachineInstr *End = HI[1];
1206 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1207 << "\t" << *Begin << "\t" << *End << "\n");
1208 if (End->isDebugValue())
1209 SLabel = getLabelBeforeInsn(End);
1211 // End is a normal instruction clobbering the range.
1212 SLabel = getLabelAfterInsn(End);
1213 assert(SLabel && "Forgot label after clobber instruction");
1218 // The value is valid until the next DBG_VALUE or clobber.
1219 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1222 DotDebugLocEntries.push_back(DotDebugLocEntry());
1225 // Collect info for variables that were optimized out.
1226 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1227 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1228 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1229 DIVariable DV(Variables.getElement(i));
1230 if (!DV || !DV.Verify() || !Processed.insert(DV))
1232 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1233 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1237 // Return Label preceding the instruction.
1238 const MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1239 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1240 assert(Label && "Didn't insert label before instruction");
1244 // Return Label immediately following the instruction.
1245 const MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1246 return LabelsAfterInsn.lookup(MI);
1249 // Process beginning of an instruction.
1250 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1251 // Check if source location changes, but ignore DBG_VALUE locations.
1252 if (!MI->isDebugValue()) {
1253 DebugLoc DL = MI->getDebugLoc();
1254 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1257 if (DL == PrologEndLoc) {
1258 Flags |= DWARF2_FLAG_PROLOGUE_END;
1259 PrologEndLoc = DebugLoc();
1261 if (PrologEndLoc.isUnknown())
1262 Flags |= DWARF2_FLAG_IS_STMT;
1264 if (!DL.isUnknown()) {
1265 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1266 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1268 recordSourceLine(0, 0, 0, 0);
1272 // Insert labels where requested.
1273 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1274 LabelsBeforeInsn.find(MI);
1277 if (I == LabelsBeforeInsn.end())
1280 // Label already assigned.
1285 PrevLabel = MMI->getContext().CreateTempSymbol();
1286 Asm->OutStreamer.EmitLabel(PrevLabel);
1288 I->second = PrevLabel;
1291 // Process end of an instruction.
1292 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1293 // Don't create a new label after DBG_VALUE instructions.
1294 // They don't generate code.
1295 if (!MI->isDebugValue())
1298 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1299 LabelsAfterInsn.find(MI);
1302 if (I == LabelsAfterInsn.end())
1305 // Label already assigned.
1309 // We need a label after this instruction.
1311 PrevLabel = MMI->getContext().CreateTempSymbol();
1312 Asm->OutStreamer.EmitLabel(PrevLabel);
1314 I->second = PrevLabel;
1317 // Each LexicalScope has first instruction and last instruction to mark
1318 // beginning and end of a scope respectively. Create an inverse map that list
1319 // scopes starts (and ends) with an instruction. One instruction may start (or
1320 // end) multiple scopes. Ignore scopes that are not reachable.
1321 void DwarfDebug::identifyScopeMarkers() {
1322 SmallVector<LexicalScope *, 4> WorkList;
1323 WorkList.push_back(LScopes.getCurrentFunctionScope());
1324 while (!WorkList.empty()) {
1325 LexicalScope *S = WorkList.pop_back_val();
1327 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1328 if (!Children.empty())
1329 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1330 SE = Children.end(); SI != SE; ++SI)
1331 WorkList.push_back(*SI);
1333 if (S->isAbstractScope())
1336 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1339 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1340 RE = Ranges.end(); RI != RE; ++RI) {
1341 assert(RI->first && "InsnRange does not have first instruction!");
1342 assert(RI->second && "InsnRange does not have second instruction!");
1343 requestLabelBeforeInsn(RI->first);
1344 requestLabelAfterInsn(RI->second);
1349 // Get MDNode for DebugLoc's scope.
1350 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1351 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1352 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1353 return DL.getScope(Ctx);
1356 // Walk up the scope chain of given debug loc and find line number info
1357 // for the function.
1358 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1359 const MDNode *Scope = getScopeNode(DL, Ctx);
1360 DISubprogram SP = getDISubprogram(Scope);
1362 // Check for number of operands since the compatibility is
1364 if (SP->getNumOperands() > 19)
1365 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1367 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1373 // Gather pre-function debug information. Assumes being called immediately
1374 // after the function entry point has been emitted.
1375 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1376 if (!MMI->hasDebugInfo()) return;
1377 LScopes.initialize(*MF);
1378 if (LScopes.empty()) return;
1379 identifyScopeMarkers();
1381 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1382 Asm->getFunctionNumber());
1383 // Assumes in correct section after the entry point.
1384 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1386 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1388 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1389 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1390 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1392 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1394 bool AtBlockEntry = true;
1395 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1397 const MachineInstr *MI = II;
1399 if (MI->isDebugValue()) {
1400 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1402 // Keep track of user variables.
1404 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1406 // Variable is in a register, we need to check for clobbers.
1407 if (isDbgValueInDefinedReg(MI))
1408 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1410 // Check the history of this variable.
1411 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1412 if (History.empty()) {
1413 UserVariables.push_back(Var);
1414 // The first mention of a function argument gets the FunctionBeginSym
1415 // label, so arguments are visible when breaking at function entry.
1417 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1418 DISubprogram(getDISubprogram(DV.getContext()))
1419 .describes(MF->getFunction()))
1420 LabelsBeforeInsn[MI] = FunctionBeginSym;
1422 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1423 const MachineInstr *Prev = History.back();
1424 if (Prev->isDebugValue()) {
1425 // Coalesce identical entries at the end of History.
1426 if (History.size() >= 2 &&
1427 Prev->isIdenticalTo(History[History.size() - 2])) {
1428 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1430 << "\t" << *History[History.size() - 2] << "\n");
1434 // Terminate old register assignments that don't reach MI;
1435 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1436 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1437 isDbgValueInDefinedReg(Prev)) {
1438 // Previous register assignment needs to terminate at the end of
1440 MachineBasicBlock::const_iterator LastMI =
1441 PrevMBB->getLastNonDebugInstr();
1442 if (LastMI == PrevMBB->end()) {
1443 // Drop DBG_VALUE for empty range.
1444 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1445 << "\t" << *Prev << "\n");
1449 // Terminate after LastMI.
1450 History.push_back(LastMI);
1455 History.push_back(MI);
1457 // Not a DBG_VALUE instruction.
1459 AtBlockEntry = false;
1461 // First known non-DBG_VALUE and non-frame setup location marks
1462 // the beginning of the function body.
1463 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1464 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1465 PrologEndLoc = MI->getDebugLoc();
1467 // Check if the instruction clobbers any registers with debug vars.
1468 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1469 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1470 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1472 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1473 AI.isValid(); ++AI) {
1475 const MDNode *Var = LiveUserVar[Reg];
1478 // Reg is now clobbered.
1479 LiveUserVar[Reg] = 0;
1481 // Was MD last defined by a DBG_VALUE referring to Reg?
1482 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1483 if (HistI == DbgValues.end())
1485 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1486 if (History.empty())
1488 const MachineInstr *Prev = History.back();
1489 // Sanity-check: Register assignments are terminated at the end of
1491 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1493 // Is the variable still in Reg?
1494 if (!isDbgValueInDefinedReg(Prev) ||
1495 Prev->getOperand(0).getReg() != Reg)
1497 // Var is clobbered. Make sure the next instruction gets a label.
1498 History.push_back(MI);
1505 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1507 SmallVectorImpl<const MachineInstr*> &History = I->second;
1508 if (History.empty())
1511 // Make sure the final register assignments are terminated.
1512 const MachineInstr *Prev = History.back();
1513 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1514 const MachineBasicBlock *PrevMBB = Prev->getParent();
1515 MachineBasicBlock::const_iterator LastMI =
1516 PrevMBB->getLastNonDebugInstr();
1517 if (LastMI == PrevMBB->end())
1518 // Drop DBG_VALUE for empty range.
1521 // Terminate after LastMI.
1522 History.push_back(LastMI);
1525 // Request labels for the full history.
1526 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1527 const MachineInstr *MI = History[i];
1528 if (MI->isDebugValue())
1529 requestLabelBeforeInsn(MI);
1531 requestLabelAfterInsn(MI);
1535 PrevInstLoc = DebugLoc();
1536 PrevLabel = FunctionBeginSym;
1538 // Record beginning of function.
1539 if (!PrologEndLoc.isUnknown()) {
1540 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1541 MF->getFunction()->getContext());
1542 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1543 FnStartDL.getScope(MF->getFunction()->getContext()),
1544 // We'd like to list the prologue as "not statements" but GDB behaves
1545 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1546 DWARF2_FLAG_IS_STMT);
1550 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1551 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1552 ScopeVariables[LS].push_back(Var);
1553 // Vars.push_back(Var);
1556 // Gather and emit post-function debug information.
1557 void DwarfDebug::endFunction(const MachineFunction *MF) {
1558 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1560 // Define end label for subprogram.
1561 FunctionEndSym = Asm->GetTempSymbol("func_end",
1562 Asm->getFunctionNumber());
1563 // Assumes in correct section after the entry point.
1564 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1566 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1567 collectVariableInfo(MF, ProcessedVars);
1569 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1570 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1571 assert(TheCU && "Unable to find compile unit!");
1573 // Construct abstract scopes.
1574 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1575 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1576 LexicalScope *AScope = AList[i];
1577 DISubprogram SP(AScope->getScopeNode());
1579 // Collect info for variables that were optimized out.
1580 DIArray Variables = SP.getVariables();
1581 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1582 DIVariable DV(Variables.getElement(i));
1583 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1585 // Check that DbgVariable for DV wasn't created earlier, when
1586 // findAbstractVariable() was called for inlined instance of DV.
1587 LLVMContext &Ctx = DV->getContext();
1588 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1589 if (AbstractVariables.lookup(CleanDV))
1591 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1592 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1595 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1596 constructScopeDIE(TheCU, AScope);
1599 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1601 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1602 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1604 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1605 MMI->getFrameMoves()));
1608 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1609 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1610 DeleteContainerPointers(I->second);
1611 ScopeVariables.clear();
1612 DeleteContainerPointers(CurrentFnArguments);
1613 UserVariables.clear();
1615 AbstractVariables.clear();
1616 LabelsBeforeInsn.clear();
1617 LabelsAfterInsn.clear();
1621 // Register a source line with debug info. Returns the unique label that was
1622 // emitted and which provides correspondence to the source line list.
1623 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1629 DIDescriptor Scope(S);
1631 if (Scope.isCompileUnit()) {
1632 DICompileUnit CU(S);
1633 Fn = CU.getFilename();
1634 Dir = CU.getDirectory();
1635 } else if (Scope.isFile()) {
1637 Fn = F.getFilename();
1638 Dir = F.getDirectory();
1639 } else if (Scope.isSubprogram()) {
1641 Fn = SP.getFilename();
1642 Dir = SP.getDirectory();
1643 } else if (Scope.isLexicalBlockFile()) {
1644 DILexicalBlockFile DBF(S);
1645 Fn = DBF.getFilename();
1646 Dir = DBF.getDirectory();
1647 } else if (Scope.isLexicalBlock()) {
1648 DILexicalBlock DB(S);
1649 Fn = DB.getFilename();
1650 Dir = DB.getDirectory();
1652 llvm_unreachable("Unexpected scope info");
1654 Src = getOrCreateSourceID(Fn, Dir);
1656 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1659 //===----------------------------------------------------------------------===//
1661 //===----------------------------------------------------------------------===//
1663 // Compute the size and offset of a DIE.
1665 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1666 // Get the children.
1667 const std::vector<DIE *> &Children = Die->getChildren();
1669 // Record the abbreviation.
1670 assignAbbrevNumber(Die->getAbbrev());
1672 // Get the abbreviation for this DIE.
1673 unsigned AbbrevNumber = Die->getAbbrevNumber();
1674 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1677 Die->setOffset(Offset);
1679 // Start the size with the size of abbreviation code.
1680 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1682 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1683 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1685 // Size the DIE attribute values.
1686 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1687 // Size attribute value.
1688 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1690 // Size the DIE children if any.
1691 if (!Children.empty()) {
1692 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1693 "Children flag not set");
1695 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1696 Offset = computeSizeAndOffset(Children[j], Offset);
1698 // End of children marker.
1699 Offset += sizeof(int8_t);
1702 Die->setSize(Offset - Die->getOffset());
1706 // Compute the size and offset of all the DIEs.
1707 void DwarfUnits::computeSizeAndOffsets() {
1708 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1709 E = CUs.end(); I != E; ++I) {
1711 sizeof(int32_t) + // Length of Compilation Unit Info
1712 sizeof(int16_t) + // DWARF version number
1713 sizeof(int32_t) + // Offset Into Abbrev. Section
1714 sizeof(int8_t); // Pointer Size (in bytes)
1716 computeSizeAndOffset((*I)->getCUDie(), Offset);
1720 // Emit initial Dwarf sections with a label at the start of each one.
1721 void DwarfDebug::emitSectionLabels() {
1722 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1724 // Dwarf sections base addresses.
1725 DwarfInfoSectionSym =
1726 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1727 DwarfAbbrevSectionSym =
1728 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1729 if (useSplitDwarf())
1730 DwarfAbbrevDWOSectionSym =
1731 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1732 "section_abbrev_dwo");
1733 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1735 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1736 emitSectionSym(Asm, MacroInfo);
1738 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1739 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1740 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1741 DwarfStrSectionSym =
1742 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1743 if (useSplitDwarf())
1744 DwarfStrDWOSectionSym =
1745 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1746 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1749 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1750 "section_debug_loc");
1752 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1753 emitSectionSym(Asm, TLOF.getDataSection());
1756 // Recursively emits a debug information entry.
1757 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1758 // Get the abbreviation for this DIE.
1759 unsigned AbbrevNumber = Die->getAbbrevNumber();
1760 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1762 // Emit the code (index) for the abbreviation.
1763 if (Asm->isVerbose())
1764 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1765 Twine::utohexstr(Die->getOffset()) + ":0x" +
1766 Twine::utohexstr(Die->getSize()) + " " +
1767 dwarf::TagString(Abbrev->getTag()));
1768 Asm->EmitULEB128(AbbrevNumber);
1770 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1771 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1773 // Emit the DIE attribute values.
1774 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1775 unsigned Attr = AbbrevData[i].getAttribute();
1776 unsigned Form = AbbrevData[i].getForm();
1777 assert(Form && "Too many attributes for DIE (check abbreviation)");
1779 if (Asm->isVerbose())
1780 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1783 case dwarf::DW_AT_abstract_origin: {
1784 DIEEntry *E = cast<DIEEntry>(Values[i]);
1785 DIE *Origin = E->getEntry();
1786 unsigned Addr = Origin->getOffset();
1787 Asm->EmitInt32(Addr);
1790 case dwarf::DW_AT_ranges: {
1791 // DW_AT_range Value encodes offset in debug_range section.
1792 DIEInteger *V = cast<DIEInteger>(Values[i]);
1794 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1795 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1799 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1801 DwarfDebugRangeSectionSym,
1806 case dwarf::DW_AT_location: {
1807 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1808 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1809 Asm->EmitLabelReference(L->getValue(), 4);
1811 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1813 Values[i]->EmitValue(Asm, Form);
1817 case dwarf::DW_AT_accessibility: {
1818 if (Asm->isVerbose()) {
1819 DIEInteger *V = cast<DIEInteger>(Values[i]);
1820 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1822 Values[i]->EmitValue(Asm, Form);
1826 // Emit an attribute using the defined form.
1827 Values[i]->EmitValue(Asm, Form);
1832 // Emit the DIE children if any.
1833 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1834 const std::vector<DIE *> &Children = Die->getChildren();
1836 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1837 emitDIE(Children[j], Abbrevs);
1839 if (Asm->isVerbose())
1840 Asm->OutStreamer.AddComment("End Of Children Mark");
1845 // Emit the various dwarf units to the unit section USection with
1846 // the abbreviations going into ASection.
1847 void DwarfUnits::emitUnits(DwarfDebug *DD,
1848 const MCSection *USection,
1849 const MCSection *ASection,
1850 const MCSymbol *ASectionSym) {
1851 Asm->OutStreamer.SwitchSection(USection);
1852 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1853 E = CUs.end(); I != E; ++I) {
1854 CompileUnit *TheCU = *I;
1855 DIE *Die = TheCU->getCUDie();
1857 // Emit the compile units header.
1859 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1860 TheCU->getUniqueID()));
1862 // Emit size of content not including length itself
1863 unsigned ContentSize = Die->getSize() +
1864 sizeof(int16_t) + // DWARF version number
1865 sizeof(int32_t) + // Offset Into Abbrev. Section
1866 sizeof(int8_t); // Pointer Size (in bytes)
1868 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1869 Asm->EmitInt32(ContentSize);
1870 Asm->OutStreamer.AddComment("DWARF version number");
1871 Asm->EmitInt16(dwarf::DWARF_VERSION);
1872 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1873 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1875 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1876 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1878 DD->emitDIE(Die, Abbreviations);
1879 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1880 TheCU->getUniqueID()));
1884 // Emit the debug info section.
1885 void DwarfDebug::emitDebugInfo() {
1886 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1888 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1889 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1890 DwarfAbbrevSectionSym);
1893 // Emit the abbreviation section.
1894 void DwarfDebug::emitAbbreviations() {
1895 if (!useSplitDwarf())
1896 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1899 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1902 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1903 std::vector<DIEAbbrev *> *Abbrevs) {
1904 // Check to see if it is worth the effort.
1905 if (!Abbrevs->empty()) {
1906 // Start the debug abbrev section.
1907 Asm->OutStreamer.SwitchSection(Section);
1909 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1910 Asm->OutStreamer.EmitLabel(Begin);
1912 // For each abbrevation.
1913 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1914 // Get abbreviation data
1915 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1917 // Emit the abbrevations code (base 1 index.)
1918 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1920 // Emit the abbreviations data.
1924 // Mark end of abbreviations.
1925 Asm->EmitULEB128(0, "EOM(3)");
1927 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1928 Asm->OutStreamer.EmitLabel(End);
1932 // Emit the last address of the section and the end of the line matrix.
1933 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1934 // Define last address of section.
1935 Asm->OutStreamer.AddComment("Extended Op");
1938 Asm->OutStreamer.AddComment("Op size");
1939 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1940 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1941 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1943 Asm->OutStreamer.AddComment("Section end label");
1945 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1946 Asm->getDataLayout().getPointerSize(),
1949 // Mark end of matrix.
1950 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1956 // Emit visible names into a hashed accelerator table section.
1957 void DwarfDebug::emitAccelNames() {
1958 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1959 dwarf::DW_FORM_data4));
1960 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1961 E = CUMap.end(); I != E; ++I) {
1962 CompileUnit *TheCU = I->second;
1963 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1964 for (StringMap<std::vector<DIE*> >::const_iterator
1965 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1966 const char *Name = GI->getKeyData();
1967 const std::vector<DIE *> &Entities = GI->second;
1968 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1969 DE = Entities.end(); DI != DE; ++DI)
1970 AT.AddName(Name, (*DI));
1974 AT.FinalizeTable(Asm, "Names");
1975 Asm->OutStreamer.SwitchSection(
1976 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1977 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1978 Asm->OutStreamer.EmitLabel(SectionBegin);
1980 // Emit the full data.
1981 AT.Emit(Asm, SectionBegin, &InfoHolder);
1984 // Emit objective C classes and categories into a hashed accelerator table
1986 void DwarfDebug::emitAccelObjC() {
1987 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1988 dwarf::DW_FORM_data4));
1989 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1990 E = CUMap.end(); I != E; ++I) {
1991 CompileUnit *TheCU = I->second;
1992 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
1993 for (StringMap<std::vector<DIE*> >::const_iterator
1994 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1995 const char *Name = GI->getKeyData();
1996 const std::vector<DIE *> &Entities = GI->second;
1997 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1998 DE = Entities.end(); DI != DE; ++DI)
1999 AT.AddName(Name, (*DI));
2003 AT.FinalizeTable(Asm, "ObjC");
2004 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2005 .getDwarfAccelObjCSection());
2006 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2007 Asm->OutStreamer.EmitLabel(SectionBegin);
2009 // Emit the full data.
2010 AT.Emit(Asm, SectionBegin, &InfoHolder);
2013 // Emit namespace dies into a hashed accelerator table.
2014 void DwarfDebug::emitAccelNamespaces() {
2015 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2016 dwarf::DW_FORM_data4));
2017 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2018 E = CUMap.end(); I != E; ++I) {
2019 CompileUnit *TheCU = I->second;
2020 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2021 for (StringMap<std::vector<DIE*> >::const_iterator
2022 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2023 const char *Name = GI->getKeyData();
2024 const std::vector<DIE *> &Entities = GI->second;
2025 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2026 DE = Entities.end(); DI != DE; ++DI)
2027 AT.AddName(Name, (*DI));
2031 AT.FinalizeTable(Asm, "namespac");
2032 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2033 .getDwarfAccelNamespaceSection());
2034 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2035 Asm->OutStreamer.EmitLabel(SectionBegin);
2037 // Emit the full data.
2038 AT.Emit(Asm, SectionBegin, &InfoHolder);
2041 // Emit type dies into a hashed accelerator table.
2042 void DwarfDebug::emitAccelTypes() {
2043 std::vector<DwarfAccelTable::Atom> Atoms;
2044 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2045 dwarf::DW_FORM_data4));
2046 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2047 dwarf::DW_FORM_data2));
2048 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2049 dwarf::DW_FORM_data1));
2050 DwarfAccelTable AT(Atoms);
2051 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2052 E = CUMap.end(); I != E; ++I) {
2053 CompileUnit *TheCU = I->second;
2054 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2055 = TheCU->getAccelTypes();
2056 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2057 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2058 const char *Name = GI->getKeyData();
2059 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2060 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2061 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2062 AT.AddName(Name, (*DI).first, (*DI).second);
2066 AT.FinalizeTable(Asm, "types");
2067 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2068 .getDwarfAccelTypesSection());
2069 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2070 Asm->OutStreamer.EmitLabel(SectionBegin);
2072 // Emit the full data.
2073 AT.Emit(Asm, SectionBegin, &InfoHolder);
2076 void DwarfDebug::emitDebugPubTypes() {
2077 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2078 E = CUMap.end(); I != E; ++I) {
2079 CompileUnit *TheCU = I->second;
2080 // Start the dwarf pubtypes section.
2081 Asm->OutStreamer.SwitchSection(
2082 Asm->getObjFileLowering().getDwarfPubTypesSection());
2083 Asm->OutStreamer.AddComment("Length of Public Types Info");
2084 Asm->EmitLabelDifference(
2085 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2086 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2088 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2089 TheCU->getUniqueID()));
2091 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2092 Asm->EmitInt16(dwarf::DWARF_VERSION);
2094 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2095 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2096 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2097 TheCU->getUniqueID()),
2098 DwarfInfoSectionSym);
2100 Asm->OutStreamer.AddComment("Compilation Unit Length");
2101 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2102 TheCU->getUniqueID()),
2103 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2104 TheCU->getUniqueID()),
2107 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2108 for (StringMap<DIE*>::const_iterator
2109 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2110 const char *Name = GI->getKeyData();
2111 DIE *Entity = GI->second;
2113 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2114 Asm->EmitInt32(Entity->getOffset());
2116 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2117 // Emit the name with a terminating null byte.
2118 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1), 0);
2121 Asm->OutStreamer.AddComment("End Mark");
2123 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2124 TheCU->getUniqueID()));
2128 // Emit strings into a string section.
2129 void DwarfUnits::emitStrings(const MCSection *StrSection,
2130 const MCSection *OffsetSection = NULL,
2131 const MCSymbol *StrSecSym = NULL) {
2133 if (StringPool->empty()) return;
2135 // Start the dwarf str section.
2136 Asm->OutStreamer.SwitchSection(StrSection);
2138 // Get all of the string pool entries and put them in an array by their ID so
2139 // we can sort them.
2140 SmallVector<std::pair<unsigned,
2141 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2143 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2144 I = StringPool->begin(), E = StringPool->end();
2146 Entries.push_back(std::make_pair(I->second.second, &*I));
2148 array_pod_sort(Entries.begin(), Entries.end());
2150 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2151 // Emit a label for reference from debug information entries.
2152 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2154 // Emit the string itself with a terminating null byte.
2155 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2156 Entries[i].second->getKeyLength()+1),
2160 // If we've got an offset section go ahead and emit that now as well.
2161 if (OffsetSection) {
2162 Asm->OutStreamer.SwitchSection(OffsetSection);
2163 unsigned offset = 0;
2165 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2166 Asm->OutStreamer.EmitIntValue(offset, size, 0);
2167 offset += Entries[i].second->getKeyLength() + 1;
2172 // Emit visible names into a debug str section.
2173 void DwarfDebug::emitDebugStr() {
2174 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2175 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2178 // Emit visible names into a debug loc section.
2179 void DwarfDebug::emitDebugLoc() {
2180 if (DotDebugLocEntries.empty())
2183 for (SmallVector<DotDebugLocEntry, 4>::iterator
2184 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2186 DotDebugLocEntry &Entry = *I;
2187 if (I + 1 != DotDebugLocEntries.end())
2191 // Start the dwarf loc section.
2192 Asm->OutStreamer.SwitchSection(
2193 Asm->getObjFileLowering().getDwarfLocSection());
2194 unsigned char Size = Asm->getDataLayout().getPointerSize();
2195 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2197 for (SmallVector<DotDebugLocEntry, 4>::iterator
2198 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2199 I != E; ++I, ++index) {
2200 DotDebugLocEntry &Entry = *I;
2201 if (Entry.isMerged()) continue;
2202 if (Entry.isEmpty()) {
2203 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2204 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2205 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2207 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size, 0);
2208 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size, 0);
2209 DIVariable DV(Entry.Variable);
2210 Asm->OutStreamer.AddComment("Loc expr size");
2211 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2212 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2213 Asm->EmitLabelDifference(end, begin, 2);
2214 Asm->OutStreamer.EmitLabel(begin);
2215 if (Entry.isInt()) {
2216 DIBasicType BTy(DV.getType());
2218 (BTy.getEncoding() == dwarf::DW_ATE_signed
2219 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2220 Asm->OutStreamer.AddComment("DW_OP_consts");
2221 Asm->EmitInt8(dwarf::DW_OP_consts);
2222 Asm->EmitSLEB128(Entry.getInt());
2224 Asm->OutStreamer.AddComment("DW_OP_constu");
2225 Asm->EmitInt8(dwarf::DW_OP_constu);
2226 Asm->EmitULEB128(Entry.getInt());
2228 } else if (Entry.isLocation()) {
2229 if (!DV.hasComplexAddress())
2231 Asm->EmitDwarfRegOp(Entry.Loc);
2233 // Complex address entry.
2234 unsigned N = DV.getNumAddrElements();
2236 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2237 if (Entry.Loc.getOffset()) {
2239 Asm->EmitDwarfRegOp(Entry.Loc);
2240 Asm->OutStreamer.AddComment("DW_OP_deref");
2241 Asm->EmitInt8(dwarf::DW_OP_deref);
2242 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2243 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2244 Asm->EmitSLEB128(DV.getAddrElement(1));
2246 // If first address element is OpPlus then emit
2247 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2248 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2249 Asm->EmitDwarfRegOp(Loc);
2253 Asm->EmitDwarfRegOp(Entry.Loc);
2256 // Emit remaining complex address elements.
2257 for (; i < N; ++i) {
2258 uint64_t Element = DV.getAddrElement(i);
2259 if (Element == DIBuilder::OpPlus) {
2260 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2261 Asm->EmitULEB128(DV.getAddrElement(++i));
2262 } else if (Element == DIBuilder::OpDeref) {
2263 if (!Entry.Loc.isReg())
2264 Asm->EmitInt8(dwarf::DW_OP_deref);
2266 llvm_unreachable("unknown Opcode found in complex address");
2270 // else ... ignore constant fp. There is not any good way to
2271 // to represent them here in dwarf.
2272 Asm->OutStreamer.EmitLabel(end);
2277 // Emit visible names into a debug aranges section.
2278 void DwarfDebug::emitDebugARanges() {
2279 // Start the dwarf aranges section.
2280 Asm->OutStreamer.SwitchSection(
2281 Asm->getObjFileLowering().getDwarfARangesSection());
2284 // Emit visible names into a debug ranges section.
2285 void DwarfDebug::emitDebugRanges() {
2286 // Start the dwarf ranges section.
2287 Asm->OutStreamer.SwitchSection(
2288 Asm->getObjFileLowering().getDwarfRangesSection());
2289 unsigned char Size = Asm->getDataLayout().getPointerSize();
2290 for (SmallVector<const MCSymbol *, 8>::iterator
2291 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2294 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size, 0);
2296 Asm->OutStreamer.EmitIntValue(0, Size, /*addrspace*/0);
2300 // Emit visible names into a debug macinfo section.
2301 void DwarfDebug::emitDebugMacInfo() {
2302 if (const MCSection *LineInfo =
2303 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2304 // Start the dwarf macinfo section.
2305 Asm->OutStreamer.SwitchSection(LineInfo);
2309 // Emit inline info using following format.
2311 // 1. length of section
2312 // 2. Dwarf version number
2315 // Entries (one "entry" for each function that was inlined):
2317 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2318 // otherwise offset into __debug_str for regular function name.
2319 // 2. offset into __debug_str section for regular function name.
2320 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2321 // instances for the function.
2323 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2324 // inlined instance; the die_offset points to the inlined_subroutine die in the
2325 // __debug_info section, and the low_pc is the starting address for the
2326 // inlining instance.
2327 void DwarfDebug::emitDebugInlineInfo() {
2328 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2334 Asm->OutStreamer.SwitchSection(
2335 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2337 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2338 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2339 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2341 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2343 Asm->OutStreamer.AddComment("Dwarf Version");
2344 Asm->EmitInt16(dwarf::DWARF_VERSION);
2345 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2346 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2348 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2349 E = InlinedSPNodes.end(); I != E; ++I) {
2351 const MDNode *Node = *I;
2352 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2353 = InlineInfo.find(Node);
2354 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2355 DISubprogram SP(Node);
2356 StringRef LName = SP.getLinkageName();
2357 StringRef Name = SP.getName();
2359 Asm->OutStreamer.AddComment("MIPS linkage name");
2361 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2362 DwarfStrSectionSym);
2364 Asm->EmitSectionOffset(InfoHolder
2365 .getStringPoolEntry(getRealLinkageName(LName)),
2366 DwarfStrSectionSym);
2368 Asm->OutStreamer.AddComment("Function name");
2369 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2370 DwarfStrSectionSym);
2371 Asm->EmitULEB128(Labels.size(), "Inline count");
2373 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2374 LE = Labels.end(); LI != LE; ++LI) {
2375 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2376 Asm->EmitInt32(LI->second->getOffset());
2378 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2379 Asm->OutStreamer.EmitSymbolValue(LI->first,
2380 Asm->getDataLayout().getPointerSize(),0);
2384 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2387 // DWARF5 Experimental Separate Dwarf emitters.
2389 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2390 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2391 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2392 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2393 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2394 DICompileUnit DIUnit(N);
2395 StringRef FN = DIUnit.getFilename();
2396 CompilationDir = DIUnit.getDirectory();
2398 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2399 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2400 DIUnit.getLanguage(), Die, Asm,
2401 this, &SkeletonHolder);
2402 // FIXME: This should be the .dwo file.
2403 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2405 // FIXME: We also need DW_AT_addr_base and DW_AT_dwo_id.
2407 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2409 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2410 // DW_AT_stmt_list is a offset of line number information for this
2411 // compile unit in debug_line section.
2412 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2413 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
2414 Asm->GetTempSymbol("section_line"));
2416 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
2418 if (!CompilationDir.empty())
2419 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2421 SkeletonHolder.addUnit(NewCU);
2426 void DwarfDebug::emitSkeletonCU(const MCSection *Section) {
2427 Asm->OutStreamer.SwitchSection(Section);
2428 DIE *Die = SkeletonCU->getCUDie();
2430 // Emit the compile units header.
2431 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelBeginName(),
2432 SkeletonCU->getUniqueID()));
2434 // Emit size of content not including length itself
2435 unsigned ContentSize = Die->getSize() +
2436 sizeof(int16_t) + // DWARF version number
2437 sizeof(int32_t) + // Offset Into Abbrev. Section
2438 sizeof(int8_t); // Pointer Size (in bytes)
2440 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2441 Asm->EmitInt32(ContentSize);
2442 Asm->OutStreamer.AddComment("DWARF version number");
2443 Asm->EmitInt16(dwarf::DWARF_VERSION);
2444 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2446 const MCSection *ASec = Asm->getObjFileLowering().getDwarfAbbrevSection();
2447 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASec->getLabelBeginName()),
2448 DwarfAbbrevSectionSym);
2449 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2450 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2452 emitDIE(Die, &SkeletonAbbrevs);
2453 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelEndName(),
2454 SkeletonCU->getUniqueID()));
2457 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2458 assert(useSplitDwarf() && "No split dwarf debug info?");
2459 emitAbbrevs(Section, &SkeletonAbbrevs);
2462 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2463 // compile units that would normally be in debug_info.
2464 void DwarfDebug::emitDebugInfoDWO() {
2465 assert(useSplitDwarf() && "No split dwarf debug info?");
2466 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2467 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2468 DwarfAbbrevDWOSectionSym);
2471 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2472 // abbreviations for the .debug_info.dwo section.
2473 void DwarfDebug::emitDebugAbbrevDWO() {
2474 assert(useSplitDwarf() && "No split dwarf?");
2475 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2479 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2480 // string section and is identical in format to traditional .debug_str
2482 void DwarfDebug::emitDebugStrDWO() {
2483 assert(useSplitDwarf() && "No split dwarf?");
2484 const MCSection *OffSec = Asm->getObjFileLowering()
2485 .getDwarfStrOffDWOSection();
2486 const MCSymbol *StrSym = DwarfStrSectionSym;
2487 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),