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."),
57 static cl::opt<bool> GenerateDwarfPubNamesSection("generate-dwarf-pubnames",
58 cl::Hidden, cl::init(false),
59 cl::desc("Generate DWARF pubnames section"));
63 Default, Enable, Disable
67 static cl::opt<DefaultOnOff> DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
68 cl::desc("Output prototype dwarf accelerator tables."),
70 clEnumVal(Default, "Default for platform"),
71 clEnumVal(Enable, "Enabled"),
72 clEnumVal(Disable, "Disabled"),
76 static cl::opt<DefaultOnOff> DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
77 cl::desc("Compatibility with Darwin gdb."),
79 clEnumVal(Default, "Default for platform"),
80 clEnumVal(Enable, "Enabled"),
81 clEnumVal(Disable, "Disabled"),
85 static cl::opt<DefaultOnOff> SplitDwarf("split-dwarf", cl::Hidden,
86 cl::desc("Output prototype dwarf split debug info."),
88 clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"),
95 const char *DWARFGroupName = "DWARF Emission";
96 const char *DbgTimerName = "DWARF Debug Writer";
97 } // end anonymous namespace
99 //===----------------------------------------------------------------------===//
101 // Configuration values for initial hash set sizes (log2).
103 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
107 DIType DbgVariable::getType() const {
108 DIType Ty = Var.getType();
109 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
110 // addresses instead.
111 if (Var.isBlockByrefVariable()) {
112 /* Byref variables, in Blocks, are declared by the programmer as
113 "SomeType VarName;", but the compiler creates a
114 __Block_byref_x_VarName struct, and gives the variable VarName
115 either the struct, or a pointer to the struct, as its type. This
116 is necessary for various behind-the-scenes things the compiler
117 needs to do with by-reference variables in blocks.
119 However, as far as the original *programmer* is concerned, the
120 variable should still have type 'SomeType', as originally declared.
122 The following function dives into the __Block_byref_x_VarName
123 struct to find the original type of the variable. This will be
124 passed back to the code generating the type for the Debug
125 Information Entry for the variable 'VarName'. 'VarName' will then
126 have the original type 'SomeType' in its debug information.
128 The original type 'SomeType' will be the type of the field named
129 'VarName' inside the __Block_byref_x_VarName struct.
131 NOTE: In order for this to not completely fail on the debugger
132 side, the Debug Information Entry for the variable VarName needs to
133 have a DW_AT_location that tells the debugger how to unwind through
134 the pointers and __Block_byref_x_VarName struct to find the actual
135 value of the variable. The function addBlockByrefType does this. */
137 unsigned tag = Ty.getTag();
139 if (tag == dwarf::DW_TAG_pointer_type) {
140 DIDerivedType DTy = DIDerivedType(Ty);
141 subType = DTy.getTypeDerivedFrom();
144 DICompositeType blockStruct = DICompositeType(subType);
145 DIArray Elements = blockStruct.getTypeArray();
147 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
148 DIDescriptor Element = Elements.getElement(i);
149 DIDerivedType DT = DIDerivedType(Element);
150 if (getName() == DT.getName())
151 return (DT.getTypeDerivedFrom());
157 } // end llvm namespace
159 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
160 : Asm(A), MMI(Asm->MMI), FirstCU(0),
161 AbbreviationsSet(InitAbbreviationsSetSize),
162 SourceIdMap(DIEValueAllocator),
163 PrevLabel(NULL), GlobalCUIndexCount(0),
164 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
166 SkeletonAbbrevSet(InitAbbreviationsSetSize),
167 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
170 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
171 DwarfStrSectionSym = TextSectionSym = 0;
172 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
173 DwarfAddrSectionSym = 0;
174 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
175 FunctionBeginSym = FunctionEndSym = 0;
177 // Turn on accelerator tables and older gdb compatibility
179 bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
180 if (DarwinGDBCompat == Default) {
182 IsDarwinGDBCompat = true;
184 IsDarwinGDBCompat = false;
186 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
188 if (DwarfAccelTables == Default) {
190 HasDwarfAccelTables = true;
192 HasDwarfAccelTables = false;
194 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
196 if (SplitDwarf == Default)
197 HasSplitDwarf = false;
199 HasSplitDwarf = SplitDwarf == Enable ? true : false;
202 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
206 DwarfDebug::~DwarfDebug() {
209 // Switch to the specified MCSection and emit an assembler
210 // temporary label to it if SymbolStem is specified.
211 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
212 const char *SymbolStem = 0) {
213 Asm->OutStreamer.SwitchSection(Section);
214 if (!SymbolStem) return 0;
216 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
217 Asm->OutStreamer.EmitLabel(TmpSym);
221 MCSymbol *DwarfUnits::getStringPoolSym() {
222 return Asm->GetTempSymbol(StringPref);
225 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
226 std::pair<MCSymbol*, unsigned> &Entry =
227 StringPool.GetOrCreateValue(Str).getValue();
228 if (Entry.first) return Entry.first;
230 Entry.second = NextStringPoolNumber++;
231 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
234 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
235 std::pair<MCSymbol*, unsigned> &Entry =
236 StringPool.GetOrCreateValue(Str).getValue();
237 if (Entry.first) return Entry.second;
239 Entry.second = NextStringPoolNumber++;
240 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
244 unsigned DwarfUnits::getAddrPoolIndex(MCSymbol *Sym) {
245 std::pair<MCSymbol*, unsigned> &Entry = AddressPool[Sym];
246 if (Entry.first) return Entry.second;
248 Entry.second = NextAddrPoolNumber++;
253 // Define a unique number for the abbreviation.
255 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
256 // Profile the node so that we can make it unique.
260 // Check the set for priors.
261 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
263 // If it's newly added.
264 if (InSet == &Abbrev) {
265 // Add to abbreviation list.
266 Abbreviations->push_back(&Abbrev);
268 // Assign the vector position + 1 as its number.
269 Abbrev.setNumber(Abbreviations->size());
271 // Assign existing abbreviation number.
272 Abbrev.setNumber(InSet->getNumber());
276 // If special LLVM prefix that is used to inform the asm
277 // printer to not emit usual symbol prefix before the symbol name is used then
278 // return linkage name after skipping this special LLVM prefix.
279 static StringRef getRealLinkageName(StringRef LinkageName) {
281 if (LinkageName.startswith(StringRef(&One, 1)))
282 return LinkageName.substr(1);
286 static bool isObjCClass(StringRef Name) {
287 return Name.startswith("+") || Name.startswith("-");
290 static bool hasObjCCategory(StringRef Name) {
291 if (!isObjCClass(Name)) return false;
293 size_t pos = Name.find(')');
294 if (pos != std::string::npos) {
295 if (Name[pos+1] != ' ') return false;
301 static void getObjCClassCategory(StringRef In, StringRef &Class,
302 StringRef &Category) {
303 if (!hasObjCCategory(In)) {
304 Class = In.slice(In.find('[') + 1, In.find(' '));
309 Class = In.slice(In.find('[') + 1, In.find('('));
310 Category = In.slice(In.find('[') + 1, In.find(' '));
314 static StringRef getObjCMethodName(StringRef In) {
315 return In.slice(In.find(' ') + 1, In.find(']'));
318 // Add the various names to the Dwarf accelerator table names.
319 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
321 if (!SP.isDefinition()) return;
323 TheCU->addAccelName(SP.getName(), Die);
325 // If the linkage name is different than the name, go ahead and output
326 // that as well into the name table.
327 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
328 TheCU->addAccelName(SP.getLinkageName(), Die);
330 // If this is an Objective-C selector name add it to the ObjC accelerator
332 if (isObjCClass(SP.getName())) {
333 StringRef Class, Category;
334 getObjCClassCategory(SP.getName(), Class, Category);
335 TheCU->addAccelObjC(Class, Die);
337 TheCU->addAccelObjC(Category, Die);
338 // Also add the base method name to the name table.
339 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
343 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
344 // and DW_AT_high_pc attributes. If there are global variables in this
345 // scope then create and insert DIEs for these variables.
346 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
347 const MDNode *SPNode) {
348 DIE *SPDie = SPCU->getDIE(SPNode);
350 assert(SPDie && "Unable to find subprogram DIE!");
351 DISubprogram SP(SPNode);
353 // If we're updating an abstract DIE, then we will be adding the children and
354 // object pointer later on. But what we don't want to do is process the
355 // concrete DIE twice.
356 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
358 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
359 // Pick up abstract subprogram DIE.
360 SPDie = new DIE(dwarf::DW_TAG_subprogram);
361 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
363 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
364 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
368 DISubprogram SPDecl = SP.getFunctionDeclaration();
369 if (!SPDecl.isSubprogram()) {
370 // There is not any need to generate specification DIE for a function
371 // defined at compile unit level. If a function is defined inside another
372 // function then gdb prefers the definition at top level and but does not
373 // expect specification DIE in parent function. So avoid creating
374 // specification DIE for a function defined inside a function.
375 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
376 !SP.getContext().isFile() &&
377 !isSubprogramContext(SP.getContext())) {
378 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
381 DICompositeType SPTy = SP.getType();
382 DIArray Args = SPTy.getTypeArray();
383 unsigned SPTag = SPTy.getTag();
384 if (SPTag == dwarf::DW_TAG_subroutine_type)
385 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
386 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
387 DIType ATy = DIType(Args.getElement(i));
388 SPCU->addType(Arg, ATy);
389 if (ATy.isArtificial())
390 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
391 if (ATy.isObjectPointer())
392 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
393 dwarf::DW_FORM_ref4, Arg);
394 SPDie->addChild(Arg);
396 DIE *SPDeclDie = SPDie;
397 SPDie = new DIE(dwarf::DW_TAG_subprogram);
398 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
399 dwarf::DW_FORM_ref4, SPDeclDie);
405 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
406 Asm->GetTempSymbol("func_begin",
407 Asm->getFunctionNumber()));
408 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
409 Asm->GetTempSymbol("func_end",
410 Asm->getFunctionNumber()));
411 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
412 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
413 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
415 // Add name to the name table, we do this here because we're guaranteed
416 // to have concrete versions of our DW_TAG_subprogram nodes.
417 addSubprogramNames(SPCU, SP, SPDie);
422 // Construct new DW_TAG_lexical_block for this scope and attach
423 // DW_AT_low_pc/DW_AT_high_pc labels.
424 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
425 LexicalScope *Scope) {
426 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
427 if (Scope->isAbstractScope())
430 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
434 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
435 if (Ranges.size() > 1) {
436 // .debug_range section has not been laid out yet. Emit offset in
437 // .debug_range as a uint, size 4, for now. emitDIE will handle
438 // DW_AT_ranges appropriately.
439 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
440 DebugRangeSymbols.size()
441 * Asm->getDataLayout().getPointerSize());
442 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
443 RE = Ranges.end(); RI != RE; ++RI) {
444 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
445 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
447 DebugRangeSymbols.push_back(NULL);
448 DebugRangeSymbols.push_back(NULL);
452 MCSymbol *Start = getLabelBeforeInsn(RI->first);
453 MCSymbol *End = getLabelAfterInsn(RI->second);
455 if (End == 0) return 0;
457 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
458 assert(End->isDefined() && "Invalid end label for an inlined scope!");
460 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
461 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
466 // This scope represents inlined body of a function. Construct DIE to
467 // represent this concrete inlined copy of the function.
468 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
469 LexicalScope *Scope) {
470 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
471 assert(Ranges.empty() == false &&
472 "LexicalScope does not have instruction markers!");
474 if (!Scope->getScopeNode())
476 DIScope DS(Scope->getScopeNode());
477 DISubprogram InlinedSP = getDISubprogram(DS);
478 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
480 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
484 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
485 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
486 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
488 if (StartLabel == 0 || EndLabel == 0) {
489 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
491 assert(StartLabel->isDefined() &&
492 "Invalid starting label for an inlined scope!");
493 assert(EndLabel->isDefined() &&
494 "Invalid end label for an inlined scope!");
496 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
497 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
498 dwarf::DW_FORM_ref4, OriginDIE);
500 if (Ranges.size() > 1) {
501 // .debug_range section has not been laid out yet. Emit offset in
502 // .debug_range as a uint, size 4, for now. emitDIE will handle
503 // DW_AT_ranges appropriately.
504 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
505 DebugRangeSymbols.size()
506 * Asm->getDataLayout().getPointerSize());
507 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
508 RE = Ranges.end(); RI != RE; ++RI) {
509 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
510 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
512 DebugRangeSymbols.push_back(NULL);
513 DebugRangeSymbols.push_back(NULL);
515 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
516 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
519 InlinedSubprogramDIEs.insert(OriginDIE);
521 // Track the start label for this inlined function.
522 //.debug_inlined section specification does not clearly state how
523 // to emit inlined scope that is split into multiple instruction ranges.
524 // For now, use first instruction range and emit low_pc/high_pc pair and
525 // corresponding .debug_inlined section entry for this pair.
526 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
527 I = InlineInfo.find(InlinedSP);
529 if (I == InlineInfo.end()) {
530 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
531 InlinedSPNodes.push_back(InlinedSP);
533 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
535 DILocation DL(Scope->getInlinedAt());
536 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
537 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
538 TheCU->getUniqueID()));
539 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
541 // Add name to the name table, we do this here because we're guaranteed
542 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
543 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
548 // Construct a DIE for this scope.
549 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
550 if (!Scope || !Scope->getScopeNode())
553 DIScope DS(Scope->getScopeNode());
554 // Early return to avoid creating dangling variable|scope DIEs.
555 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
559 SmallVector<DIE *, 8> Children;
560 DIE *ObjectPointer = NULL;
562 // Collect arguments for current function.
563 if (LScopes.isCurrentFunctionScope(Scope))
564 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
565 if (DbgVariable *ArgDV = CurrentFnArguments[i])
567 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
568 Children.push_back(Arg);
569 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
572 // Collect lexical scope children first.
573 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
574 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
576 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
577 Children.push_back(Variable);
578 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
580 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
581 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
582 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
583 Children.push_back(Nested);
584 DIE *ScopeDIE = NULL;
585 if (Scope->getInlinedAt())
586 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
587 else if (DS.isSubprogram()) {
588 ProcessedSPNodes.insert(DS);
589 if (Scope->isAbstractScope()) {
590 ScopeDIE = TheCU->getDIE(DS);
591 // Note down abstract DIE.
593 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
596 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
599 // There is no need to emit empty lexical block DIE.
600 if (Children.empty())
602 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
605 if (!ScopeDIE) return NULL;
608 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
609 E = Children.end(); I != E; ++I)
610 ScopeDIE->addChild(*I);
612 if (DS.isSubprogram() && ObjectPointer != NULL)
613 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
614 dwarf::DW_FORM_ref4, ObjectPointer);
616 if (DS.isSubprogram())
617 TheCU->addPubTypes(DISubprogram(DS));
622 // Look up the source id with the given directory and source file names.
623 // If none currently exists, create a new id and insert it in the
624 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
626 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
627 StringRef DirName, unsigned CUID) {
628 // If we use .loc in assembly, we can't separate .file entries according to
629 // compile units. Thus all files will belong to the default compile unit.
630 if (Asm->TM.hasMCUseLoc() &&
631 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
634 // If FE did not provide a file name, then assume stdin.
635 if (FileName.empty())
636 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
638 // TODO: this might not belong here. See if we can factor this better.
639 if (DirName == CompilationDir)
642 // FileIDCUMap stores the current ID for the given compile unit.
643 unsigned SrcId = FileIDCUMap[CUID] + 1;
645 // We look up the CUID/file/dir by concatenating them with a zero byte.
646 SmallString<128> NamePair;
647 NamePair += utostr(CUID);
650 NamePair += '\0'; // Zero bytes are not allowed in paths.
651 NamePair += FileName;
653 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
654 if (Ent.getValue() != SrcId)
655 return Ent.getValue();
657 FileIDCUMap[CUID] = SrcId;
658 // Print out a .file directive to specify files for .loc directives.
659 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
664 // Create new CompileUnit for the given metadata node with tag
665 // DW_TAG_compile_unit.
666 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
667 DICompileUnit DIUnit(N);
668 StringRef FN = DIUnit.getFilename();
669 CompilationDir = DIUnit.getDirectory();
671 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
672 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
673 DIUnit.getLanguage(), Die, Asm,
676 FileIDCUMap[NewCU->getUniqueID()] = 0;
677 // Call this to emit a .file directive if it wasn't emitted for the source
678 // file this CU comes from yet.
679 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
681 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
682 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
683 DIUnit.getLanguage());
684 NewCU->addString(Die, dwarf::DW_AT_name, FN);
686 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
687 // into an entity. We're using 0 (or a NULL label) for this. For
688 // split dwarf it's in the skeleton CU so omit it here.
689 if (!useSplitDwarf())
690 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
692 // Define start line table label for each Compile Unit.
693 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
694 NewCU->getUniqueID());
695 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
696 NewCU->getUniqueID());
698 // DW_AT_stmt_list is a offset of line number information for this
699 // compile unit in debug_line section. For split dwarf this is
700 // left in the skeleton CU and so not included.
701 // The line table entries are not always emitted in assembly, so it
702 // is not okay to use line_table_start here.
703 if (!useSplitDwarf()) {
704 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
705 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
706 NewCU->getUniqueID() == 0 ?
707 Asm->GetTempSymbol("section_line") : LineTableStartSym);
708 else if (NewCU->getUniqueID() == 0)
709 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
711 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
712 LineTableStartSym, DwarfLineSectionSym);
715 // If we're using split dwarf the compilation dir is going to be in the
716 // skeleton CU and so we don't need to duplicate it here.
717 if (!useSplitDwarf() && !CompilationDir.empty())
718 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
719 if (DIUnit.isOptimized())
720 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
722 StringRef Flags = DIUnit.getFlags();
724 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
726 if (unsigned RVer = DIUnit.getRunTimeVersion())
727 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
728 dwarf::DW_FORM_data1, RVer);
733 InfoHolder.addUnit(NewCU);
735 CUMap.insert(std::make_pair(N, NewCU));
739 // Construct subprogram DIE.
740 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
742 CompileUnit *&CURef = SPMap[N];
748 if (!SP.isDefinition())
749 // This is a method declaration which will be handled while constructing
753 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
756 TheCU->insertDIE(N, SubprogramDie);
758 // Add to context owner.
759 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
761 // Expose as global, if requested.
762 if (GenerateDwarfPubNamesSection)
763 TheCU->addGlobalName(SP.getName(), SubprogramDie);
766 // Emit all Dwarf sections that should come prior to the content. Create
767 // global DIEs and emit initial debug info sections. This is invoked by
768 // the target AsmPrinter.
769 void DwarfDebug::beginModule() {
770 if (DisableDebugInfoPrinting)
773 const Module *M = MMI->getModule();
775 // If module has named metadata anchors then use them, otherwise scan the
776 // module using debug info finder to collect debug info.
777 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
781 // Emit initial sections so we can reference labels later.
784 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
785 DICompileUnit CUNode(CU_Nodes->getOperand(i));
786 CompileUnit *CU = constructCompileUnit(CUNode);
787 DIArray GVs = CUNode.getGlobalVariables();
788 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
789 CU->createGlobalVariableDIE(GVs.getElement(i));
790 DIArray SPs = CUNode.getSubprograms();
791 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
792 constructSubprogramDIE(CU, SPs.getElement(i));
793 DIArray EnumTypes = CUNode.getEnumTypes();
794 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
795 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
796 DIArray RetainedTypes = CUNode.getRetainedTypes();
797 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
798 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
799 // If we're splitting the dwarf out now that we've got the entire
800 // CU then construct a skeleton CU based upon it.
801 if (useSplitDwarf()) {
802 // This should be a unique identifier when we want to build .dwp files.
803 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
804 // Now construct the skeleton CU associated.
805 constructSkeletonCU(CUNode);
809 // Tell MMI that we have debug info.
810 MMI->setDebugInfoAvailability(true);
812 // Prime section data.
813 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
816 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
817 void DwarfDebug::computeInlinedDIEs() {
818 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
819 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
820 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
822 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
824 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
825 AE = AbstractSPDies.end(); AI != AE; ++AI) {
826 DIE *ISP = AI->second;
827 if (InlinedSubprogramDIEs.count(ISP))
829 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
833 // Collect info for variables that were optimized out.
834 void DwarfDebug::collectDeadVariables() {
835 const Module *M = MMI->getModule();
836 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
838 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
839 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
840 DICompileUnit TheCU(CU_Nodes->getOperand(i));
841 DIArray Subprograms = TheCU.getSubprograms();
842 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
843 DISubprogram SP(Subprograms.getElement(i));
844 if (ProcessedSPNodes.count(SP) != 0) continue;
845 if (!SP.Verify()) continue;
846 if (!SP.isDefinition()) continue;
847 DIArray Variables = SP.getVariables();
848 if (Variables.getNumElements() == 0) continue;
850 LexicalScope *Scope =
851 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
852 DeadFnScopeMap[SP] = Scope;
854 // Construct subprogram DIE and add variables DIEs.
855 CompileUnit *SPCU = CUMap.lookup(TheCU);
856 assert(SPCU && "Unable to find Compile Unit!");
857 constructSubprogramDIE(SPCU, SP);
858 DIE *ScopeDIE = SPCU->getDIE(SP);
859 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
860 DIVariable DV(Variables.getElement(vi));
861 if (!DV.Verify()) continue;
862 DbgVariable *NewVar = new DbgVariable(DV, NULL);
863 if (DIE *VariableDIE =
864 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
865 ScopeDIE->addChild(VariableDIE);
870 DeleteContainerSeconds(DeadFnScopeMap);
873 void DwarfDebug::finalizeModuleInfo() {
874 // Collect info for variables that were optimized out.
875 collectDeadVariables();
877 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
878 computeInlinedDIEs();
880 // Emit DW_AT_containing_type attribute to connect types with their
881 // vtable holding type.
882 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
883 CUE = CUMap.end(); CUI != CUE; ++CUI) {
884 CompileUnit *TheCU = CUI->second;
885 TheCU->constructContainingTypeDIEs();
888 // Compute DIE offsets and sizes.
889 InfoHolder.computeSizeAndOffsets();
891 SkeletonHolder.computeSizeAndOffsets();
894 void DwarfDebug::endSections() {
895 // Standard sections final addresses.
896 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
897 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
898 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
899 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
901 // End text sections.
902 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
903 Asm->OutStreamer.SwitchSection(SectionMap[I]);
904 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
908 // Emit all Dwarf sections that should come after the content.
909 void DwarfDebug::endModule() {
911 if (!FirstCU) return;
913 // End any existing sections.
914 // TODO: Does this need to happen?
917 // Finalize the debug info for the module.
918 finalizeModuleInfo();
920 if (!useSplitDwarf()) {
921 // Emit all the DIEs into a debug info section.
924 // Corresponding abbreviations into a abbrev section.
927 // Emit info into a debug loc section.
930 // Emit info into a debug aranges section.
933 // Emit info into a debug ranges section.
936 // Emit info into a debug macinfo section.
940 // TODO: When we don't need the option anymore we
941 // can remove all of the code that this section
943 if (useDarwinGDBCompat())
944 emitDebugInlineInfo();
946 // TODO: Fill this in for separated debug sections and separate
947 // out information into new sections.
949 // Emit the debug info section and compile units.
953 // Corresponding abbreviations into a abbrev section.
955 emitDebugAbbrevDWO();
957 // Emit info into a debug loc section.
960 // Emit info into a debug aranges section.
963 // Emit info into a debug ranges section.
966 // Emit info into a debug macinfo section.
969 // Emit DWO addresses.
970 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
973 // TODO: When we don't need the option anymore we
974 // can remove all of the code that this section
976 if (useDarwinGDBCompat())
977 emitDebugInlineInfo();
980 // Emit info into the dwarf accelerator table sections.
981 if (useDwarfAccelTables()) {
984 emitAccelNamespaces();
988 // Emit info into a debug pubnames section, if requested.
989 if (GenerateDwarfPubNamesSection)
992 // Emit info into a debug pubtypes section.
993 // TODO: When we don't need the option anymore we can
994 // remove all of the code that adds to the table.
995 if (useDarwinGDBCompat())
998 // Finally emit string information into a string table.
1000 if (useSplitDwarf())
1005 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1006 E = CUMap.end(); I != E; ++I)
1009 for (SmallVector<CompileUnit *, 1>::iterator I = SkeletonCUs.begin(),
1010 E = SkeletonCUs.end(); I != E; ++I)
1013 // Reset these for the next Module if we have one.
1017 // Find abstract variable, if any, associated with Var.
1018 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1019 DebugLoc ScopeLoc) {
1020 LLVMContext &Ctx = DV->getContext();
1021 // More then one inlined variable corresponds to one abstract variable.
1022 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1023 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1025 return AbsDbgVariable;
1027 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1031 AbsDbgVariable = new DbgVariable(Var, NULL);
1032 addScopeVariable(Scope, AbsDbgVariable);
1033 AbstractVariables[Var] = AbsDbgVariable;
1034 return AbsDbgVariable;
1037 // If Var is a current function argument then add it to CurrentFnArguments list.
1038 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1039 DbgVariable *Var, LexicalScope *Scope) {
1040 if (!LScopes.isCurrentFunctionScope(Scope))
1042 DIVariable DV = Var->getVariable();
1043 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1045 unsigned ArgNo = DV.getArgNumber();
1049 size_t Size = CurrentFnArguments.size();
1051 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1052 // llvm::Function argument size is not good indicator of how many
1053 // arguments does the function have at source level.
1055 CurrentFnArguments.resize(ArgNo * 2);
1056 CurrentFnArguments[ArgNo - 1] = Var;
1060 // Collect variable information from side table maintained by MMI.
1062 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1063 SmallPtrSet<const MDNode *, 16> &Processed) {
1064 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1065 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1066 VE = VMap.end(); VI != VE; ++VI) {
1067 const MDNode *Var = VI->first;
1069 Processed.insert(Var);
1071 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1073 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1075 // If variable scope is not found then skip this variable.
1079 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1080 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1081 RegVar->setFrameIndex(VP.first);
1082 if (!addCurrentFnArgument(MF, RegVar, Scope))
1083 addScopeVariable(Scope, RegVar);
1085 AbsDbgVariable->setFrameIndex(VP.first);
1089 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1091 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1092 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1093 return MI->getNumOperands() == 3 &&
1094 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1095 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1098 // Get .debug_loc entry for the instruction range starting at MI.
1099 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1100 const MCSymbol *FLabel,
1101 const MCSymbol *SLabel,
1102 const MachineInstr *MI) {
1103 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1105 if (MI->getNumOperands() != 3) {
1106 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1107 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1109 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1110 MachineLocation MLoc;
1111 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1112 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1114 if (MI->getOperand(0).isImm())
1115 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1116 if (MI->getOperand(0).isFPImm())
1117 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1118 if (MI->getOperand(0).isCImm())
1119 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1121 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1124 // Find variables for each lexical scope.
1126 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1127 SmallPtrSet<const MDNode *, 16> &Processed) {
1129 // collection info from MMI table.
1130 collectVariableInfoFromMMITable(MF, Processed);
1132 for (SmallVectorImpl<const MDNode*>::const_iterator
1133 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1135 const MDNode *Var = *UVI;
1136 if (Processed.count(Var))
1139 // History contains relevant DBG_VALUE instructions for Var and instructions
1141 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1142 if (History.empty())
1144 const MachineInstr *MInsn = History.front();
1147 LexicalScope *Scope = NULL;
1148 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1149 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1150 Scope = LScopes.getCurrentFunctionScope();
1151 else if (MDNode *IA = DV.getInlinedAt())
1152 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1154 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1155 // If variable scope is not found then skip this variable.
1159 Processed.insert(DV);
1160 assert(MInsn->isDebugValue() && "History must begin with debug value");
1161 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1162 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1163 if (!addCurrentFnArgument(MF, RegVar, Scope))
1164 addScopeVariable(Scope, RegVar);
1166 AbsVar->setMInsn(MInsn);
1168 // Simplify ranges that are fully coalesced.
1169 if (History.size() <= 1 || (History.size() == 2 &&
1170 MInsn->isIdenticalTo(History.back()))) {
1171 RegVar->setMInsn(MInsn);
1175 // Handle multiple DBG_VALUE instructions describing one variable.
1176 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1178 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1179 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1180 const MachineInstr *Begin = *HI;
1181 assert(Begin->isDebugValue() && "Invalid History entry");
1183 // Check if DBG_VALUE is truncating a range.
1184 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1185 && !Begin->getOperand(0).getReg())
1188 // Compute the range for a register location.
1189 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1190 const MCSymbol *SLabel = 0;
1193 // If Begin is the last instruction in History then its value is valid
1194 // until the end of the function.
1195 SLabel = FunctionEndSym;
1197 const MachineInstr *End = HI[1];
1198 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1199 << "\t" << *Begin << "\t" << *End << "\n");
1200 if (End->isDebugValue())
1201 SLabel = getLabelBeforeInsn(End);
1203 // End is a normal instruction clobbering the range.
1204 SLabel = getLabelAfterInsn(End);
1205 assert(SLabel && "Forgot label after clobber instruction");
1210 // The value is valid until the next DBG_VALUE or clobber.
1211 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1214 DotDebugLocEntries.push_back(DotDebugLocEntry());
1217 // Collect info for variables that were optimized out.
1218 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1219 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1220 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1221 DIVariable DV(Variables.getElement(i));
1222 if (!DV || !DV.Verify() || !Processed.insert(DV))
1224 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1225 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1229 // Return Label preceding the instruction.
1230 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1231 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1232 assert(Label && "Didn't insert label before instruction");
1236 // Return Label immediately following the instruction.
1237 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1238 return LabelsAfterInsn.lookup(MI);
1241 // Process beginning of an instruction.
1242 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1243 // Check if source location changes, but ignore DBG_VALUE locations.
1244 if (!MI->isDebugValue()) {
1245 DebugLoc DL = MI->getDebugLoc();
1246 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1249 if (DL == PrologEndLoc) {
1250 Flags |= DWARF2_FLAG_PROLOGUE_END;
1251 PrologEndLoc = DebugLoc();
1253 if (PrologEndLoc.isUnknown())
1254 Flags |= DWARF2_FLAG_IS_STMT;
1256 if (!DL.isUnknown()) {
1257 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1258 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1260 recordSourceLine(0, 0, 0, 0);
1264 // Insert labels where requested.
1265 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1266 LabelsBeforeInsn.find(MI);
1269 if (I == LabelsBeforeInsn.end())
1272 // Label already assigned.
1277 PrevLabel = MMI->getContext().CreateTempSymbol();
1278 Asm->OutStreamer.EmitLabel(PrevLabel);
1280 I->second = PrevLabel;
1283 // Process end of an instruction.
1284 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1285 // Don't create a new label after DBG_VALUE instructions.
1286 // They don't generate code.
1287 if (!MI->isDebugValue())
1290 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1291 LabelsAfterInsn.find(MI);
1294 if (I == LabelsAfterInsn.end())
1297 // Label already assigned.
1301 // We need a label after this instruction.
1303 PrevLabel = MMI->getContext().CreateTempSymbol();
1304 Asm->OutStreamer.EmitLabel(PrevLabel);
1306 I->second = PrevLabel;
1309 // Each LexicalScope has first instruction and last instruction to mark
1310 // beginning and end of a scope respectively. Create an inverse map that list
1311 // scopes starts (and ends) with an instruction. One instruction may start (or
1312 // end) multiple scopes. Ignore scopes that are not reachable.
1313 void DwarfDebug::identifyScopeMarkers() {
1314 SmallVector<LexicalScope *, 4> WorkList;
1315 WorkList.push_back(LScopes.getCurrentFunctionScope());
1316 while (!WorkList.empty()) {
1317 LexicalScope *S = WorkList.pop_back_val();
1319 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1320 if (!Children.empty())
1321 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1322 SE = Children.end(); SI != SE; ++SI)
1323 WorkList.push_back(*SI);
1325 if (S->isAbstractScope())
1328 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1331 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1332 RE = Ranges.end(); RI != RE; ++RI) {
1333 assert(RI->first && "InsnRange does not have first instruction!");
1334 assert(RI->second && "InsnRange does not have second instruction!");
1335 requestLabelBeforeInsn(RI->first);
1336 requestLabelAfterInsn(RI->second);
1341 // Get MDNode for DebugLoc's scope.
1342 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1343 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1344 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1345 return DL.getScope(Ctx);
1348 // Walk up the scope chain of given debug loc and find line number info
1349 // for the function.
1350 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1351 const MDNode *Scope = getScopeNode(DL, Ctx);
1352 DISubprogram SP = getDISubprogram(Scope);
1354 // Check for number of operands since the compatibility is
1356 if (SP->getNumOperands() > 19)
1357 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1359 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1365 // Gather pre-function debug information. Assumes being called immediately
1366 // after the function entry point has been emitted.
1367 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1368 if (!MMI->hasDebugInfo()) return;
1369 LScopes.initialize(*MF);
1370 if (LScopes.empty()) return;
1371 identifyScopeMarkers();
1373 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1375 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1376 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1377 assert(TheCU && "Unable to find compile unit!");
1378 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1380 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1381 Asm->getFunctionNumber());
1382 // Assumes in correct section after the entry point.
1383 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1385 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1387 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1388 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1389 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1391 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1393 bool AtBlockEntry = true;
1394 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1396 const MachineInstr *MI = II;
1398 if (MI->isDebugValue()) {
1399 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1401 // Keep track of user variables.
1403 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1405 // Variable is in a register, we need to check for clobbers.
1406 if (isDbgValueInDefinedReg(MI))
1407 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1409 // Check the history of this variable.
1410 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1411 if (History.empty()) {
1412 UserVariables.push_back(Var);
1413 // The first mention of a function argument gets the FunctionBeginSym
1414 // label, so arguments are visible when breaking at function entry.
1416 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1417 DISubprogram(getDISubprogram(DV.getContext()))
1418 .describes(MF->getFunction()))
1419 LabelsBeforeInsn[MI] = FunctionBeginSym;
1421 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1422 const MachineInstr *Prev = History.back();
1423 if (Prev->isDebugValue()) {
1424 // Coalesce identical entries at the end of History.
1425 if (History.size() >= 2 &&
1426 Prev->isIdenticalTo(History[History.size() - 2])) {
1427 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1429 << "\t" << *History[History.size() - 2] << "\n");
1433 // Terminate old register assignments that don't reach MI;
1434 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1435 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1436 isDbgValueInDefinedReg(Prev)) {
1437 // Previous register assignment needs to terminate at the end of
1439 MachineBasicBlock::const_iterator LastMI =
1440 PrevMBB->getLastNonDebugInstr();
1441 if (LastMI == PrevMBB->end()) {
1442 // Drop DBG_VALUE for empty range.
1443 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1444 << "\t" << *Prev << "\n");
1448 // Terminate after LastMI.
1449 History.push_back(LastMI);
1454 History.push_back(MI);
1456 // Not a DBG_VALUE instruction.
1458 AtBlockEntry = false;
1460 // First known non-DBG_VALUE and non-frame setup location marks
1461 // the beginning of the function body.
1462 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1463 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1464 PrologEndLoc = MI->getDebugLoc();
1466 // Check if the instruction clobbers any registers with debug vars.
1467 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1468 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1469 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1471 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1472 AI.isValid(); ++AI) {
1474 const MDNode *Var = LiveUserVar[Reg];
1477 // Reg is now clobbered.
1478 LiveUserVar[Reg] = 0;
1480 // Was MD last defined by a DBG_VALUE referring to Reg?
1481 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1482 if (HistI == DbgValues.end())
1484 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1485 if (History.empty())
1487 const MachineInstr *Prev = History.back();
1488 // Sanity-check: Register assignments are terminated at the end of
1490 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1492 // Is the variable still in Reg?
1493 if (!isDbgValueInDefinedReg(Prev) ||
1494 Prev->getOperand(0).getReg() != Reg)
1496 // Var is clobbered. Make sure the next instruction gets a label.
1497 History.push_back(MI);
1504 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1506 SmallVectorImpl<const MachineInstr*> &History = I->second;
1507 if (History.empty())
1510 // Make sure the final register assignments are terminated.
1511 const MachineInstr *Prev = History.back();
1512 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1513 const MachineBasicBlock *PrevMBB = Prev->getParent();
1514 MachineBasicBlock::const_iterator LastMI =
1515 PrevMBB->getLastNonDebugInstr();
1516 if (LastMI == PrevMBB->end())
1517 // Drop DBG_VALUE for empty range.
1520 // Terminate after LastMI.
1521 History.push_back(LastMI);
1524 // Request labels for the full history.
1525 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1526 const MachineInstr *MI = History[i];
1527 if (MI->isDebugValue())
1528 requestLabelBeforeInsn(MI);
1530 requestLabelAfterInsn(MI);
1534 PrevInstLoc = DebugLoc();
1535 PrevLabel = FunctionBeginSym;
1537 // Record beginning of function.
1538 if (!PrologEndLoc.isUnknown()) {
1539 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1540 MF->getFunction()->getContext());
1541 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1542 FnStartDL.getScope(MF->getFunction()->getContext()),
1543 // We'd like to list the prologue as "not statements" but GDB behaves
1544 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1545 DWARF2_FLAG_IS_STMT);
1549 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1550 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1551 ScopeVariables[LS].push_back(Var);
1552 // Vars.push_back(Var);
1555 // Gather and emit post-function debug information.
1556 void DwarfDebug::endFunction(const MachineFunction *MF) {
1557 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1559 // Define end label for subprogram.
1560 FunctionEndSym = Asm->GetTempSymbol("func_end",
1561 Asm->getFunctionNumber());
1562 // Assumes in correct section after the entry point.
1563 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1564 // Set DwarfCompileUnitID in MCContext to default value.
1565 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1567 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1568 collectVariableInfo(MF, ProcessedVars);
1570 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1571 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1572 assert(TheCU && "Unable to find compile unit!");
1574 // Construct abstract scopes.
1575 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1576 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1577 LexicalScope *AScope = AList[i];
1578 DISubprogram SP(AScope->getScopeNode());
1580 // Collect info for variables that were optimized out.
1581 DIArray Variables = SP.getVariables();
1582 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1583 DIVariable DV(Variables.getElement(i));
1584 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1586 // Check that DbgVariable for DV wasn't created earlier, when
1587 // findAbstractVariable() was called for inlined instance of DV.
1588 LLVMContext &Ctx = DV->getContext();
1589 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1590 if (AbstractVariables.lookup(CleanDV))
1592 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1593 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1596 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1597 constructScopeDIE(TheCU, AScope);
1600 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1602 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1603 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1605 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1606 MMI->getFrameMoves()));
1609 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1610 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1611 DeleteContainerPointers(I->second);
1612 ScopeVariables.clear();
1613 DeleteContainerPointers(CurrentFnArguments);
1614 UserVariables.clear();
1616 AbstractVariables.clear();
1617 LabelsBeforeInsn.clear();
1618 LabelsAfterInsn.clear();
1622 // Register a source line with debug info. Returns the unique label that was
1623 // emitted and which provides correspondence to the source line list.
1624 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1630 DIDescriptor Scope(S);
1632 if (Scope.isCompileUnit()) {
1633 DICompileUnit CU(S);
1634 Fn = CU.getFilename();
1635 Dir = CU.getDirectory();
1636 } else if (Scope.isFile()) {
1638 Fn = F.getFilename();
1639 Dir = F.getDirectory();
1640 } else if (Scope.isSubprogram()) {
1642 Fn = SP.getFilename();
1643 Dir = SP.getDirectory();
1644 } else if (Scope.isLexicalBlockFile()) {
1645 DILexicalBlockFile DBF(S);
1646 Fn = DBF.getFilename();
1647 Dir = DBF.getDirectory();
1648 } else if (Scope.isLexicalBlock()) {
1649 DILexicalBlock DB(S);
1650 Fn = DB.getFilename();
1651 Dir = DB.getDirectory();
1653 llvm_unreachable("Unexpected scope info");
1655 Src = getOrCreateSourceID(Fn, Dir,
1656 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1658 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1661 //===----------------------------------------------------------------------===//
1663 //===----------------------------------------------------------------------===//
1665 // Compute the size and offset of a DIE.
1667 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1668 // Get the children.
1669 const std::vector<DIE *> &Children = Die->getChildren();
1671 // Record the abbreviation.
1672 assignAbbrevNumber(Die->getAbbrev());
1674 // Get the abbreviation for this DIE.
1675 unsigned AbbrevNumber = Die->getAbbrevNumber();
1676 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1679 Die->setOffset(Offset);
1681 // Start the size with the size of abbreviation code.
1682 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1684 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1685 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1687 // Size the DIE attribute values.
1688 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1689 // Size attribute value.
1690 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1692 // Size the DIE children if any.
1693 if (!Children.empty()) {
1694 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1695 "Children flag not set");
1697 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1698 Offset = computeSizeAndOffset(Children[j], Offset);
1700 // End of children marker.
1701 Offset += sizeof(int8_t);
1704 Die->setSize(Offset - Die->getOffset());
1708 // Compute the size and offset of all the DIEs.
1709 void DwarfUnits::computeSizeAndOffsets() {
1710 // Offset from the beginning of debug info section.
1711 unsigned AccuOffset = 0;
1712 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1713 E = CUs.end(); I != E; ++I) {
1714 (*I)->setDebugInfoOffset(AccuOffset);
1716 sizeof(int32_t) + // Length of Compilation Unit Info
1717 sizeof(int16_t) + // DWARF version number
1718 sizeof(int32_t) + // Offset Into Abbrev. Section
1719 sizeof(int8_t); // Pointer Size (in bytes)
1721 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1722 AccuOffset += EndOffset;
1726 // Emit initial Dwarf sections with a label at the start of each one.
1727 void DwarfDebug::emitSectionLabels() {
1728 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1730 // Dwarf sections base addresses.
1731 DwarfInfoSectionSym =
1732 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1733 DwarfAbbrevSectionSym =
1734 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1735 if (useSplitDwarf())
1736 DwarfAbbrevDWOSectionSym =
1737 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1738 "section_abbrev_dwo");
1739 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1741 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1742 emitSectionSym(Asm, MacroInfo);
1744 DwarfLineSectionSym =
1745 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1746 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1747 if (GenerateDwarfPubNamesSection)
1748 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1749 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1750 DwarfStrSectionSym =
1751 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1752 if (useSplitDwarf()) {
1753 DwarfStrDWOSectionSym =
1754 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1755 DwarfAddrSectionSym =
1756 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1758 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1761 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1762 "section_debug_loc");
1764 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1765 emitSectionSym(Asm, TLOF.getDataSection());
1768 // Recursively emits a debug information entry.
1769 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1770 // Get the abbreviation for this DIE.
1771 unsigned AbbrevNumber = Die->getAbbrevNumber();
1772 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1774 // Emit the code (index) for the abbreviation.
1775 if (Asm->isVerbose())
1776 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1777 Twine::utohexstr(Die->getOffset()) + ":0x" +
1778 Twine::utohexstr(Die->getSize()) + " " +
1779 dwarf::TagString(Abbrev->getTag()));
1780 Asm->EmitULEB128(AbbrevNumber);
1782 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1783 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1785 // Emit the DIE attribute values.
1786 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1787 unsigned Attr = AbbrevData[i].getAttribute();
1788 unsigned Form = AbbrevData[i].getForm();
1789 assert(Form && "Too many attributes for DIE (check abbreviation)");
1791 if (Asm->isVerbose())
1792 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1795 case dwarf::DW_AT_abstract_origin: {
1796 DIEEntry *E = cast<DIEEntry>(Values[i]);
1797 DIE *Origin = E->getEntry();
1798 unsigned Addr = Origin->getOffset();
1799 if (Form == dwarf::DW_FORM_ref_addr) {
1800 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1801 // section. Origin->getOffset() returns the offset from start of the
1803 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1804 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1806 Asm->EmitInt32(Addr);
1809 case dwarf::DW_AT_ranges: {
1810 // DW_AT_range Value encodes offset in debug_range section.
1811 DIEInteger *V = cast<DIEInteger>(Values[i]);
1813 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1814 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1818 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1820 DwarfDebugRangeSectionSym,
1825 case dwarf::DW_AT_location: {
1826 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1827 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1828 Asm->EmitLabelReference(L->getValue(), 4);
1830 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1832 Values[i]->EmitValue(Asm, Form);
1836 case dwarf::DW_AT_accessibility: {
1837 if (Asm->isVerbose()) {
1838 DIEInteger *V = cast<DIEInteger>(Values[i]);
1839 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1841 Values[i]->EmitValue(Asm, Form);
1845 // Emit an attribute using the defined form.
1846 Values[i]->EmitValue(Asm, Form);
1851 // Emit the DIE children if any.
1852 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1853 const std::vector<DIE *> &Children = Die->getChildren();
1855 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1856 emitDIE(Children[j], Abbrevs);
1858 if (Asm->isVerbose())
1859 Asm->OutStreamer.AddComment("End Of Children Mark");
1864 // Emit the various dwarf units to the unit section USection with
1865 // the abbreviations going into ASection.
1866 void DwarfUnits::emitUnits(DwarfDebug *DD,
1867 const MCSection *USection,
1868 const MCSection *ASection,
1869 const MCSymbol *ASectionSym) {
1870 Asm->OutStreamer.SwitchSection(USection);
1871 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1872 E = CUs.end(); I != E; ++I) {
1873 CompileUnit *TheCU = *I;
1874 DIE *Die = TheCU->getCUDie();
1876 // Emit the compile units header.
1878 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1879 TheCU->getUniqueID()));
1881 // Emit size of content not including length itself
1882 unsigned ContentSize = Die->getSize() +
1883 sizeof(int16_t) + // DWARF version number
1884 sizeof(int32_t) + // Offset Into Abbrev. Section
1885 sizeof(int8_t); // Pointer Size (in bytes)
1887 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1888 Asm->EmitInt32(ContentSize);
1889 Asm->OutStreamer.AddComment("DWARF version number");
1890 Asm->EmitInt16(dwarf::DWARF_VERSION);
1891 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1892 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1894 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1895 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1897 DD->emitDIE(Die, Abbreviations);
1898 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1899 TheCU->getUniqueID()));
1903 /// For a given compile unit DIE, returns offset from beginning of debug info.
1904 unsigned DwarfUnits::getCUOffset(DIE *Die) {
1905 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
1906 "Input DIE should be compile unit in getCUOffset.");
1907 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1908 E = CUs.end(); I != E; ++I) {
1909 CompileUnit *TheCU = *I;
1910 if (TheCU->getCUDie() == Die)
1911 return TheCU->getDebugInfoOffset();
1913 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
1916 // Emit the debug info section.
1917 void DwarfDebug::emitDebugInfo() {
1918 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1920 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1921 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1922 DwarfAbbrevSectionSym);
1925 // Emit the abbreviation section.
1926 void DwarfDebug::emitAbbreviations() {
1927 if (!useSplitDwarf())
1928 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1931 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1934 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1935 std::vector<DIEAbbrev *> *Abbrevs) {
1936 // Check to see if it is worth the effort.
1937 if (!Abbrevs->empty()) {
1938 // Start the debug abbrev section.
1939 Asm->OutStreamer.SwitchSection(Section);
1941 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1942 Asm->OutStreamer.EmitLabel(Begin);
1944 // For each abbrevation.
1945 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1946 // Get abbreviation data
1947 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1949 // Emit the abbrevations code (base 1 index.)
1950 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1952 // Emit the abbreviations data.
1956 // Mark end of abbreviations.
1957 Asm->EmitULEB128(0, "EOM(3)");
1959 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1960 Asm->OutStreamer.EmitLabel(End);
1964 // Emit the last address of the section and the end of the line matrix.
1965 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1966 // Define last address of section.
1967 Asm->OutStreamer.AddComment("Extended Op");
1970 Asm->OutStreamer.AddComment("Op size");
1971 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1972 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1973 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1975 Asm->OutStreamer.AddComment("Section end label");
1977 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
1978 Asm->getDataLayout().getPointerSize());
1980 // Mark end of matrix.
1981 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1987 // Emit visible names into a hashed accelerator table section.
1988 void DwarfDebug::emitAccelNames() {
1989 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
1990 dwarf::DW_FORM_data4));
1991 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1992 E = CUMap.end(); I != E; ++I) {
1993 CompileUnit *TheCU = I->second;
1994 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
1995 for (StringMap<std::vector<DIE*> >::const_iterator
1996 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
1997 const char *Name = GI->getKeyData();
1998 const std::vector<DIE *> &Entities = GI->second;
1999 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2000 DE = Entities.end(); DI != DE; ++DI)
2001 AT.AddName(Name, (*DI));
2005 AT.FinalizeTable(Asm, "Names");
2006 Asm->OutStreamer.SwitchSection(
2007 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2008 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2009 Asm->OutStreamer.EmitLabel(SectionBegin);
2011 // Emit the full data.
2012 AT.Emit(Asm, SectionBegin, &InfoHolder);
2015 // Emit objective C classes and categories into a hashed accelerator table
2017 void DwarfDebug::emitAccelObjC() {
2018 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2019 dwarf::DW_FORM_data4));
2020 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2021 E = CUMap.end(); I != E; ++I) {
2022 CompileUnit *TheCU = I->second;
2023 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2024 for (StringMap<std::vector<DIE*> >::const_iterator
2025 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2026 const char *Name = GI->getKeyData();
2027 const std::vector<DIE *> &Entities = GI->second;
2028 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2029 DE = Entities.end(); DI != DE; ++DI)
2030 AT.AddName(Name, (*DI));
2034 AT.FinalizeTable(Asm, "ObjC");
2035 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2036 .getDwarfAccelObjCSection());
2037 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2038 Asm->OutStreamer.EmitLabel(SectionBegin);
2040 // Emit the full data.
2041 AT.Emit(Asm, SectionBegin, &InfoHolder);
2044 // Emit namespace dies into a hashed accelerator table.
2045 void DwarfDebug::emitAccelNamespaces() {
2046 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2047 dwarf::DW_FORM_data4));
2048 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2049 E = CUMap.end(); I != E; ++I) {
2050 CompileUnit *TheCU = I->second;
2051 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2052 for (StringMap<std::vector<DIE*> >::const_iterator
2053 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2054 const char *Name = GI->getKeyData();
2055 const std::vector<DIE *> &Entities = GI->second;
2056 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2057 DE = Entities.end(); DI != DE; ++DI)
2058 AT.AddName(Name, (*DI));
2062 AT.FinalizeTable(Asm, "namespac");
2063 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2064 .getDwarfAccelNamespaceSection());
2065 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2066 Asm->OutStreamer.EmitLabel(SectionBegin);
2068 // Emit the full data.
2069 AT.Emit(Asm, SectionBegin, &InfoHolder);
2072 // Emit type dies into a hashed accelerator table.
2073 void DwarfDebug::emitAccelTypes() {
2074 std::vector<DwarfAccelTable::Atom> Atoms;
2075 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2076 dwarf::DW_FORM_data4));
2077 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2078 dwarf::DW_FORM_data2));
2079 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2080 dwarf::DW_FORM_data1));
2081 DwarfAccelTable AT(Atoms);
2082 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2083 E = CUMap.end(); I != E; ++I) {
2084 CompileUnit *TheCU = I->second;
2085 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2086 = TheCU->getAccelTypes();
2087 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2088 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2089 const char *Name = GI->getKeyData();
2090 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2091 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2092 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2093 AT.AddName(Name, (*DI).first, (*DI).second);
2097 AT.FinalizeTable(Asm, "types");
2098 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2099 .getDwarfAccelTypesSection());
2100 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2101 Asm->OutStreamer.EmitLabel(SectionBegin);
2103 // Emit the full data.
2104 AT.Emit(Asm, SectionBegin, &InfoHolder);
2107 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2109 void DwarfDebug::emitDebugPubnames() {
2110 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2112 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2113 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2114 CompileUnit *TheCU = I->second;
2115 unsigned ID = TheCU->getUniqueID();
2117 if (TheCU->getGlobalNames().empty())
2120 // Start the dwarf pubnames section.
2121 Asm->OutStreamer.SwitchSection(
2122 Asm->getObjFileLowering().getDwarfPubNamesSection());
2124 Asm->OutStreamer.AddComment("Length of Public Names Info");
2125 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2126 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2128 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2130 Asm->OutStreamer.AddComment("DWARF Version");
2131 Asm->EmitInt16(dwarf::DWARF_VERSION);
2133 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2134 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2135 DwarfInfoSectionSym);
2137 Asm->OutStreamer.AddComment("Compilation Unit Length");
2138 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2139 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2142 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2143 for (StringMap<DIE*>::const_iterator
2144 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2145 const char *Name = GI->getKeyData();
2146 const DIE *Entity = GI->second;
2148 Asm->OutStreamer.AddComment("DIE offset");
2149 Asm->EmitInt32(Entity->getOffset());
2151 if (Asm->isVerbose())
2152 Asm->OutStreamer.AddComment("External Name");
2153 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2156 Asm->OutStreamer.AddComment("End Mark");
2158 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2162 void DwarfDebug::emitDebugPubTypes() {
2163 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2164 E = CUMap.end(); I != E; ++I) {
2165 CompileUnit *TheCU = I->second;
2166 // Start the dwarf pubtypes section.
2167 Asm->OutStreamer.SwitchSection(
2168 Asm->getObjFileLowering().getDwarfPubTypesSection());
2169 Asm->OutStreamer.AddComment("Length of Public Types Info");
2170 Asm->EmitLabelDifference(
2171 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2172 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2174 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2175 TheCU->getUniqueID()));
2177 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2178 Asm->EmitInt16(dwarf::DWARF_VERSION);
2180 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2181 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2182 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2183 TheCU->getUniqueID()),
2184 DwarfInfoSectionSym);
2186 Asm->OutStreamer.AddComment("Compilation Unit Length");
2187 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2188 TheCU->getUniqueID()),
2189 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2190 TheCU->getUniqueID()),
2193 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2194 for (StringMap<DIE*>::const_iterator
2195 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2196 const char *Name = GI->getKeyData();
2197 DIE *Entity = GI->second;
2199 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2200 Asm->EmitInt32(Entity->getOffset());
2202 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2203 // Emit the name with a terminating null byte.
2204 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2207 Asm->OutStreamer.AddComment("End Mark");
2209 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2210 TheCU->getUniqueID()));
2214 // Emit strings into a string section.
2215 void DwarfUnits::emitStrings(const MCSection *StrSection,
2216 const MCSection *OffsetSection = NULL,
2217 const MCSymbol *StrSecSym = NULL) {
2219 if (StringPool.empty()) return;
2221 // Start the dwarf str section.
2222 Asm->OutStreamer.SwitchSection(StrSection);
2224 // Get all of the string pool entries and put them in an array by their ID so
2225 // we can sort them.
2226 SmallVector<std::pair<unsigned,
2227 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2229 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2230 I = StringPool.begin(), E = StringPool.end();
2232 Entries.push_back(std::make_pair(I->second.second, &*I));
2234 array_pod_sort(Entries.begin(), Entries.end());
2236 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2237 // Emit a label for reference from debug information entries.
2238 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2240 // Emit the string itself with a terminating null byte.
2241 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2242 Entries[i].second->getKeyLength()+1));
2245 // If we've got an offset section go ahead and emit that now as well.
2246 if (OffsetSection) {
2247 Asm->OutStreamer.SwitchSection(OffsetSection);
2248 unsigned offset = 0;
2249 unsigned size = 4; // FIXME: DWARF64 is 8.
2250 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2251 Asm->OutStreamer.EmitIntValue(offset, size);
2252 offset += Entries[i].second->getKeyLength() + 1;
2257 // Emit strings into a string section.
2258 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2260 if (AddressPool.empty()) return;
2262 // Start the dwarf addr section.
2263 Asm->OutStreamer.SwitchSection(AddrSection);
2265 // Get all of the string pool entries and put them in an array by their ID so
2266 // we can sort them.
2267 SmallVector<std::pair<unsigned,
2268 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2270 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2271 I = AddressPool.begin(), E = AddressPool.end();
2273 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2275 array_pod_sort(Entries.begin(), Entries.end());
2277 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2278 // Emit a label for reference from debug information entries.
2279 MCSymbol *Sym = Entries[i].second->first;
2281 Asm->EmitLabelReference(Entries[i].second->first,
2282 Asm->getDataLayout().getPointerSize());
2284 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2289 // Emit visible names into a debug str section.
2290 void DwarfDebug::emitDebugStr() {
2291 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2292 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2295 // Emit visible names into a debug loc section.
2296 void DwarfDebug::emitDebugLoc() {
2297 if (DotDebugLocEntries.empty())
2300 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2301 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2303 DotDebugLocEntry &Entry = *I;
2304 if (I + 1 != DotDebugLocEntries.end())
2308 // Start the dwarf loc section.
2309 Asm->OutStreamer.SwitchSection(
2310 Asm->getObjFileLowering().getDwarfLocSection());
2311 unsigned char Size = Asm->getDataLayout().getPointerSize();
2312 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2314 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2315 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2316 I != E; ++I, ++index) {
2317 DotDebugLocEntry &Entry = *I;
2318 if (Entry.isMerged()) continue;
2319 if (Entry.isEmpty()) {
2320 Asm->OutStreamer.EmitIntValue(0, Size);
2321 Asm->OutStreamer.EmitIntValue(0, Size);
2322 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2324 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2325 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2326 DIVariable DV(Entry.Variable);
2327 Asm->OutStreamer.AddComment("Loc expr size");
2328 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2329 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2330 Asm->EmitLabelDifference(end, begin, 2);
2331 Asm->OutStreamer.EmitLabel(begin);
2332 if (Entry.isInt()) {
2333 DIBasicType BTy(DV.getType());
2335 (BTy.getEncoding() == dwarf::DW_ATE_signed
2336 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2337 Asm->OutStreamer.AddComment("DW_OP_consts");
2338 Asm->EmitInt8(dwarf::DW_OP_consts);
2339 Asm->EmitSLEB128(Entry.getInt());
2341 Asm->OutStreamer.AddComment("DW_OP_constu");
2342 Asm->EmitInt8(dwarf::DW_OP_constu);
2343 Asm->EmitULEB128(Entry.getInt());
2345 } else if (Entry.isLocation()) {
2346 if (!DV.hasComplexAddress())
2348 Asm->EmitDwarfRegOp(Entry.Loc);
2350 // Complex address entry.
2351 unsigned N = DV.getNumAddrElements();
2353 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2354 if (Entry.Loc.getOffset()) {
2356 Asm->EmitDwarfRegOp(Entry.Loc);
2357 Asm->OutStreamer.AddComment("DW_OP_deref");
2358 Asm->EmitInt8(dwarf::DW_OP_deref);
2359 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2360 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2361 Asm->EmitSLEB128(DV.getAddrElement(1));
2363 // If first address element is OpPlus then emit
2364 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2365 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2366 Asm->EmitDwarfRegOp(Loc);
2370 Asm->EmitDwarfRegOp(Entry.Loc);
2373 // Emit remaining complex address elements.
2374 for (; i < N; ++i) {
2375 uint64_t Element = DV.getAddrElement(i);
2376 if (Element == DIBuilder::OpPlus) {
2377 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2378 Asm->EmitULEB128(DV.getAddrElement(++i));
2379 } else if (Element == DIBuilder::OpDeref) {
2380 if (!Entry.Loc.isReg())
2381 Asm->EmitInt8(dwarf::DW_OP_deref);
2383 llvm_unreachable("unknown Opcode found in complex address");
2387 // else ... ignore constant fp. There is not any good way to
2388 // to represent them here in dwarf.
2389 Asm->OutStreamer.EmitLabel(end);
2394 // Emit visible names into a debug aranges section.
2395 void DwarfDebug::emitDebugARanges() {
2396 // Start the dwarf aranges section.
2397 Asm->OutStreamer.SwitchSection(
2398 Asm->getObjFileLowering().getDwarfARangesSection());
2401 // Emit visible names into a debug ranges section.
2402 void DwarfDebug::emitDebugRanges() {
2403 // Start the dwarf ranges section.
2404 Asm->OutStreamer.SwitchSection(
2405 Asm->getObjFileLowering().getDwarfRangesSection());
2406 unsigned char Size = Asm->getDataLayout().getPointerSize();
2407 for (SmallVectorImpl<const MCSymbol *>::iterator
2408 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2411 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2413 Asm->OutStreamer.EmitIntValue(0, Size);
2417 // Emit visible names into a debug macinfo section.
2418 void DwarfDebug::emitDebugMacInfo() {
2419 if (const MCSection *LineInfo =
2420 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2421 // Start the dwarf macinfo section.
2422 Asm->OutStreamer.SwitchSection(LineInfo);
2426 // Emit inline info using following format.
2428 // 1. length of section
2429 // 2. Dwarf version number
2432 // Entries (one "entry" for each function that was inlined):
2434 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2435 // otherwise offset into __debug_str for regular function name.
2436 // 2. offset into __debug_str section for regular function name.
2437 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2438 // instances for the function.
2440 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2441 // inlined instance; the die_offset points to the inlined_subroutine die in the
2442 // __debug_info section, and the low_pc is the starting address for the
2443 // inlining instance.
2444 void DwarfDebug::emitDebugInlineInfo() {
2445 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2451 Asm->OutStreamer.SwitchSection(
2452 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2454 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2455 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2456 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2458 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2460 Asm->OutStreamer.AddComment("Dwarf Version");
2461 Asm->EmitInt16(dwarf::DWARF_VERSION);
2462 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2463 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2465 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2466 E = InlinedSPNodes.end(); I != E; ++I) {
2468 const MDNode *Node = *I;
2469 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2470 = InlineInfo.find(Node);
2471 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2472 DISubprogram SP(Node);
2473 StringRef LName = SP.getLinkageName();
2474 StringRef Name = SP.getName();
2476 Asm->OutStreamer.AddComment("MIPS linkage name");
2478 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2479 DwarfStrSectionSym);
2481 Asm->EmitSectionOffset(InfoHolder
2482 .getStringPoolEntry(getRealLinkageName(LName)),
2483 DwarfStrSectionSym);
2485 Asm->OutStreamer.AddComment("Function name");
2486 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2487 DwarfStrSectionSym);
2488 Asm->EmitULEB128(Labels.size(), "Inline count");
2490 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2491 LE = Labels.end(); LI != LE; ++LI) {
2492 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2493 Asm->EmitInt32(LI->second->getOffset());
2495 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2496 Asm->OutStreamer.EmitSymbolValue(LI->first,
2497 Asm->getDataLayout().getPointerSize());
2501 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2504 // DWARF5 Experimental Separate Dwarf emitters.
2506 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2507 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2508 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2509 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2510 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2511 DICompileUnit DIUnit(N);
2512 CompilationDir = DIUnit.getDirectory();
2514 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2515 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2516 DIUnit.getLanguage(), Die, Asm,
2517 this, &SkeletonHolder);
2519 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2520 DIUnit.getSplitDebugFilename());
2522 // This should be a unique identifier when we want to build .dwp files.
2523 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2525 // Relocate to the beginning of the addr_base section, else 0 for the beginning
2526 // of the one for this compile unit.
2527 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2528 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2529 DwarfAddrSectionSym);
2531 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset, 0);
2533 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2534 // into an entity. We're using 0, or a NULL label for this.
2535 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2537 // DW_AT_stmt_list is a offset of line number information for this
2538 // compile unit in debug_line section.
2539 // FIXME: Should handle multiple compile units.
2540 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2541 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2542 DwarfLineSectionSym);
2544 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2546 if (!CompilationDir.empty())
2547 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2549 SkeletonHolder.addUnit(NewCU);
2550 SkeletonCUs.push_back(NewCU);
2555 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2556 assert(useSplitDwarf() && "No split dwarf debug info?");
2557 emitAbbrevs(Section, &SkeletonAbbrevs);
2560 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2561 // compile units that would normally be in debug_info.
2562 void DwarfDebug::emitDebugInfoDWO() {
2563 assert(useSplitDwarf() && "No split dwarf debug info?");
2564 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2565 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2566 DwarfAbbrevDWOSectionSym);
2569 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2570 // abbreviations for the .debug_info.dwo section.
2571 void DwarfDebug::emitDebugAbbrevDWO() {
2572 assert(useSplitDwarf() && "No split dwarf?");
2573 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2577 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2578 // string section and is identical in format to traditional .debug_str
2580 void DwarfDebug::emitDebugStrDWO() {
2581 assert(useSplitDwarf() && "No split dwarf?");
2582 const MCSection *OffSec = Asm->getObjFileLowering()
2583 .getDwarfStrOffDWOSection();
2584 const MCSymbol *StrSym = DwarfStrSectionSym;
2585 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),