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),
159 PrevLabel(NULL), GlobalCUIndexCount(0),
160 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
163 SkeletonAbbrevSet(InitAbbreviationsSetSize),
164 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
167 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
168 DwarfStrSectionSym = TextSectionSym = 0;
169 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = 0;
170 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
171 FunctionBeginSym = FunctionEndSym = 0;
173 // Turn on accelerator tables and older gdb compatibility
175 bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
176 if (DarwinGDBCompat == Default) {
178 IsDarwinGDBCompat = true;
180 IsDarwinGDBCompat = false;
182 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
184 if (DwarfAccelTables == Default) {
186 HasDwarfAccelTables = true;
188 HasDwarfAccelTables = false;
190 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
192 if (SplitDwarf == Default)
193 HasSplitDwarf = false;
195 HasSplitDwarf = SplitDwarf == Enable ? true : false;
198 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
202 DwarfDebug::~DwarfDebug() {
205 // Switch to the specified MCSection and emit an assembler
206 // temporary label to it if SymbolStem is specified.
207 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
208 const char *SymbolStem = 0) {
209 Asm->OutStreamer.SwitchSection(Section);
210 if (!SymbolStem) return 0;
212 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
213 Asm->OutStreamer.EmitLabel(TmpSym);
217 MCSymbol *DwarfUnits::getStringPoolSym() {
218 return Asm->GetTempSymbol(StringPref);
221 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
222 std::pair<MCSymbol*, unsigned> &Entry =
223 StringPool.GetOrCreateValue(Str).getValue();
224 if (Entry.first) return Entry.first;
226 Entry.second = NextStringPoolNumber++;
227 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
230 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
231 std::pair<MCSymbol*, unsigned> &Entry =
232 StringPool.GetOrCreateValue(Str).getValue();
233 if (Entry.first) return Entry.second;
235 Entry.second = NextStringPoolNumber++;
236 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
240 unsigned DwarfUnits::getAddrPoolIndex(MCSymbol *Sym) {
241 std::pair<MCSymbol*, unsigned> &Entry = AddressPool[Sym];
242 if (Entry.first) return Entry.second;
244 Entry.second = NextAddrPoolNumber++;
249 // Define a unique number for the abbreviation.
251 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
252 // Profile the node so that we can make it unique.
256 // Check the set for priors.
257 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
259 // If it's newly added.
260 if (InSet == &Abbrev) {
261 // Add to abbreviation list.
262 Abbreviations->push_back(&Abbrev);
264 // Assign the vector position + 1 as its number.
265 Abbrev.setNumber(Abbreviations->size());
267 // Assign existing abbreviation number.
268 Abbrev.setNumber(InSet->getNumber());
272 // If special LLVM prefix that is used to inform the asm
273 // printer to not emit usual symbol prefix before the symbol name is used then
274 // return linkage name after skipping this special LLVM prefix.
275 static StringRef getRealLinkageName(StringRef LinkageName) {
277 if (LinkageName.startswith(StringRef(&One, 1)))
278 return LinkageName.substr(1);
282 static bool isObjCClass(StringRef Name) {
283 return Name.startswith("+") || Name.startswith("-");
286 static bool hasObjCCategory(StringRef Name) {
287 if (!isObjCClass(Name)) return false;
289 size_t pos = Name.find(')');
290 if (pos != std::string::npos) {
291 if (Name[pos+1] != ' ') return false;
297 static void getObjCClassCategory(StringRef In, StringRef &Class,
298 StringRef &Category) {
299 if (!hasObjCCategory(In)) {
300 Class = In.slice(In.find('[') + 1, In.find(' '));
305 Class = In.slice(In.find('[') + 1, In.find('('));
306 Category = In.slice(In.find('[') + 1, In.find(' '));
310 static StringRef getObjCMethodName(StringRef In) {
311 return In.slice(In.find(' ') + 1, In.find(']'));
314 // Add the various names to the Dwarf accelerator table names.
315 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
317 if (!SP.isDefinition()) return;
319 TheCU->addAccelName(SP.getName(), Die);
321 // If the linkage name is different than the name, go ahead and output
322 // that as well into the name table.
323 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
324 TheCU->addAccelName(SP.getLinkageName(), Die);
326 // If this is an Objective-C selector name add it to the ObjC accelerator
328 if (isObjCClass(SP.getName())) {
329 StringRef Class, Category;
330 getObjCClassCategory(SP.getName(), Class, Category);
331 TheCU->addAccelObjC(Class, Die);
333 TheCU->addAccelObjC(Category, Die);
334 // Also add the base method name to the name table.
335 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
339 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
340 // and DW_AT_high_pc attributes. If there are global variables in this
341 // scope then create and insert DIEs for these variables.
342 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
343 const MDNode *SPNode) {
344 DIE *SPDie = SPCU->getDIE(SPNode);
346 assert(SPDie && "Unable to find subprogram DIE!");
347 DISubprogram SP(SPNode);
349 // If we're updating an abstract DIE, then we will be adding the children and
350 // object pointer later on. But what we don't want to do is process the
351 // concrete DIE twice.
352 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
353 // Pick up abstract subprogram DIE.
354 SPDie = new DIE(dwarf::DW_TAG_subprogram);
355 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
356 dwarf::DW_FORM_ref4, AbsSPDIE);
359 DISubprogram SPDecl = SP.getFunctionDeclaration();
360 if (!SPDecl.isSubprogram()) {
361 // There is not any need to generate specification DIE for a function
362 // defined at compile unit level. If a function is defined inside another
363 // function then gdb prefers the definition at top level and but does not
364 // expect specification DIE in parent function. So avoid creating
365 // specification DIE for a function defined inside a function.
366 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
367 !SP.getContext().isFile() &&
368 !isSubprogramContext(SP.getContext())) {
369 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
372 DICompositeType SPTy = SP.getType();
373 DIArray Args = SPTy.getTypeArray();
374 unsigned SPTag = SPTy.getTag();
375 if (SPTag == dwarf::DW_TAG_subroutine_type)
376 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
377 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
378 DIType ATy = DIType(Args.getElement(i));
379 SPCU->addType(Arg, ATy);
380 if (ATy.isArtificial())
381 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
382 if (ATy.isObjectPointer())
383 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
384 dwarf::DW_FORM_ref4, Arg);
385 SPDie->addChild(Arg);
387 DIE *SPDeclDie = SPDie;
388 SPDie = new DIE(dwarf::DW_TAG_subprogram);
389 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
390 dwarf::DW_FORM_ref4, SPDeclDie);
396 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
397 Asm->GetTempSymbol("func_begin",
398 Asm->getFunctionNumber()));
399 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
400 Asm->GetTempSymbol("func_end",
401 Asm->getFunctionNumber()));
402 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
403 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
404 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
406 // Add name to the name table, we do this here because we're guaranteed
407 // to have concrete versions of our DW_TAG_subprogram nodes.
408 addSubprogramNames(SPCU, SP, SPDie);
413 // Construct new DW_TAG_lexical_block for this scope and attach
414 // DW_AT_low_pc/DW_AT_high_pc labels.
415 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
416 LexicalScope *Scope) {
417 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
418 if (Scope->isAbstractScope())
421 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
425 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
426 if (Ranges.size() > 1) {
427 // .debug_range section has not been laid out yet. Emit offset in
428 // .debug_range as a uint, size 4, for now. emitDIE will handle
429 // DW_AT_ranges appropriately.
430 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
431 DebugRangeSymbols.size()
432 * Asm->getDataLayout().getPointerSize());
433 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
434 RE = Ranges.end(); RI != RE; ++RI) {
435 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
436 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
438 DebugRangeSymbols.push_back(NULL);
439 DebugRangeSymbols.push_back(NULL);
443 MCSymbol *Start = getLabelBeforeInsn(RI->first);
444 MCSymbol *End = getLabelAfterInsn(RI->second);
446 if (End == 0) return 0;
448 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
449 assert(End->isDefined() && "Invalid end label for an inlined scope!");
451 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
452 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
457 // This scope represents inlined body of a function. Construct DIE to
458 // represent this concrete inlined copy of the function.
459 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
460 LexicalScope *Scope) {
461 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
462 assert(Ranges.empty() == false &&
463 "LexicalScope does not have instruction markers!");
465 if (!Scope->getScopeNode())
467 DIScope DS(Scope->getScopeNode());
468 DISubprogram InlinedSP = getDISubprogram(DS);
469 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
471 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
475 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
476 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
477 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
479 if (StartLabel == 0 || EndLabel == 0) {
480 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
482 assert(StartLabel->isDefined() &&
483 "Invalid starting label for an inlined scope!");
484 assert(EndLabel->isDefined() &&
485 "Invalid end label for an inlined scope!");
487 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
488 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
489 dwarf::DW_FORM_ref4, OriginDIE);
491 if (Ranges.size() > 1) {
492 // .debug_range section has not been laid out yet. Emit offset in
493 // .debug_range as a uint, size 4, for now. emitDIE will handle
494 // DW_AT_ranges appropriately.
495 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
496 DebugRangeSymbols.size()
497 * Asm->getDataLayout().getPointerSize());
498 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
499 RE = Ranges.end(); RI != RE; ++RI) {
500 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
501 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
503 DebugRangeSymbols.push_back(NULL);
504 DebugRangeSymbols.push_back(NULL);
506 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
507 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
510 InlinedSubprogramDIEs.insert(OriginDIE);
512 // Track the start label for this inlined function.
513 //.debug_inlined section specification does not clearly state how
514 // to emit inlined scope that is split into multiple instruction ranges.
515 // For now, use first instruction range and emit low_pc/high_pc pair and
516 // corresponding .debug_inlined section entry for this pair.
517 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
518 I = InlineInfo.find(InlinedSP);
520 if (I == InlineInfo.end()) {
521 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
522 InlinedSPNodes.push_back(InlinedSP);
524 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
526 DILocation DL(Scope->getInlinedAt());
527 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
528 getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
529 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
531 // Add name to the name table, we do this here because we're guaranteed
532 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
533 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
538 // Construct a DIE for this scope.
539 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
540 if (!Scope || !Scope->getScopeNode())
543 SmallVector<DIE *, 8> Children;
544 DIE *ObjectPointer = NULL;
546 // Collect arguments for current function.
547 if (LScopes.isCurrentFunctionScope(Scope))
548 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
549 if (DbgVariable *ArgDV = CurrentFnArguments[i])
551 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
552 Children.push_back(Arg);
553 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
556 // Collect lexical scope children first.
557 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
558 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
560 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
561 Children.push_back(Variable);
562 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
564 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
565 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
566 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
567 Children.push_back(Nested);
568 DIScope DS(Scope->getScopeNode());
569 DIE *ScopeDIE = NULL;
570 if (Scope->getInlinedAt())
571 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
572 else if (DS.isSubprogram()) {
573 ProcessedSPNodes.insert(DS);
574 if (Scope->isAbstractScope()) {
575 ScopeDIE = TheCU->getDIE(DS);
576 // Note down abstract DIE.
578 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
581 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
584 // There is no need to emit empty lexical block DIE.
585 if (Children.empty())
587 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
590 if (!ScopeDIE) return NULL;
593 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
594 E = Children.end(); I != E; ++I)
595 ScopeDIE->addChild(*I);
597 if (DS.isSubprogram() && ObjectPointer != NULL)
598 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
599 dwarf::DW_FORM_ref4, ObjectPointer);
601 if (DS.isSubprogram())
602 TheCU->addPubTypes(DISubprogram(DS));
607 // Look up the source id with the given directory and source file names.
608 // If none currently exists, create a new id and insert it in the
609 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
611 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
613 // If FE did not provide a file name, then assume stdin.
614 if (FileName.empty())
615 return getOrCreateSourceID("<stdin>", StringRef());
617 // TODO: this might not belong here. See if we can factor this better.
618 if (DirName == CompilationDir)
621 unsigned SrcId = SourceIdMap.size()+1;
623 // We look up the file/dir pair by concatenating them with a zero byte.
624 SmallString<128> NamePair;
626 NamePair += '\0'; // Zero bytes are not allowed in paths.
627 NamePair += FileName;
629 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
630 if (Ent.getValue() != SrcId)
631 return Ent.getValue();
633 // Print out a .file directive to specify files for .loc directives.
634 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
639 // Create new CompileUnit for the given metadata node with tag
640 // DW_TAG_compile_unit.
641 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
642 DICompileUnit DIUnit(N);
643 StringRef FN = DIUnit.getFilename();
644 CompilationDir = DIUnit.getDirectory();
645 // Call this to emit a .file directive if it wasn't emitted for the source
646 // file this CU comes from yet.
647 getOrCreateSourceID(FN, CompilationDir);
649 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
650 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
651 DIUnit.getLanguage(), Die, Asm,
653 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
654 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
655 DIUnit.getLanguage());
656 NewCU->addString(Die, dwarf::DW_AT_name, FN);
657 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
658 // into an entity. We're using 0 (or a NULL label) for this.
659 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
660 // DW_AT_stmt_list is a offset of line number information for this
661 // compile unit in debug_line section.
662 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
663 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
664 Asm->GetTempSymbol("section_line"));
666 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
668 if (!CompilationDir.empty())
669 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
670 if (DIUnit.isOptimized())
671 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
673 StringRef Flags = DIUnit.getFlags();
675 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
677 if (unsigned RVer = DIUnit.getRunTimeVersion())
678 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
679 dwarf::DW_FORM_data1, RVer);
683 if (useSplitDwarf() && !SkeletonCU)
684 SkeletonCU = constructSkeletonCU(N);
686 InfoHolder.addUnit(NewCU);
688 CUMap.insert(std::make_pair(N, NewCU));
692 // Construct subprogram DIE.
693 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
695 CompileUnit *&CURef = SPMap[N];
701 if (!SP.isDefinition())
702 // This is a method declaration which will be handled while constructing
706 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
709 TheCU->insertDIE(N, SubprogramDie);
711 // Add to context owner.
712 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
717 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
718 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
719 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
720 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
721 const MDNode *N = NMD->getOperand(i);
722 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
723 constructSubprogramDIE(CU, N);
726 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
727 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
728 const MDNode *N = NMD->getOperand(i);
729 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
730 CU->createGlobalVariableDIE(N);
733 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
734 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
735 DIType Ty(NMD->getOperand(i));
736 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
737 CU->getOrCreateTypeDIE(Ty);
740 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
741 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
742 DIType Ty(NMD->getOperand(i));
743 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
744 CU->getOrCreateTypeDIE(Ty);
748 // Collect debug info using DebugInfoFinder.
749 // FIXME - Remove this when dragonegg switches to DIBuilder.
750 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
751 DebugInfoFinder DbgFinder;
752 DbgFinder.processModule(*M);
754 bool HasDebugInfo = false;
755 // Scan all the compile-units to see if there are any marked as the main
756 // unit. If not, we do not generate debug info.
757 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
758 E = DbgFinder.compile_unit_end(); I != E; ++I) {
759 if (DICompileUnit(*I).isMain()) {
764 if (!HasDebugInfo) return false;
766 // Create all the compile unit DIEs.
767 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
768 E = DbgFinder.compile_unit_end(); I != E; ++I)
769 constructCompileUnit(*I);
771 // Create DIEs for each global variable.
772 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
773 E = DbgFinder.global_variable_end(); I != E; ++I) {
774 const MDNode *N = *I;
775 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
776 CU->createGlobalVariableDIE(N);
779 // Create DIEs for each subprogram.
780 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
781 E = DbgFinder.subprogram_end(); I != E; ++I) {
782 const MDNode *N = *I;
783 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
784 constructSubprogramDIE(CU, N);
790 // Emit all Dwarf sections that should come prior to the content. Create
791 // global DIEs and emit initial debug info sections. This is invoked by
792 // the target AsmPrinter.
793 void DwarfDebug::beginModule() {
794 if (DisableDebugInfoPrinting)
797 const Module *M = MMI->getModule();
799 // If module has named metadata anchors then use them, otherwise scan the
800 // module using debug info finder to collect debug info.
801 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
803 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
804 DICompileUnit CUNode(CU_Nodes->getOperand(i));
805 CompileUnit *CU = constructCompileUnit(CUNode);
806 DIArray GVs = CUNode.getGlobalVariables();
807 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
808 CU->createGlobalVariableDIE(GVs.getElement(i));
809 DIArray SPs = CUNode.getSubprograms();
810 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
811 constructSubprogramDIE(CU, SPs.getElement(i));
812 DIArray EnumTypes = CUNode.getEnumTypes();
813 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
814 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
815 DIArray RetainedTypes = CUNode.getRetainedTypes();
816 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
817 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
819 } else if (!collectLegacyDebugInfo(M))
822 collectInfoFromNamedMDNodes(M);
824 // Tell MMI that we have debug info.
825 MMI->setDebugInfoAvailability(true);
827 // Prime section data.
828 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
831 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
832 void DwarfDebug::computeInlinedDIEs() {
833 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
834 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
835 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
837 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
839 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
840 AE = AbstractSPDies.end(); AI != AE; ++AI) {
841 DIE *ISP = AI->second;
842 if (InlinedSubprogramDIEs.count(ISP))
844 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
848 // Collect info for variables that were optimized out.
849 void DwarfDebug::collectDeadVariables() {
850 const Module *M = MMI->getModule();
851 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
853 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
854 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
855 DICompileUnit TheCU(CU_Nodes->getOperand(i));
856 DIArray Subprograms = TheCU.getSubprograms();
857 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
858 DISubprogram SP(Subprograms.getElement(i));
859 if (ProcessedSPNodes.count(SP) != 0) continue;
860 if (!SP.Verify()) continue;
861 if (!SP.isDefinition()) continue;
862 DIArray Variables = SP.getVariables();
863 if (Variables.getNumElements() == 0) continue;
865 LexicalScope *Scope =
866 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
867 DeadFnScopeMap[SP] = Scope;
869 // Construct subprogram DIE and add variables DIEs.
870 CompileUnit *SPCU = CUMap.lookup(TheCU);
871 assert(SPCU && "Unable to find Compile Unit!");
872 constructSubprogramDIE(SPCU, SP);
873 DIE *ScopeDIE = SPCU->getDIE(SP);
874 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
875 DIVariable DV(Variables.getElement(vi));
876 if (!DV.Verify()) continue;
877 DbgVariable *NewVar = new DbgVariable(DV, NULL);
878 if (DIE *VariableDIE =
879 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
880 ScopeDIE->addChild(VariableDIE);
885 DeleteContainerSeconds(DeadFnScopeMap);
888 void DwarfDebug::finalizeModuleInfo() {
889 // Collect info for variables that were optimized out.
890 collectDeadVariables();
892 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
893 computeInlinedDIEs();
895 // Emit DW_AT_containing_type attribute to connect types with their
896 // vtable holding type.
897 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
898 CUE = CUMap.end(); CUI != CUE; ++CUI) {
899 CompileUnit *TheCU = CUI->second;
900 TheCU->constructContainingTypeDIEs();
903 // Compute DIE offsets and sizes.
904 InfoHolder.computeSizeAndOffsets();
906 SkeletonHolder.computeSizeAndOffsets();
909 void DwarfDebug::endSections() {
910 // Standard sections final addresses.
911 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
912 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
913 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
914 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
916 // End text sections.
917 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
918 Asm->OutStreamer.SwitchSection(SectionMap[I]);
919 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
923 // Emit all Dwarf sections that should come after the content.
924 void DwarfDebug::endModule() {
926 if (!FirstCU) return;
928 // End any existing sections.
929 // TODO: Does this need to happen?
932 // Finalize the debug info for the module.
933 finalizeModuleInfo();
935 // Emit initial sections.
938 if (!useSplitDwarf()) {
939 // Emit all the DIEs into a debug info section.
942 // Corresponding abbreviations into a abbrev section.
945 // Emit info into a debug loc section.
948 // Emit info into a debug aranges section.
951 // Emit info into a debug ranges section.
954 // Emit info into a debug macinfo section.
958 // TODO: When we don't need the option anymore we
959 // can remove all of the code that this section
961 if (useDarwinGDBCompat())
962 emitDebugInlineInfo();
964 // TODO: Fill this in for separated debug sections and separate
965 // out information into new sections.
967 // Emit the debug info section and compile units.
971 // Corresponding abbreviations into a abbrev section.
973 emitDebugAbbrevDWO();
975 // Emit info into a debug loc section.
978 // Emit info into a debug aranges section.
981 // Emit info into a debug ranges section.
984 // Emit info into a debug macinfo section.
987 // Emit DWO addresses.
988 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
991 // TODO: When we don't need the option anymore we
992 // can remove all of the code that this section
994 if (useDarwinGDBCompat())
995 emitDebugInlineInfo();
998 // Emit info into the dwarf accelerator table sections.
999 if (useDwarfAccelTables()) {
1002 emitAccelNamespaces();
1006 // Emit info into a debug pubtypes section.
1007 // TODO: When we don't need the option anymore we can
1008 // remove all of the code that adds to the table.
1009 if (useDarwinGDBCompat())
1010 emitDebugPubTypes();
1012 // Finally emit string information into a string table.
1014 if (useSplitDwarf())
1019 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1020 E = CUMap.end(); I != E; ++I)
1025 // Reset these for the next Module if we have one.
1030 // Find abstract variable, if any, associated with Var.
1031 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1032 DebugLoc ScopeLoc) {
1033 LLVMContext &Ctx = DV->getContext();
1034 // More then one inlined variable corresponds to one abstract variable.
1035 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1036 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1038 return AbsDbgVariable;
1040 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1044 AbsDbgVariable = new DbgVariable(Var, NULL);
1045 addScopeVariable(Scope, AbsDbgVariable);
1046 AbstractVariables[Var] = AbsDbgVariable;
1047 return AbsDbgVariable;
1050 // If Var is a current function argument then add it to CurrentFnArguments list.
1051 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1052 DbgVariable *Var, LexicalScope *Scope) {
1053 if (!LScopes.isCurrentFunctionScope(Scope))
1055 DIVariable DV = Var->getVariable();
1056 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1058 unsigned ArgNo = DV.getArgNumber();
1062 size_t Size = CurrentFnArguments.size();
1064 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1065 // llvm::Function argument size is not good indicator of how many
1066 // arguments does the function have at source level.
1068 CurrentFnArguments.resize(ArgNo * 2);
1069 CurrentFnArguments[ArgNo - 1] = Var;
1073 // Collect variable information from side table maintained by MMI.
1075 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1076 SmallPtrSet<const MDNode *, 16> &Processed) {
1077 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1078 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1079 VE = VMap.end(); VI != VE; ++VI) {
1080 const MDNode *Var = VI->first;
1082 Processed.insert(Var);
1084 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1086 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1088 // If variable scope is not found then skip this variable.
1092 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1093 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1094 RegVar->setFrameIndex(VP.first);
1095 if (!addCurrentFnArgument(MF, RegVar, Scope))
1096 addScopeVariable(Scope, RegVar);
1098 AbsDbgVariable->setFrameIndex(VP.first);
1102 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1104 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1105 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1106 return MI->getNumOperands() == 3 &&
1107 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1108 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1111 // Get .debug_loc entry for the instruction range starting at MI.
1112 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1113 const MCSymbol *FLabel,
1114 const MCSymbol *SLabel,
1115 const MachineInstr *MI) {
1116 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1118 if (MI->getNumOperands() != 3) {
1119 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1120 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1122 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1123 MachineLocation MLoc;
1124 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1125 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1127 if (MI->getOperand(0).isImm())
1128 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1129 if (MI->getOperand(0).isFPImm())
1130 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1131 if (MI->getOperand(0).isCImm())
1132 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1134 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1137 // Find variables for each lexical scope.
1139 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1140 SmallPtrSet<const MDNode *, 16> &Processed) {
1142 // collection info from MMI table.
1143 collectVariableInfoFromMMITable(MF, Processed);
1145 for (SmallVectorImpl<const MDNode*>::const_iterator
1146 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1148 const MDNode *Var = *UVI;
1149 if (Processed.count(Var))
1152 // History contains relevant DBG_VALUE instructions for Var and instructions
1154 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1155 if (History.empty())
1157 const MachineInstr *MInsn = History.front();
1160 LexicalScope *Scope = NULL;
1161 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1162 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1163 Scope = LScopes.getCurrentFunctionScope();
1165 if (DV.getVersion() <= LLVMDebugVersion9)
1166 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1168 if (MDNode *IA = DV.getInlinedAt())
1169 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1171 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1174 // If variable scope is not found then skip this variable.
1178 Processed.insert(DV);
1179 assert(MInsn->isDebugValue() && "History must begin with debug value");
1180 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1181 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1182 if (!addCurrentFnArgument(MF, RegVar, Scope))
1183 addScopeVariable(Scope, RegVar);
1185 AbsVar->setMInsn(MInsn);
1187 // Simplify ranges that are fully coalesced.
1188 if (History.size() <= 1 || (History.size() == 2 &&
1189 MInsn->isIdenticalTo(History.back()))) {
1190 RegVar->setMInsn(MInsn);
1194 // Handle multiple DBG_VALUE instructions describing one variable.
1195 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1197 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1198 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1199 const MachineInstr *Begin = *HI;
1200 assert(Begin->isDebugValue() && "Invalid History entry");
1202 // Check if DBG_VALUE is truncating a range.
1203 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1204 && !Begin->getOperand(0).getReg())
1207 // Compute the range for a register location.
1208 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1209 const MCSymbol *SLabel = 0;
1212 // If Begin is the last instruction in History then its value is valid
1213 // until the end of the function.
1214 SLabel = FunctionEndSym;
1216 const MachineInstr *End = HI[1];
1217 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1218 << "\t" << *Begin << "\t" << *End << "\n");
1219 if (End->isDebugValue())
1220 SLabel = getLabelBeforeInsn(End);
1222 // End is a normal instruction clobbering the range.
1223 SLabel = getLabelAfterInsn(End);
1224 assert(SLabel && "Forgot label after clobber instruction");
1229 // The value is valid until the next DBG_VALUE or clobber.
1230 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1233 DotDebugLocEntries.push_back(DotDebugLocEntry());
1236 // Collect info for variables that were optimized out.
1237 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1238 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1239 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1240 DIVariable DV(Variables.getElement(i));
1241 if (!DV || !DV.Verify() || !Processed.insert(DV))
1243 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1244 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1248 // Return Label preceding the instruction.
1249 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1250 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1251 assert(Label && "Didn't insert label before instruction");
1255 // Return Label immediately following the instruction.
1256 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1257 return LabelsAfterInsn.lookup(MI);
1260 // Process beginning of an instruction.
1261 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1262 // Check if source location changes, but ignore DBG_VALUE locations.
1263 if (!MI->isDebugValue()) {
1264 DebugLoc DL = MI->getDebugLoc();
1265 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1268 if (DL == PrologEndLoc) {
1269 Flags |= DWARF2_FLAG_PROLOGUE_END;
1270 PrologEndLoc = DebugLoc();
1272 if (PrologEndLoc.isUnknown())
1273 Flags |= DWARF2_FLAG_IS_STMT;
1275 if (!DL.isUnknown()) {
1276 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1277 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1279 recordSourceLine(0, 0, 0, 0);
1283 // Insert labels where requested.
1284 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1285 LabelsBeforeInsn.find(MI);
1288 if (I == LabelsBeforeInsn.end())
1291 // Label already assigned.
1296 PrevLabel = MMI->getContext().CreateTempSymbol();
1297 Asm->OutStreamer.EmitLabel(PrevLabel);
1299 I->second = PrevLabel;
1302 // Process end of an instruction.
1303 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1304 // Don't create a new label after DBG_VALUE instructions.
1305 // They don't generate code.
1306 if (!MI->isDebugValue())
1309 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1310 LabelsAfterInsn.find(MI);
1313 if (I == LabelsAfterInsn.end())
1316 // Label already assigned.
1320 // We need a label after this instruction.
1322 PrevLabel = MMI->getContext().CreateTempSymbol();
1323 Asm->OutStreamer.EmitLabel(PrevLabel);
1325 I->second = PrevLabel;
1328 // Each LexicalScope has first instruction and last instruction to mark
1329 // beginning and end of a scope respectively. Create an inverse map that list
1330 // scopes starts (and ends) with an instruction. One instruction may start (or
1331 // end) multiple scopes. Ignore scopes that are not reachable.
1332 void DwarfDebug::identifyScopeMarkers() {
1333 SmallVector<LexicalScope *, 4> WorkList;
1334 WorkList.push_back(LScopes.getCurrentFunctionScope());
1335 while (!WorkList.empty()) {
1336 LexicalScope *S = WorkList.pop_back_val();
1338 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1339 if (!Children.empty())
1340 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1341 SE = Children.end(); SI != SE; ++SI)
1342 WorkList.push_back(*SI);
1344 if (S->isAbstractScope())
1347 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1350 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1351 RE = Ranges.end(); RI != RE; ++RI) {
1352 assert(RI->first && "InsnRange does not have first instruction!");
1353 assert(RI->second && "InsnRange does not have second instruction!");
1354 requestLabelBeforeInsn(RI->first);
1355 requestLabelAfterInsn(RI->second);
1360 // Get MDNode for DebugLoc's scope.
1361 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1362 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1363 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1364 return DL.getScope(Ctx);
1367 // Walk up the scope chain of given debug loc and find line number info
1368 // for the function.
1369 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1370 const MDNode *Scope = getScopeNode(DL, Ctx);
1371 DISubprogram SP = getDISubprogram(Scope);
1373 // Check for number of operands since the compatibility is
1375 if (SP->getNumOperands() > 19)
1376 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1378 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1384 // Gather pre-function debug information. Assumes being called immediately
1385 // after the function entry point has been emitted.
1386 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1387 if (!MMI->hasDebugInfo()) return;
1388 LScopes.initialize(*MF);
1389 if (LScopes.empty()) return;
1390 identifyScopeMarkers();
1392 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1393 Asm->getFunctionNumber());
1394 // Assumes in correct section after the entry point.
1395 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1397 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1399 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1400 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1401 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1403 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1405 bool AtBlockEntry = true;
1406 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1408 const MachineInstr *MI = II;
1410 if (MI->isDebugValue()) {
1411 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1413 // Keep track of user variables.
1415 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1417 // Variable is in a register, we need to check for clobbers.
1418 if (isDbgValueInDefinedReg(MI))
1419 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1421 // Check the history of this variable.
1422 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1423 if (History.empty()) {
1424 UserVariables.push_back(Var);
1425 // The first mention of a function argument gets the FunctionBeginSym
1426 // label, so arguments are visible when breaking at function entry.
1428 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1429 DISubprogram(getDISubprogram(DV.getContext()))
1430 .describes(MF->getFunction()))
1431 LabelsBeforeInsn[MI] = FunctionBeginSym;
1433 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1434 const MachineInstr *Prev = History.back();
1435 if (Prev->isDebugValue()) {
1436 // Coalesce identical entries at the end of History.
1437 if (History.size() >= 2 &&
1438 Prev->isIdenticalTo(History[History.size() - 2])) {
1439 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1441 << "\t" << *History[History.size() - 2] << "\n");
1445 // Terminate old register assignments that don't reach MI;
1446 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1447 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1448 isDbgValueInDefinedReg(Prev)) {
1449 // Previous register assignment needs to terminate at the end of
1451 MachineBasicBlock::const_iterator LastMI =
1452 PrevMBB->getLastNonDebugInstr();
1453 if (LastMI == PrevMBB->end()) {
1454 // Drop DBG_VALUE for empty range.
1455 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1456 << "\t" << *Prev << "\n");
1460 // Terminate after LastMI.
1461 History.push_back(LastMI);
1466 History.push_back(MI);
1468 // Not a DBG_VALUE instruction.
1470 AtBlockEntry = false;
1472 // First known non-DBG_VALUE and non-frame setup location marks
1473 // the beginning of the function body.
1474 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1475 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1476 PrologEndLoc = MI->getDebugLoc();
1478 // Check if the instruction clobbers any registers with debug vars.
1479 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1480 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1481 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1483 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1484 AI.isValid(); ++AI) {
1486 const MDNode *Var = LiveUserVar[Reg];
1489 // Reg is now clobbered.
1490 LiveUserVar[Reg] = 0;
1492 // Was MD last defined by a DBG_VALUE referring to Reg?
1493 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1494 if (HistI == DbgValues.end())
1496 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1497 if (History.empty())
1499 const MachineInstr *Prev = History.back();
1500 // Sanity-check: Register assignments are terminated at the end of
1502 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1504 // Is the variable still in Reg?
1505 if (!isDbgValueInDefinedReg(Prev) ||
1506 Prev->getOperand(0).getReg() != Reg)
1508 // Var is clobbered. Make sure the next instruction gets a label.
1509 History.push_back(MI);
1516 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1518 SmallVectorImpl<const MachineInstr*> &History = I->second;
1519 if (History.empty())
1522 // Make sure the final register assignments are terminated.
1523 const MachineInstr *Prev = History.back();
1524 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1525 const MachineBasicBlock *PrevMBB = Prev->getParent();
1526 MachineBasicBlock::const_iterator LastMI =
1527 PrevMBB->getLastNonDebugInstr();
1528 if (LastMI == PrevMBB->end())
1529 // Drop DBG_VALUE for empty range.
1532 // Terminate after LastMI.
1533 History.push_back(LastMI);
1536 // Request labels for the full history.
1537 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1538 const MachineInstr *MI = History[i];
1539 if (MI->isDebugValue())
1540 requestLabelBeforeInsn(MI);
1542 requestLabelAfterInsn(MI);
1546 PrevInstLoc = DebugLoc();
1547 PrevLabel = FunctionBeginSym;
1549 // Record beginning of function.
1550 if (!PrologEndLoc.isUnknown()) {
1551 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1552 MF->getFunction()->getContext());
1553 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1554 FnStartDL.getScope(MF->getFunction()->getContext()),
1555 // We'd like to list the prologue as "not statements" but GDB behaves
1556 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1557 DWARF2_FLAG_IS_STMT);
1561 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1562 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1563 ScopeVariables[LS].push_back(Var);
1564 // Vars.push_back(Var);
1567 // Gather and emit post-function debug information.
1568 void DwarfDebug::endFunction(const MachineFunction *MF) {
1569 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1571 // Define end label for subprogram.
1572 FunctionEndSym = Asm->GetTempSymbol("func_end",
1573 Asm->getFunctionNumber());
1574 // Assumes in correct section after the entry point.
1575 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1577 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1578 collectVariableInfo(MF, ProcessedVars);
1580 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1581 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1582 assert(TheCU && "Unable to find compile unit!");
1584 // Construct abstract scopes.
1585 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1586 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1587 LexicalScope *AScope = AList[i];
1588 DISubprogram SP(AScope->getScopeNode());
1590 // Collect info for variables that were optimized out.
1591 DIArray Variables = SP.getVariables();
1592 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1593 DIVariable DV(Variables.getElement(i));
1594 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1596 // Check that DbgVariable for DV wasn't created earlier, when
1597 // findAbstractVariable() was called for inlined instance of DV.
1598 LLVMContext &Ctx = DV->getContext();
1599 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1600 if (AbstractVariables.lookup(CleanDV))
1602 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1603 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1606 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1607 constructScopeDIE(TheCU, AScope);
1610 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1612 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1613 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1615 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1616 MMI->getFrameMoves()));
1619 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1620 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1621 DeleteContainerPointers(I->second);
1622 ScopeVariables.clear();
1623 DeleteContainerPointers(CurrentFnArguments);
1624 UserVariables.clear();
1626 AbstractVariables.clear();
1627 LabelsBeforeInsn.clear();
1628 LabelsAfterInsn.clear();
1632 // Register a source line with debug info. Returns the unique label that was
1633 // emitted and which provides correspondence to the source line list.
1634 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1640 DIDescriptor Scope(S);
1642 if (Scope.isCompileUnit()) {
1643 DICompileUnit CU(S);
1644 Fn = CU.getFilename();
1645 Dir = CU.getDirectory();
1646 } else if (Scope.isFile()) {
1648 Fn = F.getFilename();
1649 Dir = F.getDirectory();
1650 } else if (Scope.isSubprogram()) {
1652 Fn = SP.getFilename();
1653 Dir = SP.getDirectory();
1654 } else if (Scope.isLexicalBlockFile()) {
1655 DILexicalBlockFile DBF(S);
1656 Fn = DBF.getFilename();
1657 Dir = DBF.getDirectory();
1658 } else if (Scope.isLexicalBlock()) {
1659 DILexicalBlock DB(S);
1660 Fn = DB.getFilename();
1661 Dir = DB.getDirectory();
1663 llvm_unreachable("Unexpected scope info");
1665 Src = getOrCreateSourceID(Fn, Dir);
1667 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1670 //===----------------------------------------------------------------------===//
1672 //===----------------------------------------------------------------------===//
1674 // Compute the size and offset of a DIE.
1676 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1677 // Get the children.
1678 const std::vector<DIE *> &Children = Die->getChildren();
1680 // Record the abbreviation.
1681 assignAbbrevNumber(Die->getAbbrev());
1683 // Get the abbreviation for this DIE.
1684 unsigned AbbrevNumber = Die->getAbbrevNumber();
1685 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1688 Die->setOffset(Offset);
1690 // Start the size with the size of abbreviation code.
1691 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1693 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1694 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1696 // Size the DIE attribute values.
1697 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1698 // Size attribute value.
1699 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1701 // Size the DIE children if any.
1702 if (!Children.empty()) {
1703 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1704 "Children flag not set");
1706 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1707 Offset = computeSizeAndOffset(Children[j], Offset);
1709 // End of children marker.
1710 Offset += sizeof(int8_t);
1713 Die->setSize(Offset - Die->getOffset());
1717 // Compute the size and offset of all the DIEs.
1718 void DwarfUnits::computeSizeAndOffsets() {
1719 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1720 E = CUs.end(); I != E; ++I) {
1722 sizeof(int32_t) + // Length of Compilation Unit Info
1723 sizeof(int16_t) + // DWARF version number
1724 sizeof(int32_t) + // Offset Into Abbrev. Section
1725 sizeof(int8_t); // Pointer Size (in bytes)
1727 computeSizeAndOffset((*I)->getCUDie(), Offset);
1731 // Emit initial Dwarf sections with a label at the start of each one.
1732 void DwarfDebug::emitSectionLabels() {
1733 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1735 // Dwarf sections base addresses.
1736 DwarfInfoSectionSym =
1737 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1738 DwarfAbbrevSectionSym =
1739 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1740 if (useSplitDwarf())
1741 DwarfAbbrevDWOSectionSym =
1742 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1743 "section_abbrev_dwo");
1744 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1746 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1747 emitSectionSym(Asm, MacroInfo);
1749 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1750 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1751 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1752 DwarfStrSectionSym =
1753 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1754 if (useSplitDwarf())
1755 DwarfStrDWOSectionSym =
1756 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1757 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1760 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1761 "section_debug_loc");
1763 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1764 emitSectionSym(Asm, TLOF.getDataSection());
1767 // Recursively emits a debug information entry.
1768 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1769 // Get the abbreviation for this DIE.
1770 unsigned AbbrevNumber = Die->getAbbrevNumber();
1771 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1773 // Emit the code (index) for the abbreviation.
1774 if (Asm->isVerbose())
1775 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1776 Twine::utohexstr(Die->getOffset()) + ":0x" +
1777 Twine::utohexstr(Die->getSize()) + " " +
1778 dwarf::TagString(Abbrev->getTag()));
1779 Asm->EmitULEB128(AbbrevNumber);
1781 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1782 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1784 // Emit the DIE attribute values.
1785 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1786 unsigned Attr = AbbrevData[i].getAttribute();
1787 unsigned Form = AbbrevData[i].getForm();
1788 assert(Form && "Too many attributes for DIE (check abbreviation)");
1790 if (Asm->isVerbose())
1791 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1794 case dwarf::DW_AT_abstract_origin: {
1795 DIEEntry *E = cast<DIEEntry>(Values[i]);
1796 DIE *Origin = E->getEntry();
1797 unsigned Addr = Origin->getOffset();
1798 Asm->EmitInt32(Addr);
1801 case dwarf::DW_AT_ranges: {
1802 // DW_AT_range Value encodes offset in debug_range section.
1803 DIEInteger *V = cast<DIEInteger>(Values[i]);
1805 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1806 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1810 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1812 DwarfDebugRangeSectionSym,
1817 case dwarf::DW_AT_location: {
1818 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1819 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1820 Asm->EmitLabelReference(L->getValue(), 4);
1822 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1824 Values[i]->EmitValue(Asm, Form);
1828 case dwarf::DW_AT_accessibility: {
1829 if (Asm->isVerbose()) {
1830 DIEInteger *V = cast<DIEInteger>(Values[i]);
1831 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1833 Values[i]->EmitValue(Asm, Form);
1837 // Emit an attribute using the defined form.
1838 Values[i]->EmitValue(Asm, Form);
1843 // Emit the DIE children if any.
1844 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1845 const std::vector<DIE *> &Children = Die->getChildren();
1847 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1848 emitDIE(Children[j], Abbrevs);
1850 if (Asm->isVerbose())
1851 Asm->OutStreamer.AddComment("End Of Children Mark");
1856 // Emit the various dwarf units to the unit section USection with
1857 // the abbreviations going into ASection.
1858 void DwarfUnits::emitUnits(DwarfDebug *DD,
1859 const MCSection *USection,
1860 const MCSection *ASection,
1861 const MCSymbol *ASectionSym) {
1862 Asm->OutStreamer.SwitchSection(USection);
1863 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1864 E = CUs.end(); I != E; ++I) {
1865 CompileUnit *TheCU = *I;
1866 DIE *Die = TheCU->getCUDie();
1868 // Emit the compile units header.
1870 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1871 TheCU->getUniqueID()));
1873 // Emit size of content not including length itself
1874 unsigned ContentSize = Die->getSize() +
1875 sizeof(int16_t) + // DWARF version number
1876 sizeof(int32_t) + // Offset Into Abbrev. Section
1877 sizeof(int8_t); // Pointer Size (in bytes)
1879 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1880 Asm->EmitInt32(ContentSize);
1881 Asm->OutStreamer.AddComment("DWARF version number");
1882 Asm->EmitInt16(dwarf::DWARF_VERSION);
1883 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1884 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1886 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1887 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1889 DD->emitDIE(Die, Abbreviations);
1890 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1891 TheCU->getUniqueID()));
1895 // Emit the debug info section.
1896 void DwarfDebug::emitDebugInfo() {
1897 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1899 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1900 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1901 DwarfAbbrevSectionSym);
1904 // Emit the abbreviation section.
1905 void DwarfDebug::emitAbbreviations() {
1906 if (!useSplitDwarf())
1907 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1910 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1913 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1914 std::vector<DIEAbbrev *> *Abbrevs) {
1915 // Check to see if it is worth the effort.
1916 if (!Abbrevs->empty()) {
1917 // Start the debug abbrev section.
1918 Asm->OutStreamer.SwitchSection(Section);
1920 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1921 Asm->OutStreamer.EmitLabel(Begin);
1923 // For each abbrevation.
1924 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1925 // Get abbreviation data
1926 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1928 // Emit the abbrevations code (base 1 index.)
1929 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1931 // Emit the abbreviations data.
1935 // Mark end of abbreviations.
1936 Asm->EmitULEB128(0, "EOM(3)");
1938 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1939 Asm->OutStreamer.EmitLabel(End);
1943 // Emit the last address of the section and the end of the line matrix.
1944 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1945 // Define last address of section.
1946 Asm->OutStreamer.AddComment("Extended Op");
1949 Asm->OutStreamer.AddComment("Op size");
1950 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1951 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1952 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1954 Asm->OutStreamer.AddComment("Section end label");
1956 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1957 Asm->getDataLayout().getPointerSize());
1959 // Mark end of matrix.
1960 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1966 // Emit visible names into a hashed accelerator table section.
1967 void DwarfDebug::emitAccelNames() {
1968 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1969 dwarf::DW_FORM_data4));
1970 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1971 E = CUMap.end(); I != E; ++I) {
1972 CompileUnit *TheCU = I->second;
1973 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1974 for (StringMap<std::vector<DIE*> >::const_iterator
1975 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1976 const char *Name = GI->getKeyData();
1977 const std::vector<DIE *> &Entities = GI->second;
1978 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
1979 DE = Entities.end(); DI != DE; ++DI)
1980 AT.AddName(Name, (*DI));
1984 AT.FinalizeTable(Asm, "Names");
1985 Asm->OutStreamer.SwitchSection(
1986 Asm->getObjFileLowering().getDwarfAccelNamesSection());
1987 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
1988 Asm->OutStreamer.EmitLabel(SectionBegin);
1990 // Emit the full data.
1991 AT.Emit(Asm, SectionBegin, &InfoHolder);
1994 // Emit objective C classes and categories into a hashed accelerator table
1996 void DwarfDebug::emitAccelObjC() {
1997 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1998 dwarf::DW_FORM_data4));
1999 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2000 E = CUMap.end(); I != E; ++I) {
2001 CompileUnit *TheCU = I->second;
2002 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2003 for (StringMap<std::vector<DIE*> >::const_iterator
2004 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2005 const char *Name = GI->getKeyData();
2006 const std::vector<DIE *> &Entities = GI->second;
2007 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2008 DE = Entities.end(); DI != DE; ++DI)
2009 AT.AddName(Name, (*DI));
2013 AT.FinalizeTable(Asm, "ObjC");
2014 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2015 .getDwarfAccelObjCSection());
2016 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2017 Asm->OutStreamer.EmitLabel(SectionBegin);
2019 // Emit the full data.
2020 AT.Emit(Asm, SectionBegin, &InfoHolder);
2023 // Emit namespace dies into a hashed accelerator table.
2024 void DwarfDebug::emitAccelNamespaces() {
2025 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2026 dwarf::DW_FORM_data4));
2027 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2028 E = CUMap.end(); I != E; ++I) {
2029 CompileUnit *TheCU = I->second;
2030 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2031 for (StringMap<std::vector<DIE*> >::const_iterator
2032 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2033 const char *Name = GI->getKeyData();
2034 const std::vector<DIE *> &Entities = GI->second;
2035 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2036 DE = Entities.end(); DI != DE; ++DI)
2037 AT.AddName(Name, (*DI));
2041 AT.FinalizeTable(Asm, "namespac");
2042 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2043 .getDwarfAccelNamespaceSection());
2044 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2045 Asm->OutStreamer.EmitLabel(SectionBegin);
2047 // Emit the full data.
2048 AT.Emit(Asm, SectionBegin, &InfoHolder);
2051 // Emit type dies into a hashed accelerator table.
2052 void DwarfDebug::emitAccelTypes() {
2053 std::vector<DwarfAccelTable::Atom> Atoms;
2054 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2055 dwarf::DW_FORM_data4));
2056 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2057 dwarf::DW_FORM_data2));
2058 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2059 dwarf::DW_FORM_data1));
2060 DwarfAccelTable AT(Atoms);
2061 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2062 E = CUMap.end(); I != E; ++I) {
2063 CompileUnit *TheCU = I->second;
2064 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2065 = TheCU->getAccelTypes();
2066 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2067 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2068 const char *Name = GI->getKeyData();
2069 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2070 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2071 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2072 AT.AddName(Name, (*DI).first, (*DI).second);
2076 AT.FinalizeTable(Asm, "types");
2077 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2078 .getDwarfAccelTypesSection());
2079 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2080 Asm->OutStreamer.EmitLabel(SectionBegin);
2082 // Emit the full data.
2083 AT.Emit(Asm, SectionBegin, &InfoHolder);
2086 void DwarfDebug::emitDebugPubTypes() {
2087 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2088 E = CUMap.end(); I != E; ++I) {
2089 CompileUnit *TheCU = I->second;
2090 // Start the dwarf pubtypes section.
2091 Asm->OutStreamer.SwitchSection(
2092 Asm->getObjFileLowering().getDwarfPubTypesSection());
2093 Asm->OutStreamer.AddComment("Length of Public Types Info");
2094 Asm->EmitLabelDifference(
2095 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2096 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2098 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2099 TheCU->getUniqueID()));
2101 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2102 Asm->EmitInt16(dwarf::DWARF_VERSION);
2104 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2105 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2106 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2107 TheCU->getUniqueID()),
2108 DwarfInfoSectionSym);
2110 Asm->OutStreamer.AddComment("Compilation Unit Length");
2111 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2112 TheCU->getUniqueID()),
2113 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2114 TheCU->getUniqueID()),
2117 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2118 for (StringMap<DIE*>::const_iterator
2119 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2120 const char *Name = GI->getKeyData();
2121 DIE *Entity = GI->second;
2123 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2124 Asm->EmitInt32(Entity->getOffset());
2126 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2127 // Emit the name with a terminating null byte.
2128 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2131 Asm->OutStreamer.AddComment("End Mark");
2133 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2134 TheCU->getUniqueID()));
2138 // Emit strings into a string section.
2139 void DwarfUnits::emitStrings(const MCSection *StrSection,
2140 const MCSection *OffsetSection = NULL,
2141 const MCSymbol *StrSecSym = NULL) {
2143 if (StringPool.empty()) return;
2145 // Start the dwarf str section.
2146 Asm->OutStreamer.SwitchSection(StrSection);
2148 // Get all of the string pool entries and put them in an array by their ID so
2149 // we can sort them.
2150 SmallVector<std::pair<unsigned,
2151 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2153 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2154 I = StringPool.begin(), E = StringPool.end();
2156 Entries.push_back(std::make_pair(I->second.second, &*I));
2158 array_pod_sort(Entries.begin(), Entries.end());
2160 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2161 // Emit a label for reference from debug information entries.
2162 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2164 // Emit the string itself with a terminating null byte.
2165 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2166 Entries[i].second->getKeyLength()+1));
2169 // If we've got an offset section go ahead and emit that now as well.
2170 if (OffsetSection) {
2171 Asm->OutStreamer.SwitchSection(OffsetSection);
2172 unsigned offset = 0;
2173 unsigned size = 4; // FIXME: DWARF64 is 8.
2174 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2175 Asm->OutStreamer.EmitIntValue(offset, size);
2176 offset += Entries[i].second->getKeyLength() + 1;
2181 // Emit strings into a string section.
2182 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2184 if (AddressPool.empty()) return;
2186 // Start the dwarf addr section.
2187 Asm->OutStreamer.SwitchSection(AddrSection);
2189 // Get all of the string pool entries and put them in an array by their ID so
2190 // we can sort them.
2191 SmallVector<std::pair<unsigned,
2192 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2194 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2195 I = AddressPool.begin(), E = AddressPool.end();
2197 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2199 array_pod_sort(Entries.begin(), Entries.end());
2201 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2202 // Emit a label for reference from debug information entries.
2203 MCSymbol *Sym = Entries[i].second->first;
2205 Asm->EmitLabelReference(Entries[i].second->first,
2206 Asm->getDataLayout().getPointerSize());
2208 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2213 // Emit visible names into a debug str section.
2214 void DwarfDebug::emitDebugStr() {
2215 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2216 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2219 // Emit visible names into a debug loc section.
2220 void DwarfDebug::emitDebugLoc() {
2221 if (DotDebugLocEntries.empty())
2224 for (SmallVector<DotDebugLocEntry, 4>::iterator
2225 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2227 DotDebugLocEntry &Entry = *I;
2228 if (I + 1 != DotDebugLocEntries.end())
2232 // Start the dwarf loc section.
2233 Asm->OutStreamer.SwitchSection(
2234 Asm->getObjFileLowering().getDwarfLocSection());
2235 unsigned char Size = Asm->getDataLayout().getPointerSize();
2236 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2238 for (SmallVector<DotDebugLocEntry, 4>::iterator
2239 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2240 I != E; ++I, ++index) {
2241 DotDebugLocEntry &Entry = *I;
2242 if (Entry.isMerged()) continue;
2243 if (Entry.isEmpty()) {
2244 Asm->OutStreamer.EmitIntValue(0, Size);
2245 Asm->OutStreamer.EmitIntValue(0, Size);
2246 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2248 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2249 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2250 DIVariable DV(Entry.Variable);
2251 Asm->OutStreamer.AddComment("Loc expr size");
2252 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2253 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2254 Asm->EmitLabelDifference(end, begin, 2);
2255 Asm->OutStreamer.EmitLabel(begin);
2256 if (Entry.isInt()) {
2257 DIBasicType BTy(DV.getType());
2259 (BTy.getEncoding() == dwarf::DW_ATE_signed
2260 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2261 Asm->OutStreamer.AddComment("DW_OP_consts");
2262 Asm->EmitInt8(dwarf::DW_OP_consts);
2263 Asm->EmitSLEB128(Entry.getInt());
2265 Asm->OutStreamer.AddComment("DW_OP_constu");
2266 Asm->EmitInt8(dwarf::DW_OP_constu);
2267 Asm->EmitULEB128(Entry.getInt());
2269 } else if (Entry.isLocation()) {
2270 if (!DV.hasComplexAddress())
2272 Asm->EmitDwarfRegOp(Entry.Loc);
2274 // Complex address entry.
2275 unsigned N = DV.getNumAddrElements();
2277 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2278 if (Entry.Loc.getOffset()) {
2280 Asm->EmitDwarfRegOp(Entry.Loc);
2281 Asm->OutStreamer.AddComment("DW_OP_deref");
2282 Asm->EmitInt8(dwarf::DW_OP_deref);
2283 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2284 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2285 Asm->EmitSLEB128(DV.getAddrElement(1));
2287 // If first address element is OpPlus then emit
2288 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2289 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2290 Asm->EmitDwarfRegOp(Loc);
2294 Asm->EmitDwarfRegOp(Entry.Loc);
2297 // Emit remaining complex address elements.
2298 for (; i < N; ++i) {
2299 uint64_t Element = DV.getAddrElement(i);
2300 if (Element == DIBuilder::OpPlus) {
2301 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2302 Asm->EmitULEB128(DV.getAddrElement(++i));
2303 } else if (Element == DIBuilder::OpDeref) {
2304 if (!Entry.Loc.isReg())
2305 Asm->EmitInt8(dwarf::DW_OP_deref);
2307 llvm_unreachable("unknown Opcode found in complex address");
2311 // else ... ignore constant fp. There is not any good way to
2312 // to represent them here in dwarf.
2313 Asm->OutStreamer.EmitLabel(end);
2318 // Emit visible names into a debug aranges section.
2319 void DwarfDebug::emitDebugARanges() {
2320 // Start the dwarf aranges section.
2321 Asm->OutStreamer.SwitchSection(
2322 Asm->getObjFileLowering().getDwarfARangesSection());
2325 // Emit visible names into a debug ranges section.
2326 void DwarfDebug::emitDebugRanges() {
2327 // Start the dwarf ranges section.
2328 Asm->OutStreamer.SwitchSection(
2329 Asm->getObjFileLowering().getDwarfRangesSection());
2330 unsigned char Size = Asm->getDataLayout().getPointerSize();
2331 for (SmallVector<const MCSymbol *, 8>::iterator
2332 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2335 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2337 Asm->OutStreamer.EmitIntValue(0, Size);
2341 // Emit visible names into a debug macinfo section.
2342 void DwarfDebug::emitDebugMacInfo() {
2343 if (const MCSection *LineInfo =
2344 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2345 // Start the dwarf macinfo section.
2346 Asm->OutStreamer.SwitchSection(LineInfo);
2350 // Emit inline info using following format.
2352 // 1. length of section
2353 // 2. Dwarf version number
2356 // Entries (one "entry" for each function that was inlined):
2358 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2359 // otherwise offset into __debug_str for regular function name.
2360 // 2. offset into __debug_str section for regular function name.
2361 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2362 // instances for the function.
2364 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2365 // inlined instance; the die_offset points to the inlined_subroutine die in the
2366 // __debug_info section, and the low_pc is the starting address for the
2367 // inlining instance.
2368 void DwarfDebug::emitDebugInlineInfo() {
2369 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2375 Asm->OutStreamer.SwitchSection(
2376 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2378 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2379 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2380 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2382 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2384 Asm->OutStreamer.AddComment("Dwarf Version");
2385 Asm->EmitInt16(dwarf::DWARF_VERSION);
2386 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2387 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2389 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2390 E = InlinedSPNodes.end(); I != E; ++I) {
2392 const MDNode *Node = *I;
2393 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2394 = InlineInfo.find(Node);
2395 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2396 DISubprogram SP(Node);
2397 StringRef LName = SP.getLinkageName();
2398 StringRef Name = SP.getName();
2400 Asm->OutStreamer.AddComment("MIPS linkage name");
2402 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2403 DwarfStrSectionSym);
2405 Asm->EmitSectionOffset(InfoHolder
2406 .getStringPoolEntry(getRealLinkageName(LName)),
2407 DwarfStrSectionSym);
2409 Asm->OutStreamer.AddComment("Function name");
2410 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2411 DwarfStrSectionSym);
2412 Asm->EmitULEB128(Labels.size(), "Inline count");
2414 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2415 LE = Labels.end(); LI != LE; ++LI) {
2416 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2417 Asm->EmitInt32(LI->second->getOffset());
2419 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2420 Asm->OutStreamer.EmitSymbolValue(LI->first,
2421 Asm->getDataLayout().getPointerSize());
2425 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2428 // DWARF5 Experimental Separate Dwarf emitters.
2430 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2431 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2432 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2433 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2434 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2435 DICompileUnit DIUnit(N);
2436 CompilationDir = DIUnit.getDirectory();
2438 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2439 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2440 DIUnit.getLanguage(), Die, Asm,
2441 this, &SkeletonHolder);
2443 SmallString<16> T(DIUnit.getFilename());
2444 sys::path::replace_extension(T, ".dwo");
2445 StringRef FN = sys::path::filename(T);
2446 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2448 // FIXME: We also need DW_AT_dwo_id.
2450 // FIXME: The addr base should be relative for each compile unit, however,
2451 // this one is going to be 0 anyhow.
2452 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset, 0);
2454 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2455 // into an entity. We're using 0, or a NULL label for this.
2456 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2458 // DW_AT_stmt_list is a offset of line number information for this
2459 // compile unit in debug_line section.
2460 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2461 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2462 Asm->GetTempSymbol("section_line"));
2464 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2466 if (!CompilationDir.empty())
2467 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2469 SkeletonHolder.addUnit(NewCU);
2474 void DwarfDebug::emitSkeletonCU(const MCSection *Section) {
2475 Asm->OutStreamer.SwitchSection(Section);
2476 DIE *Die = SkeletonCU->getCUDie();
2478 // Emit the compile units header.
2479 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelBeginName(),
2480 SkeletonCU->getUniqueID()));
2482 // Emit size of content not including length itself
2483 unsigned ContentSize = Die->getSize() +
2484 sizeof(int16_t) + // DWARF version number
2485 sizeof(int32_t) + // Offset Into Abbrev. Section
2486 sizeof(int8_t); // Pointer Size (in bytes)
2488 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2489 Asm->EmitInt32(ContentSize);
2490 Asm->OutStreamer.AddComment("DWARF version number");
2491 Asm->EmitInt16(dwarf::DWARF_VERSION);
2492 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2494 const MCSection *ASec = Asm->getObjFileLowering().getDwarfAbbrevSection();
2495 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASec->getLabelBeginName()),
2496 DwarfAbbrevSectionSym);
2497 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2498 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2500 emitDIE(Die, &SkeletonAbbrevs);
2501 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(Section->getLabelEndName(),
2502 SkeletonCU->getUniqueID()));
2505 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2506 assert(useSplitDwarf() && "No split dwarf debug info?");
2507 emitAbbrevs(Section, &SkeletonAbbrevs);
2510 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2511 // compile units that would normally be in debug_info.
2512 void DwarfDebug::emitDebugInfoDWO() {
2513 assert(useSplitDwarf() && "No split dwarf debug info?");
2514 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2515 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2516 DwarfAbbrevDWOSectionSym);
2519 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2520 // abbreviations for the .debug_info.dwo section.
2521 void DwarfDebug::emitDebugAbbrevDWO() {
2522 assert(useSplitDwarf() && "No split dwarf?");
2523 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2527 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2528 // string section and is identical in format to traditional .debug_str
2530 void DwarfDebug::emitDebugStrDWO() {
2531 assert(useSplitDwarf() && "No split dwarf?");
2532 const MCSection *OffSec = Asm->getObjFileLowering()
2533 .getDwarfStrOffDWOSection();
2534 const MCSymbol *StrSym = DwarfStrSectionSym;
2535 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),