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::ZeroOrMore, 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 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
174 FunctionBeginSym = FunctionEndSym = 0;
176 // Turn on accelerator tables and older gdb compatibility
178 bool IsDarwin = Triple(M->getTargetTriple()).isOSDarwin();
179 if (DarwinGDBCompat == Default) {
181 IsDarwinGDBCompat = true;
183 IsDarwinGDBCompat = false;
185 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
187 if (DwarfAccelTables == Default) {
189 HasDwarfAccelTables = true;
191 HasDwarfAccelTables = false;
193 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
195 if (SplitDwarf == Default)
196 HasSplitDwarf = false;
198 HasSplitDwarf = SplitDwarf == Enable ? true : false;
201 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
205 DwarfDebug::~DwarfDebug() {
208 // Switch to the specified MCSection and emit an assembler
209 // temporary label to it if SymbolStem is specified.
210 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
211 const char *SymbolStem = 0) {
212 Asm->OutStreamer.SwitchSection(Section);
213 if (!SymbolStem) return 0;
215 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
216 Asm->OutStreamer.EmitLabel(TmpSym);
220 MCSymbol *DwarfUnits::getStringPoolSym() {
221 return Asm->GetTempSymbol(StringPref);
224 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
225 std::pair<MCSymbol*, unsigned> &Entry =
226 StringPool.GetOrCreateValue(Str).getValue();
227 if (Entry.first) return Entry.first;
229 Entry.second = NextStringPoolNumber++;
230 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
233 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
234 std::pair<MCSymbol*, unsigned> &Entry =
235 StringPool.GetOrCreateValue(Str).getValue();
236 if (Entry.first) return Entry.second;
238 Entry.second = NextStringPoolNumber++;
239 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
243 unsigned DwarfUnits::getAddrPoolIndex(MCSymbol *Sym) {
244 std::pair<MCSymbol*, unsigned> &Entry = AddressPool[Sym];
245 if (Entry.first) return Entry.second;
247 Entry.second = NextAddrPoolNumber++;
252 // Define a unique number for the abbreviation.
254 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
255 // Profile the node so that we can make it unique.
259 // Check the set for priors.
260 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
262 // If it's newly added.
263 if (InSet == &Abbrev) {
264 // Add to abbreviation list.
265 Abbreviations->push_back(&Abbrev);
267 // Assign the vector position + 1 as its number.
268 Abbrev.setNumber(Abbreviations->size());
270 // Assign existing abbreviation number.
271 Abbrev.setNumber(InSet->getNumber());
275 // If special LLVM prefix that is used to inform the asm
276 // printer to not emit usual symbol prefix before the symbol name is used then
277 // return linkage name after skipping this special LLVM prefix.
278 static StringRef getRealLinkageName(StringRef LinkageName) {
280 if (LinkageName.startswith(StringRef(&One, 1)))
281 return LinkageName.substr(1);
285 static bool isObjCClass(StringRef Name) {
286 return Name.startswith("+") || Name.startswith("-");
289 static bool hasObjCCategory(StringRef Name) {
290 if (!isObjCClass(Name)) return false;
292 size_t pos = Name.find(')');
293 if (pos != std::string::npos) {
294 if (Name[pos+1] != ' ') return false;
300 static void getObjCClassCategory(StringRef In, StringRef &Class,
301 StringRef &Category) {
302 if (!hasObjCCategory(In)) {
303 Class = In.slice(In.find('[') + 1, In.find(' '));
308 Class = In.slice(In.find('[') + 1, In.find('('));
309 Category = In.slice(In.find('[') + 1, In.find(' '));
313 static StringRef getObjCMethodName(StringRef In) {
314 return In.slice(In.find(' ') + 1, In.find(']'));
317 // Add the various names to the Dwarf accelerator table names.
318 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
320 if (!SP.isDefinition()) return;
322 TheCU->addAccelName(SP.getName(), Die);
324 // If the linkage name is different than the name, go ahead and output
325 // that as well into the name table.
326 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
327 TheCU->addAccelName(SP.getLinkageName(), Die);
329 // If this is an Objective-C selector name add it to the ObjC accelerator
331 if (isObjCClass(SP.getName())) {
332 StringRef Class, Category;
333 getObjCClassCategory(SP.getName(), Class, Category);
334 TheCU->addAccelObjC(Class, Die);
336 TheCU->addAccelObjC(Category, Die);
337 // Also add the base method name to the name table.
338 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
342 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
343 // and DW_AT_high_pc attributes. If there are global variables in this
344 // scope then create and insert DIEs for these variables.
345 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
346 const MDNode *SPNode) {
347 DIE *SPDie = SPCU->getDIE(SPNode);
349 assert(SPDie && "Unable to find subprogram DIE!");
350 DISubprogram SP(SPNode);
352 // If we're updating an abstract DIE, then we will be adding the children and
353 // object pointer later on. But what we don't want to do is process the
354 // concrete DIE twice.
355 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode)) {
356 // Pick up abstract subprogram DIE.
357 SPDie = new DIE(dwarf::DW_TAG_subprogram);
358 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
359 dwarf::DW_FORM_ref4, AbsSPDIE);
362 DISubprogram SPDecl = SP.getFunctionDeclaration();
363 if (!SPDecl.isSubprogram()) {
364 // There is not any need to generate specification DIE for a function
365 // defined at compile unit level. If a function is defined inside another
366 // function then gdb prefers the definition at top level and but does not
367 // expect specification DIE in parent function. So avoid creating
368 // specification DIE for a function defined inside a function.
369 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
370 !SP.getContext().isFile() &&
371 !isSubprogramContext(SP.getContext())) {
372 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
375 DICompositeType SPTy = SP.getType();
376 DIArray Args = SPTy.getTypeArray();
377 unsigned SPTag = SPTy.getTag();
378 if (SPTag == dwarf::DW_TAG_subroutine_type)
379 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
380 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
381 DIType ATy = DIType(Args.getElement(i));
382 SPCU->addType(Arg, ATy);
383 if (ATy.isArtificial())
384 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
385 if (ATy.isObjectPointer())
386 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
387 dwarf::DW_FORM_ref4, Arg);
388 SPDie->addChild(Arg);
390 DIE *SPDeclDie = SPDie;
391 SPDie = new DIE(dwarf::DW_TAG_subprogram);
392 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
393 dwarf::DW_FORM_ref4, SPDeclDie);
399 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
400 Asm->GetTempSymbol("func_begin",
401 Asm->getFunctionNumber()));
402 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
403 Asm->GetTempSymbol("func_end",
404 Asm->getFunctionNumber()));
405 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
406 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
407 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
409 // Add name to the name table, we do this here because we're guaranteed
410 // to have concrete versions of our DW_TAG_subprogram nodes.
411 addSubprogramNames(SPCU, SP, SPDie);
416 // Construct new DW_TAG_lexical_block for this scope and attach
417 // DW_AT_low_pc/DW_AT_high_pc labels.
418 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
419 LexicalScope *Scope) {
420 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
421 if (Scope->isAbstractScope())
424 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
428 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
429 if (Ranges.size() > 1) {
430 // .debug_range section has not been laid out yet. Emit offset in
431 // .debug_range as a uint, size 4, for now. emitDIE will handle
432 // DW_AT_ranges appropriately.
433 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
434 DebugRangeSymbols.size()
435 * Asm->getDataLayout().getPointerSize());
436 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
437 RE = Ranges.end(); RI != RE; ++RI) {
438 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
439 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
441 DebugRangeSymbols.push_back(NULL);
442 DebugRangeSymbols.push_back(NULL);
446 MCSymbol *Start = getLabelBeforeInsn(RI->first);
447 MCSymbol *End = getLabelAfterInsn(RI->second);
449 if (End == 0) return 0;
451 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
452 assert(End->isDefined() && "Invalid end label for an inlined scope!");
454 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
455 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
460 // This scope represents inlined body of a function. Construct DIE to
461 // represent this concrete inlined copy of the function.
462 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
463 LexicalScope *Scope) {
464 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
465 assert(Ranges.empty() == false &&
466 "LexicalScope does not have instruction markers!");
468 if (!Scope->getScopeNode())
470 DIScope DS(Scope->getScopeNode());
471 DISubprogram InlinedSP = getDISubprogram(DS);
472 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
474 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
478 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
479 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
480 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
482 if (StartLabel == 0 || EndLabel == 0) {
483 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
485 assert(StartLabel->isDefined() &&
486 "Invalid starting label for an inlined scope!");
487 assert(EndLabel->isDefined() &&
488 "Invalid end label for an inlined scope!");
490 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
491 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
492 dwarf::DW_FORM_ref4, OriginDIE);
494 if (Ranges.size() > 1) {
495 // .debug_range section has not been laid out yet. Emit offset in
496 // .debug_range as a uint, size 4, for now. emitDIE will handle
497 // DW_AT_ranges appropriately.
498 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
499 DebugRangeSymbols.size()
500 * Asm->getDataLayout().getPointerSize());
501 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
502 RE = Ranges.end(); RI != RE; ++RI) {
503 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
504 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
506 DebugRangeSymbols.push_back(NULL);
507 DebugRangeSymbols.push_back(NULL);
509 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
510 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
513 InlinedSubprogramDIEs.insert(OriginDIE);
515 // Track the start label for this inlined function.
516 //.debug_inlined section specification does not clearly state how
517 // to emit inlined scope that is split into multiple instruction ranges.
518 // For now, use first instruction range and emit low_pc/high_pc pair and
519 // corresponding .debug_inlined section entry for this pair.
520 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
521 I = InlineInfo.find(InlinedSP);
523 if (I == InlineInfo.end()) {
524 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
525 InlinedSPNodes.push_back(InlinedSP);
527 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
529 DILocation DL(Scope->getInlinedAt());
530 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
531 getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
532 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
534 // Add name to the name table, we do this here because we're guaranteed
535 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
536 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
541 // Construct a DIE for this scope.
542 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
543 if (!Scope || !Scope->getScopeNode())
546 DIScope DS(Scope->getScopeNode());
547 // Early return to avoid creating dangling variable|scope DIEs.
548 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
552 SmallVector<DIE *, 8> Children;
553 DIE *ObjectPointer = NULL;
555 // Collect arguments for current function.
556 if (LScopes.isCurrentFunctionScope(Scope))
557 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
558 if (DbgVariable *ArgDV = CurrentFnArguments[i])
560 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
561 Children.push_back(Arg);
562 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
565 // Collect lexical scope children first.
566 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
567 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
569 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
570 Children.push_back(Variable);
571 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
573 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
574 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
575 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
576 Children.push_back(Nested);
577 DIE *ScopeDIE = NULL;
578 if (Scope->getInlinedAt())
579 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
580 else if (DS.isSubprogram()) {
581 ProcessedSPNodes.insert(DS);
582 if (Scope->isAbstractScope()) {
583 ScopeDIE = TheCU->getDIE(DS);
584 // Note down abstract DIE.
586 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
589 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
592 // There is no need to emit empty lexical block DIE.
593 if (Children.empty())
595 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
598 if (!ScopeDIE) return NULL;
601 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
602 E = Children.end(); I != E; ++I)
603 ScopeDIE->addChild(*I);
605 if (DS.isSubprogram() && ObjectPointer != NULL)
606 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
607 dwarf::DW_FORM_ref4, ObjectPointer);
609 if (DS.isSubprogram())
610 TheCU->addPubTypes(DISubprogram(DS));
615 // Look up the source id with the given directory and source file names.
616 // If none currently exists, create a new id and insert it in the
617 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
619 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
621 // If FE did not provide a file name, then assume stdin.
622 if (FileName.empty())
623 return getOrCreateSourceID("<stdin>", StringRef());
625 // TODO: this might not belong here. See if we can factor this better.
626 if (DirName == CompilationDir)
629 unsigned SrcId = SourceIdMap.size()+1;
631 // We look up the file/dir pair by concatenating them with a zero byte.
632 SmallString<128> NamePair;
634 NamePair += '\0'; // Zero bytes are not allowed in paths.
635 NamePair += FileName;
637 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
638 if (Ent.getValue() != SrcId)
639 return Ent.getValue();
641 // Print out a .file directive to specify files for .loc directives.
642 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName);
647 // Create new CompileUnit for the given metadata node with tag
648 // DW_TAG_compile_unit.
649 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
650 DICompileUnit DIUnit(N);
651 StringRef FN = DIUnit.getFilename();
652 CompilationDir = DIUnit.getDirectory();
653 // Call this to emit a .file directive if it wasn't emitted for the source
654 // file this CU comes from yet.
655 getOrCreateSourceID(FN, CompilationDir);
657 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
658 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
659 DIUnit.getLanguage(), Die, Asm,
661 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
662 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
663 DIUnit.getLanguage());
664 NewCU->addString(Die, dwarf::DW_AT_name, FN);
665 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
666 // into an entity. We're using 0 (or a NULL label) for this.
667 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
669 // Define start line table label for each Compile Unit.
670 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
671 NewCU->getUniqueID());
672 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
673 NewCU->getUniqueID());
675 // DW_AT_stmt_list is a offset of line number information for this
676 // compile unit in debug_line section.
677 // The line table entries are not always emitted in assembly, so it
678 // is not okay to use line_table_start here.
679 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
680 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
681 NewCU->getUniqueID() == 0 ?
682 Asm->GetTempSymbol("section_line") : LineTableStartSym);
683 else if (NewCU->getUniqueID() == 0)
684 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
686 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
687 LineTableStartSym, DwarfLineSectionSym);
689 if (!CompilationDir.empty())
690 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
691 if (DIUnit.isOptimized())
692 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
694 StringRef Flags = DIUnit.getFlags();
696 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
698 if (unsigned RVer = DIUnit.getRunTimeVersion())
699 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
700 dwarf::DW_FORM_data1, RVer);
705 if (useSplitDwarf()) {
706 // This should be a unique identifier when we want to build .dwp files.
707 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
708 // Now construct the skeleton CU associated.
709 constructSkeletonCU(N);
712 InfoHolder.addUnit(NewCU);
714 CUMap.insert(std::make_pair(N, NewCU));
718 // Construct subprogram DIE.
719 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
721 CompileUnit *&CURef = SPMap[N];
727 if (!SP.isDefinition())
728 // This is a method declaration which will be handled while constructing
732 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
735 TheCU->insertDIE(N, SubprogramDie);
737 // Add to context owner.
738 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
740 // Expose as global, if requested.
741 if (GenerateDwarfPubNamesSection)
742 TheCU->addGlobalName(SP.getName(), SubprogramDie);
745 // Collect debug info from named mdnodes such as llvm.dbg.enum and llvm.dbg.ty.
746 void DwarfDebug::collectInfoFromNamedMDNodes(const Module *M) {
747 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.sp"))
748 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
749 const MDNode *N = NMD->getOperand(i);
750 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
751 constructSubprogramDIE(CU, N);
754 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.gv"))
755 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
756 const MDNode *N = NMD->getOperand(i);
757 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
758 CU->createGlobalVariableDIE(N);
761 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.enum"))
762 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
763 DIType Ty(NMD->getOperand(i));
764 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
765 CU->getOrCreateTypeDIE(Ty);
768 if (NamedMDNode *NMD = M->getNamedMetadata("llvm.dbg.ty"))
769 for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
770 DIType Ty(NMD->getOperand(i));
771 if (CompileUnit *CU = CUMap.lookup(Ty.getCompileUnit()))
772 CU->getOrCreateTypeDIE(Ty);
776 // Collect debug info using DebugInfoFinder.
777 // FIXME - Remove this when dragonegg switches to DIBuilder.
778 bool DwarfDebug::collectLegacyDebugInfo(const Module *M) {
779 DebugInfoFinder DbgFinder;
780 DbgFinder.processModule(*M);
782 bool HasDebugInfo = false;
783 // Scan all the compile-units to see if there are any marked as the main
784 // unit. If not, we do not generate debug info.
785 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
786 E = DbgFinder.compile_unit_end(); I != E; ++I) {
787 if (DICompileUnit(*I).isMain()) {
792 if (!HasDebugInfo) return false;
794 // Emit initial sections so we can refer to them later.
797 // Create all the compile unit DIEs.
798 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
799 E = DbgFinder.compile_unit_end(); I != E; ++I)
800 constructCompileUnit(*I);
802 // Create DIEs for each global variable.
803 for (DebugInfoFinder::iterator I = DbgFinder.global_variable_begin(),
804 E = DbgFinder.global_variable_end(); I != E; ++I) {
805 const MDNode *N = *I;
806 if (CompileUnit *CU = CUMap.lookup(DIGlobalVariable(N).getCompileUnit()))
807 CU->createGlobalVariableDIE(N);
810 // Create DIEs for each subprogram.
811 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
812 E = DbgFinder.subprogram_end(); I != E; ++I) {
813 const MDNode *N = *I;
814 if (CompileUnit *CU = CUMap.lookup(DISubprogram(N).getCompileUnit()))
815 constructSubprogramDIE(CU, N);
821 // Emit all Dwarf sections that should come prior to the content. Create
822 // global DIEs and emit initial debug info sections. This is invoked by
823 // the target AsmPrinter.
824 void DwarfDebug::beginModule() {
825 if (DisableDebugInfoPrinting)
828 const Module *M = MMI->getModule();
830 // If module has named metadata anchors then use them, otherwise scan the
831 // module using debug info finder to collect debug info.
832 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
834 // Emit initial sections so we can reference labels later.
837 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
838 DICompileUnit CUNode(CU_Nodes->getOperand(i));
839 CompileUnit *CU = constructCompileUnit(CUNode);
840 DIArray GVs = CUNode.getGlobalVariables();
841 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
842 CU->createGlobalVariableDIE(GVs.getElement(i));
843 DIArray SPs = CUNode.getSubprograms();
844 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
845 constructSubprogramDIE(CU, SPs.getElement(i));
846 DIArray EnumTypes = CUNode.getEnumTypes();
847 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
848 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
849 DIArray RetainedTypes = CUNode.getRetainedTypes();
850 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
851 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
853 } else if (!collectLegacyDebugInfo(M))
856 collectInfoFromNamedMDNodes(M);
858 // Tell MMI that we have debug info.
859 MMI->setDebugInfoAvailability(true);
861 // Prime section data.
862 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
865 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
866 void DwarfDebug::computeInlinedDIEs() {
867 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
868 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
869 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
871 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
873 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
874 AE = AbstractSPDies.end(); AI != AE; ++AI) {
875 DIE *ISP = AI->second;
876 if (InlinedSubprogramDIEs.count(ISP))
878 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
882 // Collect info for variables that were optimized out.
883 void DwarfDebug::collectDeadVariables() {
884 const Module *M = MMI->getModule();
885 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
887 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
888 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
889 DICompileUnit TheCU(CU_Nodes->getOperand(i));
890 DIArray Subprograms = TheCU.getSubprograms();
891 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
892 DISubprogram SP(Subprograms.getElement(i));
893 if (ProcessedSPNodes.count(SP) != 0) continue;
894 if (!SP.Verify()) continue;
895 if (!SP.isDefinition()) continue;
896 DIArray Variables = SP.getVariables();
897 if (Variables.getNumElements() == 0) continue;
899 LexicalScope *Scope =
900 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
901 DeadFnScopeMap[SP] = Scope;
903 // Construct subprogram DIE and add variables DIEs.
904 CompileUnit *SPCU = CUMap.lookup(TheCU);
905 assert(SPCU && "Unable to find Compile Unit!");
906 constructSubprogramDIE(SPCU, SP);
907 DIE *ScopeDIE = SPCU->getDIE(SP);
908 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
909 DIVariable DV(Variables.getElement(vi));
910 if (!DV.Verify()) continue;
911 DbgVariable *NewVar = new DbgVariable(DV, NULL);
912 if (DIE *VariableDIE =
913 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
914 ScopeDIE->addChild(VariableDIE);
919 DeleteContainerSeconds(DeadFnScopeMap);
922 void DwarfDebug::finalizeModuleInfo() {
923 // Collect info for variables that were optimized out.
924 collectDeadVariables();
926 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
927 computeInlinedDIEs();
929 // Emit DW_AT_containing_type attribute to connect types with their
930 // vtable holding type.
931 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
932 CUE = CUMap.end(); CUI != CUE; ++CUI) {
933 CompileUnit *TheCU = CUI->second;
934 TheCU->constructContainingTypeDIEs();
937 // Compute DIE offsets and sizes.
938 InfoHolder.computeSizeAndOffsets();
940 SkeletonHolder.computeSizeAndOffsets();
943 void DwarfDebug::endSections() {
944 // Standard sections final addresses.
945 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
946 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
947 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
948 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
950 // End text sections.
951 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
952 Asm->OutStreamer.SwitchSection(SectionMap[I]);
953 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
957 // Emit all Dwarf sections that should come after the content.
958 void DwarfDebug::endModule() {
960 if (!FirstCU) return;
962 // End any existing sections.
963 // TODO: Does this need to happen?
966 // Finalize the debug info for the module.
967 finalizeModuleInfo();
969 if (!useSplitDwarf()) {
970 // Emit all the DIEs into a debug info section.
973 // Corresponding abbreviations into a abbrev section.
976 // Emit info into a debug loc section.
979 // Emit info into a debug aranges section.
982 // Emit info into a debug ranges section.
985 // Emit info into a debug macinfo section.
989 // TODO: When we don't need the option anymore we
990 // can remove all of the code that this section
992 if (useDarwinGDBCompat())
993 emitDebugInlineInfo();
995 // TODO: Fill this in for separated debug sections and separate
996 // out information into new sections.
998 // Emit the debug info section and compile units.
1002 // Corresponding abbreviations into a abbrev section.
1003 emitAbbreviations();
1004 emitDebugAbbrevDWO();
1006 // Emit info into a debug loc section.
1009 // Emit info into a debug aranges section.
1012 // Emit info into a debug ranges section.
1015 // Emit info into a debug macinfo section.
1018 // Emit DWO addresses.
1019 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1021 // Emit inline info.
1022 // TODO: When we don't need the option anymore we
1023 // can remove all of the code that this section
1025 if (useDarwinGDBCompat())
1026 emitDebugInlineInfo();
1029 // Emit info into the dwarf accelerator table sections.
1030 if (useDwarfAccelTables()) {
1033 emitAccelNamespaces();
1037 // Emit info into a debug pubnames section, if requested.
1038 if (GenerateDwarfPubNamesSection)
1039 emitDebugPubnames();
1041 // Emit info into a debug pubtypes section.
1042 // TODO: When we don't need the option anymore we can
1043 // remove all of the code that adds to the table.
1044 if (useDarwinGDBCompat())
1045 emitDebugPubTypes();
1047 // Finally emit string information into a string table.
1049 if (useSplitDwarf())
1054 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1055 E = CUMap.end(); I != E; ++I)
1058 for (SmallVector<CompileUnit *, 1>::iterator I = SkeletonCUs.begin(),
1059 E = SkeletonCUs.end(); I != E; ++I)
1062 // Reset these for the next Module if we have one.
1066 // Find abstract variable, if any, associated with Var.
1067 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1068 DebugLoc ScopeLoc) {
1069 LLVMContext &Ctx = DV->getContext();
1070 // More then one inlined variable corresponds to one abstract variable.
1071 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1072 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1074 return AbsDbgVariable;
1076 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1080 AbsDbgVariable = new DbgVariable(Var, NULL);
1081 addScopeVariable(Scope, AbsDbgVariable);
1082 AbstractVariables[Var] = AbsDbgVariable;
1083 return AbsDbgVariable;
1086 // If Var is a current function argument then add it to CurrentFnArguments list.
1087 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1088 DbgVariable *Var, LexicalScope *Scope) {
1089 if (!LScopes.isCurrentFunctionScope(Scope))
1091 DIVariable DV = Var->getVariable();
1092 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1094 unsigned ArgNo = DV.getArgNumber();
1098 size_t Size = CurrentFnArguments.size();
1100 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1101 // llvm::Function argument size is not good indicator of how many
1102 // arguments does the function have at source level.
1104 CurrentFnArguments.resize(ArgNo * 2);
1105 CurrentFnArguments[ArgNo - 1] = Var;
1109 // Collect variable information from side table maintained by MMI.
1111 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1112 SmallPtrSet<const MDNode *, 16> &Processed) {
1113 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1114 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1115 VE = VMap.end(); VI != VE; ++VI) {
1116 const MDNode *Var = VI->first;
1118 Processed.insert(Var);
1120 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1122 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1124 // If variable scope is not found then skip this variable.
1128 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1129 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1130 RegVar->setFrameIndex(VP.first);
1131 if (!addCurrentFnArgument(MF, RegVar, Scope))
1132 addScopeVariable(Scope, RegVar);
1134 AbsDbgVariable->setFrameIndex(VP.first);
1138 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1140 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1141 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1142 return MI->getNumOperands() == 3 &&
1143 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1144 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1147 // Get .debug_loc entry for the instruction range starting at MI.
1148 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1149 const MCSymbol *FLabel,
1150 const MCSymbol *SLabel,
1151 const MachineInstr *MI) {
1152 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1154 if (MI->getNumOperands() != 3) {
1155 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1156 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1158 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1159 MachineLocation MLoc;
1160 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1161 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1163 if (MI->getOperand(0).isImm())
1164 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1165 if (MI->getOperand(0).isFPImm())
1166 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1167 if (MI->getOperand(0).isCImm())
1168 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1170 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1173 // Find variables for each lexical scope.
1175 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1176 SmallPtrSet<const MDNode *, 16> &Processed) {
1178 // collection info from MMI table.
1179 collectVariableInfoFromMMITable(MF, Processed);
1181 for (SmallVectorImpl<const MDNode*>::const_iterator
1182 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1184 const MDNode *Var = *UVI;
1185 if (Processed.count(Var))
1188 // History contains relevant DBG_VALUE instructions for Var and instructions
1190 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1191 if (History.empty())
1193 const MachineInstr *MInsn = History.front();
1196 LexicalScope *Scope = NULL;
1197 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1198 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1199 Scope = LScopes.getCurrentFunctionScope();
1201 if (DV.getVersion() <= LLVMDebugVersion9)
1202 Scope = LScopes.findLexicalScope(MInsn->getDebugLoc());
1204 if (MDNode *IA = DV.getInlinedAt())
1205 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1207 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1210 // If variable scope is not found then skip this variable.
1214 Processed.insert(DV);
1215 assert(MInsn->isDebugValue() && "History must begin with debug value");
1216 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1217 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1218 if (!addCurrentFnArgument(MF, RegVar, Scope))
1219 addScopeVariable(Scope, RegVar);
1221 AbsVar->setMInsn(MInsn);
1223 // Simplify ranges that are fully coalesced.
1224 if (History.size() <= 1 || (History.size() == 2 &&
1225 MInsn->isIdenticalTo(History.back()))) {
1226 RegVar->setMInsn(MInsn);
1230 // Handle multiple DBG_VALUE instructions describing one variable.
1231 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1233 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1234 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1235 const MachineInstr *Begin = *HI;
1236 assert(Begin->isDebugValue() && "Invalid History entry");
1238 // Check if DBG_VALUE is truncating a range.
1239 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1240 && !Begin->getOperand(0).getReg())
1243 // Compute the range for a register location.
1244 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1245 const MCSymbol *SLabel = 0;
1248 // If Begin is the last instruction in History then its value is valid
1249 // until the end of the function.
1250 SLabel = FunctionEndSym;
1252 const MachineInstr *End = HI[1];
1253 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1254 << "\t" << *Begin << "\t" << *End << "\n");
1255 if (End->isDebugValue())
1256 SLabel = getLabelBeforeInsn(End);
1258 // End is a normal instruction clobbering the range.
1259 SLabel = getLabelAfterInsn(End);
1260 assert(SLabel && "Forgot label after clobber instruction");
1265 // The value is valid until the next DBG_VALUE or clobber.
1266 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1269 DotDebugLocEntries.push_back(DotDebugLocEntry());
1272 // Collect info for variables that were optimized out.
1273 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1274 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1275 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1276 DIVariable DV(Variables.getElement(i));
1277 if (!DV || !DV.Verify() || !Processed.insert(DV))
1279 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1280 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1284 // Return Label preceding the instruction.
1285 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1286 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1287 assert(Label && "Didn't insert label before instruction");
1291 // Return Label immediately following the instruction.
1292 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1293 return LabelsAfterInsn.lookup(MI);
1296 // Process beginning of an instruction.
1297 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1298 // Check if source location changes, but ignore DBG_VALUE locations.
1299 if (!MI->isDebugValue()) {
1300 DebugLoc DL = MI->getDebugLoc();
1301 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1304 if (DL == PrologEndLoc) {
1305 Flags |= DWARF2_FLAG_PROLOGUE_END;
1306 PrologEndLoc = DebugLoc();
1308 if (PrologEndLoc.isUnknown())
1309 Flags |= DWARF2_FLAG_IS_STMT;
1311 if (!DL.isUnknown()) {
1312 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1313 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1315 recordSourceLine(0, 0, 0, 0);
1319 // Insert labels where requested.
1320 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1321 LabelsBeforeInsn.find(MI);
1324 if (I == LabelsBeforeInsn.end())
1327 // Label already assigned.
1332 PrevLabel = MMI->getContext().CreateTempSymbol();
1333 Asm->OutStreamer.EmitLabel(PrevLabel);
1335 I->second = PrevLabel;
1338 // Process end of an instruction.
1339 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1340 // Don't create a new label after DBG_VALUE instructions.
1341 // They don't generate code.
1342 if (!MI->isDebugValue())
1345 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1346 LabelsAfterInsn.find(MI);
1349 if (I == LabelsAfterInsn.end())
1352 // Label already assigned.
1356 // We need a label after this instruction.
1358 PrevLabel = MMI->getContext().CreateTempSymbol();
1359 Asm->OutStreamer.EmitLabel(PrevLabel);
1361 I->second = PrevLabel;
1364 // Each LexicalScope has first instruction and last instruction to mark
1365 // beginning and end of a scope respectively. Create an inverse map that list
1366 // scopes starts (and ends) with an instruction. One instruction may start (or
1367 // end) multiple scopes. Ignore scopes that are not reachable.
1368 void DwarfDebug::identifyScopeMarkers() {
1369 SmallVector<LexicalScope *, 4> WorkList;
1370 WorkList.push_back(LScopes.getCurrentFunctionScope());
1371 while (!WorkList.empty()) {
1372 LexicalScope *S = WorkList.pop_back_val();
1374 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1375 if (!Children.empty())
1376 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1377 SE = Children.end(); SI != SE; ++SI)
1378 WorkList.push_back(*SI);
1380 if (S->isAbstractScope())
1383 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1386 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1387 RE = Ranges.end(); RI != RE; ++RI) {
1388 assert(RI->first && "InsnRange does not have first instruction!");
1389 assert(RI->second && "InsnRange does not have second instruction!");
1390 requestLabelBeforeInsn(RI->first);
1391 requestLabelAfterInsn(RI->second);
1396 // Get MDNode for DebugLoc's scope.
1397 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1398 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1399 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1400 return DL.getScope(Ctx);
1403 // Walk up the scope chain of given debug loc and find line number info
1404 // for the function.
1405 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1406 const MDNode *Scope = getScopeNode(DL, Ctx);
1407 DISubprogram SP = getDISubprogram(Scope);
1409 // Check for number of operands since the compatibility is
1411 if (SP->getNumOperands() > 19)
1412 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1414 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1420 // Gather pre-function debug information. Assumes being called immediately
1421 // after the function entry point has been emitted.
1422 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1423 if (!MMI->hasDebugInfo()) return;
1424 LScopes.initialize(*MF);
1425 if (LScopes.empty()) return;
1426 identifyScopeMarkers();
1428 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1430 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1431 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1432 assert(TheCU && "Unable to find compile unit!");
1433 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1435 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1436 Asm->getFunctionNumber());
1437 // Assumes in correct section after the entry point.
1438 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1440 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1442 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1443 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1444 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1446 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1448 bool AtBlockEntry = true;
1449 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1451 const MachineInstr *MI = II;
1453 if (MI->isDebugValue()) {
1454 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1456 // Keep track of user variables.
1458 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1460 // Variable is in a register, we need to check for clobbers.
1461 if (isDbgValueInDefinedReg(MI))
1462 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1464 // Check the history of this variable.
1465 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1466 if (History.empty()) {
1467 UserVariables.push_back(Var);
1468 // The first mention of a function argument gets the FunctionBeginSym
1469 // label, so arguments are visible when breaking at function entry.
1471 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1472 DISubprogram(getDISubprogram(DV.getContext()))
1473 .describes(MF->getFunction()))
1474 LabelsBeforeInsn[MI] = FunctionBeginSym;
1476 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1477 const MachineInstr *Prev = History.back();
1478 if (Prev->isDebugValue()) {
1479 // Coalesce identical entries at the end of History.
1480 if (History.size() >= 2 &&
1481 Prev->isIdenticalTo(History[History.size() - 2])) {
1482 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1484 << "\t" << *History[History.size() - 2] << "\n");
1488 // Terminate old register assignments that don't reach MI;
1489 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1490 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1491 isDbgValueInDefinedReg(Prev)) {
1492 // Previous register assignment needs to terminate at the end of
1494 MachineBasicBlock::const_iterator LastMI =
1495 PrevMBB->getLastNonDebugInstr();
1496 if (LastMI == PrevMBB->end()) {
1497 // Drop DBG_VALUE for empty range.
1498 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1499 << "\t" << *Prev << "\n");
1503 // Terminate after LastMI.
1504 History.push_back(LastMI);
1509 History.push_back(MI);
1511 // Not a DBG_VALUE instruction.
1513 AtBlockEntry = false;
1515 // First known non-DBG_VALUE and non-frame setup location marks
1516 // the beginning of the function body.
1517 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1518 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1519 PrologEndLoc = MI->getDebugLoc();
1521 // Check if the instruction clobbers any registers with debug vars.
1522 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1523 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1524 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1526 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1527 AI.isValid(); ++AI) {
1529 const MDNode *Var = LiveUserVar[Reg];
1532 // Reg is now clobbered.
1533 LiveUserVar[Reg] = 0;
1535 // Was MD last defined by a DBG_VALUE referring to Reg?
1536 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1537 if (HistI == DbgValues.end())
1539 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1540 if (History.empty())
1542 const MachineInstr *Prev = History.back();
1543 // Sanity-check: Register assignments are terminated at the end of
1545 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1547 // Is the variable still in Reg?
1548 if (!isDbgValueInDefinedReg(Prev) ||
1549 Prev->getOperand(0).getReg() != Reg)
1551 // Var is clobbered. Make sure the next instruction gets a label.
1552 History.push_back(MI);
1559 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1561 SmallVectorImpl<const MachineInstr*> &History = I->second;
1562 if (History.empty())
1565 // Make sure the final register assignments are terminated.
1566 const MachineInstr *Prev = History.back();
1567 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1568 const MachineBasicBlock *PrevMBB = Prev->getParent();
1569 MachineBasicBlock::const_iterator LastMI =
1570 PrevMBB->getLastNonDebugInstr();
1571 if (LastMI == PrevMBB->end())
1572 // Drop DBG_VALUE for empty range.
1575 // Terminate after LastMI.
1576 History.push_back(LastMI);
1579 // Request labels for the full history.
1580 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1581 const MachineInstr *MI = History[i];
1582 if (MI->isDebugValue())
1583 requestLabelBeforeInsn(MI);
1585 requestLabelAfterInsn(MI);
1589 PrevInstLoc = DebugLoc();
1590 PrevLabel = FunctionBeginSym;
1592 // Record beginning of function.
1593 if (!PrologEndLoc.isUnknown()) {
1594 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1595 MF->getFunction()->getContext());
1596 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1597 FnStartDL.getScope(MF->getFunction()->getContext()),
1598 // We'd like to list the prologue as "not statements" but GDB behaves
1599 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1600 DWARF2_FLAG_IS_STMT);
1604 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1605 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1606 ScopeVariables[LS].push_back(Var);
1607 // Vars.push_back(Var);
1610 // Gather and emit post-function debug information.
1611 void DwarfDebug::endFunction(const MachineFunction *MF) {
1612 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1614 // Define end label for subprogram.
1615 FunctionEndSym = Asm->GetTempSymbol("func_end",
1616 Asm->getFunctionNumber());
1617 // Assumes in correct section after the entry point.
1618 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1619 // Set DwarfCompileUnitID in MCContext to default value.
1620 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1622 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1623 collectVariableInfo(MF, ProcessedVars);
1625 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1626 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1627 assert(TheCU && "Unable to find compile unit!");
1629 // Construct abstract scopes.
1630 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1631 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1632 LexicalScope *AScope = AList[i];
1633 DISubprogram SP(AScope->getScopeNode());
1635 // Collect info for variables that were optimized out.
1636 DIArray Variables = SP.getVariables();
1637 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1638 DIVariable DV(Variables.getElement(i));
1639 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1641 // Check that DbgVariable for DV wasn't created earlier, when
1642 // findAbstractVariable() was called for inlined instance of DV.
1643 LLVMContext &Ctx = DV->getContext();
1644 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1645 if (AbstractVariables.lookup(CleanDV))
1647 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1648 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1651 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1652 constructScopeDIE(TheCU, AScope);
1655 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1657 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1658 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1660 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1661 MMI->getFrameMoves()));
1664 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1665 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1666 DeleteContainerPointers(I->second);
1667 ScopeVariables.clear();
1668 DeleteContainerPointers(CurrentFnArguments);
1669 UserVariables.clear();
1671 AbstractVariables.clear();
1672 LabelsBeforeInsn.clear();
1673 LabelsAfterInsn.clear();
1677 // Register a source line with debug info. Returns the unique label that was
1678 // emitted and which provides correspondence to the source line list.
1679 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1685 DIDescriptor Scope(S);
1687 if (Scope.isCompileUnit()) {
1688 DICompileUnit CU(S);
1689 Fn = CU.getFilename();
1690 Dir = CU.getDirectory();
1691 } else if (Scope.isFile()) {
1693 Fn = F.getFilename();
1694 Dir = F.getDirectory();
1695 } else if (Scope.isSubprogram()) {
1697 Fn = SP.getFilename();
1698 Dir = SP.getDirectory();
1699 } else if (Scope.isLexicalBlockFile()) {
1700 DILexicalBlockFile DBF(S);
1701 Fn = DBF.getFilename();
1702 Dir = DBF.getDirectory();
1703 } else if (Scope.isLexicalBlock()) {
1704 DILexicalBlock DB(S);
1705 Fn = DB.getFilename();
1706 Dir = DB.getDirectory();
1708 llvm_unreachable("Unexpected scope info");
1710 Src = getOrCreateSourceID(Fn, Dir);
1712 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1715 //===----------------------------------------------------------------------===//
1717 //===----------------------------------------------------------------------===//
1719 // Compute the size and offset of a DIE.
1721 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1722 // Get the children.
1723 const std::vector<DIE *> &Children = Die->getChildren();
1725 // Record the abbreviation.
1726 assignAbbrevNumber(Die->getAbbrev());
1728 // Get the abbreviation for this DIE.
1729 unsigned AbbrevNumber = Die->getAbbrevNumber();
1730 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1733 Die->setOffset(Offset);
1735 // Start the size with the size of abbreviation code.
1736 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1738 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1739 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1741 // Size the DIE attribute values.
1742 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1743 // Size attribute value.
1744 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1746 // Size the DIE children if any.
1747 if (!Children.empty()) {
1748 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1749 "Children flag not set");
1751 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1752 Offset = computeSizeAndOffset(Children[j], Offset);
1754 // End of children marker.
1755 Offset += sizeof(int8_t);
1758 Die->setSize(Offset - Die->getOffset());
1762 // Compute the size and offset of all the DIEs.
1763 void DwarfUnits::computeSizeAndOffsets() {
1764 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1765 E = CUs.end(); I != E; ++I) {
1767 sizeof(int32_t) + // Length of Compilation Unit Info
1768 sizeof(int16_t) + // DWARF version number
1769 sizeof(int32_t) + // Offset Into Abbrev. Section
1770 sizeof(int8_t); // Pointer Size (in bytes)
1772 computeSizeAndOffset((*I)->getCUDie(), Offset);
1776 // Emit initial Dwarf sections with a label at the start of each one.
1777 void DwarfDebug::emitSectionLabels() {
1778 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1780 // Dwarf sections base addresses.
1781 DwarfInfoSectionSym =
1782 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1783 DwarfAbbrevSectionSym =
1784 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1785 if (useSplitDwarf())
1786 DwarfAbbrevDWOSectionSym =
1787 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1788 "section_abbrev_dwo");
1789 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1791 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1792 emitSectionSym(Asm, MacroInfo);
1794 DwarfLineSectionSym =
1795 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1796 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1797 if (GenerateDwarfPubNamesSection)
1798 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1799 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1800 DwarfStrSectionSym =
1801 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1802 if (useSplitDwarf())
1803 DwarfStrDWOSectionSym =
1804 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1805 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1808 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1809 "section_debug_loc");
1811 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1812 emitSectionSym(Asm, TLOF.getDataSection());
1815 // Recursively emits a debug information entry.
1816 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1817 // Get the abbreviation for this DIE.
1818 unsigned AbbrevNumber = Die->getAbbrevNumber();
1819 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1821 // Emit the code (index) for the abbreviation.
1822 if (Asm->isVerbose())
1823 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1824 Twine::utohexstr(Die->getOffset()) + ":0x" +
1825 Twine::utohexstr(Die->getSize()) + " " +
1826 dwarf::TagString(Abbrev->getTag()));
1827 Asm->EmitULEB128(AbbrevNumber);
1829 const SmallVector<DIEValue*, 32> &Values = Die->getValues();
1830 const SmallVector<DIEAbbrevData, 8> &AbbrevData = Abbrev->getData();
1832 // Emit the DIE attribute values.
1833 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1834 unsigned Attr = AbbrevData[i].getAttribute();
1835 unsigned Form = AbbrevData[i].getForm();
1836 assert(Form && "Too many attributes for DIE (check abbreviation)");
1838 if (Asm->isVerbose())
1839 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1842 case dwarf::DW_AT_abstract_origin: {
1843 DIEEntry *E = cast<DIEEntry>(Values[i]);
1844 DIE *Origin = E->getEntry();
1845 unsigned Addr = Origin->getOffset();
1846 Asm->EmitInt32(Addr);
1849 case dwarf::DW_AT_ranges: {
1850 // DW_AT_range Value encodes offset in debug_range section.
1851 DIEInteger *V = cast<DIEInteger>(Values[i]);
1853 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1854 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1858 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1860 DwarfDebugRangeSectionSym,
1865 case dwarf::DW_AT_location: {
1866 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1867 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1868 Asm->EmitLabelReference(L->getValue(), 4);
1870 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1872 Values[i]->EmitValue(Asm, Form);
1876 case dwarf::DW_AT_accessibility: {
1877 if (Asm->isVerbose()) {
1878 DIEInteger *V = cast<DIEInteger>(Values[i]);
1879 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1881 Values[i]->EmitValue(Asm, Form);
1885 // Emit an attribute using the defined form.
1886 Values[i]->EmitValue(Asm, Form);
1891 // Emit the DIE children if any.
1892 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1893 const std::vector<DIE *> &Children = Die->getChildren();
1895 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1896 emitDIE(Children[j], Abbrevs);
1898 if (Asm->isVerbose())
1899 Asm->OutStreamer.AddComment("End Of Children Mark");
1904 // Emit the various dwarf units to the unit section USection with
1905 // the abbreviations going into ASection.
1906 void DwarfUnits::emitUnits(DwarfDebug *DD,
1907 const MCSection *USection,
1908 const MCSection *ASection,
1909 const MCSymbol *ASectionSym) {
1910 Asm->OutStreamer.SwitchSection(USection);
1911 for (SmallVector<CompileUnit *, 1>::iterator I = CUs.begin(),
1912 E = CUs.end(); I != E; ++I) {
1913 CompileUnit *TheCU = *I;
1914 DIE *Die = TheCU->getCUDie();
1916 // Emit the compile units header.
1918 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1919 TheCU->getUniqueID()));
1921 // Emit size of content not including length itself
1922 unsigned ContentSize = Die->getSize() +
1923 sizeof(int16_t) + // DWARF version number
1924 sizeof(int32_t) + // Offset Into Abbrev. Section
1925 sizeof(int8_t); // Pointer Size (in bytes)
1927 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1928 Asm->EmitInt32(ContentSize);
1929 Asm->OutStreamer.AddComment("DWARF version number");
1930 Asm->EmitInt16(dwarf::DWARF_VERSION);
1931 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1932 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1934 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1935 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1937 DD->emitDIE(Die, Abbreviations);
1938 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1939 TheCU->getUniqueID()));
1943 // Emit the debug info section.
1944 void DwarfDebug::emitDebugInfo() {
1945 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1947 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1948 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1949 DwarfAbbrevSectionSym);
1952 // Emit the abbreviation section.
1953 void DwarfDebug::emitAbbreviations() {
1954 if (!useSplitDwarf())
1955 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1958 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1961 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1962 std::vector<DIEAbbrev *> *Abbrevs) {
1963 // Check to see if it is worth the effort.
1964 if (!Abbrevs->empty()) {
1965 // Start the debug abbrev section.
1966 Asm->OutStreamer.SwitchSection(Section);
1968 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1969 Asm->OutStreamer.EmitLabel(Begin);
1971 // For each abbrevation.
1972 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1973 // Get abbreviation data
1974 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1976 // Emit the abbrevations code (base 1 index.)
1977 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1979 // Emit the abbreviations data.
1983 // Mark end of abbreviations.
1984 Asm->EmitULEB128(0, "EOM(3)");
1986 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1987 Asm->OutStreamer.EmitLabel(End);
1991 // Emit the last address of the section and the end of the line matrix.
1992 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1993 // Define last address of section.
1994 Asm->OutStreamer.AddComment("Extended Op");
1997 Asm->OutStreamer.AddComment("Op size");
1998 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1999 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2000 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2002 Asm->OutStreamer.AddComment("Section end label");
2004 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2005 Asm->getDataLayout().getPointerSize());
2007 // Mark end of matrix.
2008 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2014 // Emit visible names into a hashed accelerator table section.
2015 void DwarfDebug::emitAccelNames() {
2016 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2017 dwarf::DW_FORM_data4));
2018 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2019 E = CUMap.end(); I != E; ++I) {
2020 CompileUnit *TheCU = I->second;
2021 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2022 for (StringMap<std::vector<DIE*> >::const_iterator
2023 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2024 const char *Name = GI->getKeyData();
2025 const std::vector<DIE *> &Entities = GI->second;
2026 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2027 DE = Entities.end(); DI != DE; ++DI)
2028 AT.AddName(Name, (*DI));
2032 AT.FinalizeTable(Asm, "Names");
2033 Asm->OutStreamer.SwitchSection(
2034 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2035 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2036 Asm->OutStreamer.EmitLabel(SectionBegin);
2038 // Emit the full data.
2039 AT.Emit(Asm, SectionBegin, &InfoHolder);
2042 // Emit objective C classes and categories into a hashed accelerator table
2044 void DwarfDebug::emitAccelObjC() {
2045 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2046 dwarf::DW_FORM_data4));
2047 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2048 E = CUMap.end(); I != E; ++I) {
2049 CompileUnit *TheCU = I->second;
2050 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2051 for (StringMap<std::vector<DIE*> >::const_iterator
2052 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2053 const char *Name = GI->getKeyData();
2054 const std::vector<DIE *> &Entities = GI->second;
2055 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2056 DE = Entities.end(); DI != DE; ++DI)
2057 AT.AddName(Name, (*DI));
2061 AT.FinalizeTable(Asm, "ObjC");
2062 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2063 .getDwarfAccelObjCSection());
2064 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2065 Asm->OutStreamer.EmitLabel(SectionBegin);
2067 // Emit the full data.
2068 AT.Emit(Asm, SectionBegin, &InfoHolder);
2071 // Emit namespace dies into a hashed accelerator table.
2072 void DwarfDebug::emitAccelNamespaces() {
2073 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2074 dwarf::DW_FORM_data4));
2075 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2076 E = CUMap.end(); I != E; ++I) {
2077 CompileUnit *TheCU = I->second;
2078 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2079 for (StringMap<std::vector<DIE*> >::const_iterator
2080 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2081 const char *Name = GI->getKeyData();
2082 const std::vector<DIE *> &Entities = GI->second;
2083 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2084 DE = Entities.end(); DI != DE; ++DI)
2085 AT.AddName(Name, (*DI));
2089 AT.FinalizeTable(Asm, "namespac");
2090 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2091 .getDwarfAccelNamespaceSection());
2092 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2093 Asm->OutStreamer.EmitLabel(SectionBegin);
2095 // Emit the full data.
2096 AT.Emit(Asm, SectionBegin, &InfoHolder);
2099 // Emit type dies into a hashed accelerator table.
2100 void DwarfDebug::emitAccelTypes() {
2101 std::vector<DwarfAccelTable::Atom> Atoms;
2102 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2103 dwarf::DW_FORM_data4));
2104 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2105 dwarf::DW_FORM_data2));
2106 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2107 dwarf::DW_FORM_data1));
2108 DwarfAccelTable AT(Atoms);
2109 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2110 E = CUMap.end(); I != E; ++I) {
2111 CompileUnit *TheCU = I->second;
2112 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2113 = TheCU->getAccelTypes();
2114 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2115 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2116 const char *Name = GI->getKeyData();
2117 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2118 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2119 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2120 AT.AddName(Name, (*DI).first, (*DI).second);
2124 AT.FinalizeTable(Asm, "types");
2125 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2126 .getDwarfAccelTypesSection());
2127 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2128 Asm->OutStreamer.EmitLabel(SectionBegin);
2130 // Emit the full data.
2131 AT.Emit(Asm, SectionBegin, &InfoHolder);
2134 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2136 void DwarfDebug::emitDebugPubnames() {
2137 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2139 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2140 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2141 CompileUnit *TheCU = I->second;
2142 unsigned ID = TheCU->getUniqueID();
2144 if (TheCU->getGlobalNames().empty())
2147 // Start the dwarf pubnames section.
2148 Asm->OutStreamer.SwitchSection(
2149 Asm->getObjFileLowering().getDwarfPubNamesSection());
2151 Asm->OutStreamer.AddComment("Length of Public Names Info");
2152 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2153 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2155 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2157 Asm->OutStreamer.AddComment("DWARF Version");
2158 Asm->EmitInt16(dwarf::DWARF_VERSION);
2160 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2161 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2162 DwarfInfoSectionSym);
2164 Asm->OutStreamer.AddComment("Compilation Unit Length");
2165 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2166 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2169 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2170 for (StringMap<DIE*>::const_iterator
2171 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2172 const char *Name = GI->getKeyData();
2173 const DIE *Entity = GI->second;
2175 Asm->OutStreamer.AddComment("DIE offset");
2176 Asm->EmitInt32(Entity->getOffset());
2178 if (Asm->isVerbose())
2179 Asm->OutStreamer.AddComment("External Name");
2180 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2183 Asm->OutStreamer.AddComment("End Mark");
2185 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2189 void DwarfDebug::emitDebugPubTypes() {
2190 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2191 E = CUMap.end(); I != E; ++I) {
2192 CompileUnit *TheCU = I->second;
2193 // Start the dwarf pubtypes section.
2194 Asm->OutStreamer.SwitchSection(
2195 Asm->getObjFileLowering().getDwarfPubTypesSection());
2196 Asm->OutStreamer.AddComment("Length of Public Types Info");
2197 Asm->EmitLabelDifference(
2198 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2199 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2201 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2202 TheCU->getUniqueID()));
2204 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2205 Asm->EmitInt16(dwarf::DWARF_VERSION);
2207 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2208 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2209 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2210 TheCU->getUniqueID()),
2211 DwarfInfoSectionSym);
2213 Asm->OutStreamer.AddComment("Compilation Unit Length");
2214 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2215 TheCU->getUniqueID()),
2216 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2217 TheCU->getUniqueID()),
2220 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2221 for (StringMap<DIE*>::const_iterator
2222 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2223 const char *Name = GI->getKeyData();
2224 DIE *Entity = GI->second;
2226 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2227 Asm->EmitInt32(Entity->getOffset());
2229 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2230 // Emit the name with a terminating null byte.
2231 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2234 Asm->OutStreamer.AddComment("End Mark");
2236 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2237 TheCU->getUniqueID()));
2241 // Emit strings into a string section.
2242 void DwarfUnits::emitStrings(const MCSection *StrSection,
2243 const MCSection *OffsetSection = NULL,
2244 const MCSymbol *StrSecSym = NULL) {
2246 if (StringPool.empty()) return;
2248 // Start the dwarf str section.
2249 Asm->OutStreamer.SwitchSection(StrSection);
2251 // Get all of the string pool entries and put them in an array by their ID so
2252 // we can sort them.
2253 SmallVector<std::pair<unsigned,
2254 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2256 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2257 I = StringPool.begin(), E = StringPool.end();
2259 Entries.push_back(std::make_pair(I->second.second, &*I));
2261 array_pod_sort(Entries.begin(), Entries.end());
2263 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2264 // Emit a label for reference from debug information entries.
2265 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2267 // Emit the string itself with a terminating null byte.
2268 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2269 Entries[i].second->getKeyLength()+1));
2272 // If we've got an offset section go ahead and emit that now as well.
2273 if (OffsetSection) {
2274 Asm->OutStreamer.SwitchSection(OffsetSection);
2275 unsigned offset = 0;
2276 unsigned size = 4; // FIXME: DWARF64 is 8.
2277 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2278 Asm->OutStreamer.EmitIntValue(offset, size);
2279 offset += Entries[i].second->getKeyLength() + 1;
2284 // Emit strings into a string section.
2285 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2287 if (AddressPool.empty()) return;
2289 // Start the dwarf addr section.
2290 Asm->OutStreamer.SwitchSection(AddrSection);
2292 // Get all of the string pool entries and put them in an array by their ID so
2293 // we can sort them.
2294 SmallVector<std::pair<unsigned,
2295 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2297 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2298 I = AddressPool.begin(), E = AddressPool.end();
2300 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2302 array_pod_sort(Entries.begin(), Entries.end());
2304 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2305 // Emit a label for reference from debug information entries.
2306 MCSymbol *Sym = Entries[i].second->first;
2308 Asm->EmitLabelReference(Entries[i].second->first,
2309 Asm->getDataLayout().getPointerSize());
2311 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2316 // Emit visible names into a debug str section.
2317 void DwarfDebug::emitDebugStr() {
2318 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2319 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2322 // Emit visible names into a debug loc section.
2323 void DwarfDebug::emitDebugLoc() {
2324 if (DotDebugLocEntries.empty())
2327 for (SmallVector<DotDebugLocEntry, 4>::iterator
2328 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2330 DotDebugLocEntry &Entry = *I;
2331 if (I + 1 != DotDebugLocEntries.end())
2335 // Start the dwarf loc section.
2336 Asm->OutStreamer.SwitchSection(
2337 Asm->getObjFileLowering().getDwarfLocSection());
2338 unsigned char Size = Asm->getDataLayout().getPointerSize();
2339 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2341 for (SmallVector<DotDebugLocEntry, 4>::iterator
2342 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2343 I != E; ++I, ++index) {
2344 DotDebugLocEntry &Entry = *I;
2345 if (Entry.isMerged()) continue;
2346 if (Entry.isEmpty()) {
2347 Asm->OutStreamer.EmitIntValue(0, Size);
2348 Asm->OutStreamer.EmitIntValue(0, Size);
2349 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2351 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2352 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2353 DIVariable DV(Entry.Variable);
2354 Asm->OutStreamer.AddComment("Loc expr size");
2355 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2356 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2357 Asm->EmitLabelDifference(end, begin, 2);
2358 Asm->OutStreamer.EmitLabel(begin);
2359 if (Entry.isInt()) {
2360 DIBasicType BTy(DV.getType());
2362 (BTy.getEncoding() == dwarf::DW_ATE_signed
2363 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2364 Asm->OutStreamer.AddComment("DW_OP_consts");
2365 Asm->EmitInt8(dwarf::DW_OP_consts);
2366 Asm->EmitSLEB128(Entry.getInt());
2368 Asm->OutStreamer.AddComment("DW_OP_constu");
2369 Asm->EmitInt8(dwarf::DW_OP_constu);
2370 Asm->EmitULEB128(Entry.getInt());
2372 } else if (Entry.isLocation()) {
2373 if (!DV.hasComplexAddress())
2375 Asm->EmitDwarfRegOp(Entry.Loc);
2377 // Complex address entry.
2378 unsigned N = DV.getNumAddrElements();
2380 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2381 if (Entry.Loc.getOffset()) {
2383 Asm->EmitDwarfRegOp(Entry.Loc);
2384 Asm->OutStreamer.AddComment("DW_OP_deref");
2385 Asm->EmitInt8(dwarf::DW_OP_deref);
2386 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2387 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2388 Asm->EmitSLEB128(DV.getAddrElement(1));
2390 // If first address element is OpPlus then emit
2391 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2392 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2393 Asm->EmitDwarfRegOp(Loc);
2397 Asm->EmitDwarfRegOp(Entry.Loc);
2400 // Emit remaining complex address elements.
2401 for (; i < N; ++i) {
2402 uint64_t Element = DV.getAddrElement(i);
2403 if (Element == DIBuilder::OpPlus) {
2404 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2405 Asm->EmitULEB128(DV.getAddrElement(++i));
2406 } else if (Element == DIBuilder::OpDeref) {
2407 if (!Entry.Loc.isReg())
2408 Asm->EmitInt8(dwarf::DW_OP_deref);
2410 llvm_unreachable("unknown Opcode found in complex address");
2414 // else ... ignore constant fp. There is not any good way to
2415 // to represent them here in dwarf.
2416 Asm->OutStreamer.EmitLabel(end);
2421 // Emit visible names into a debug aranges section.
2422 void DwarfDebug::emitDebugARanges() {
2423 // Start the dwarf aranges section.
2424 Asm->OutStreamer.SwitchSection(
2425 Asm->getObjFileLowering().getDwarfARangesSection());
2428 // Emit visible names into a debug ranges section.
2429 void DwarfDebug::emitDebugRanges() {
2430 // Start the dwarf ranges section.
2431 Asm->OutStreamer.SwitchSection(
2432 Asm->getObjFileLowering().getDwarfRangesSection());
2433 unsigned char Size = Asm->getDataLayout().getPointerSize();
2434 for (SmallVector<const MCSymbol *, 8>::iterator
2435 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2438 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2440 Asm->OutStreamer.EmitIntValue(0, Size);
2444 // Emit visible names into a debug macinfo section.
2445 void DwarfDebug::emitDebugMacInfo() {
2446 if (const MCSection *LineInfo =
2447 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2448 // Start the dwarf macinfo section.
2449 Asm->OutStreamer.SwitchSection(LineInfo);
2453 // Emit inline info using following format.
2455 // 1. length of section
2456 // 2. Dwarf version number
2459 // Entries (one "entry" for each function that was inlined):
2461 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2462 // otherwise offset into __debug_str for regular function name.
2463 // 2. offset into __debug_str section for regular function name.
2464 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2465 // instances for the function.
2467 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2468 // inlined instance; the die_offset points to the inlined_subroutine die in the
2469 // __debug_info section, and the low_pc is the starting address for the
2470 // inlining instance.
2471 void DwarfDebug::emitDebugInlineInfo() {
2472 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2478 Asm->OutStreamer.SwitchSection(
2479 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2481 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2482 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2483 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2485 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2487 Asm->OutStreamer.AddComment("Dwarf Version");
2488 Asm->EmitInt16(dwarf::DWARF_VERSION);
2489 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2490 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2492 for (SmallVector<const MDNode *, 4>::iterator I = InlinedSPNodes.begin(),
2493 E = InlinedSPNodes.end(); I != E; ++I) {
2495 const MDNode *Node = *I;
2496 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2497 = InlineInfo.find(Node);
2498 SmallVector<InlineInfoLabels, 4> &Labels = II->second;
2499 DISubprogram SP(Node);
2500 StringRef LName = SP.getLinkageName();
2501 StringRef Name = SP.getName();
2503 Asm->OutStreamer.AddComment("MIPS linkage name");
2505 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2506 DwarfStrSectionSym);
2508 Asm->EmitSectionOffset(InfoHolder
2509 .getStringPoolEntry(getRealLinkageName(LName)),
2510 DwarfStrSectionSym);
2512 Asm->OutStreamer.AddComment("Function name");
2513 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2514 DwarfStrSectionSym);
2515 Asm->EmitULEB128(Labels.size(), "Inline count");
2517 for (SmallVector<InlineInfoLabels, 4>::iterator LI = Labels.begin(),
2518 LE = Labels.end(); LI != LE; ++LI) {
2519 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2520 Asm->EmitInt32(LI->second->getOffset());
2522 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2523 Asm->OutStreamer.EmitSymbolValue(LI->first,
2524 Asm->getDataLayout().getPointerSize());
2528 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2531 // DWARF5 Experimental Separate Dwarf emitters.
2533 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2534 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2535 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2536 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2537 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2538 DICompileUnit DIUnit(N);
2539 CompilationDir = DIUnit.getDirectory();
2541 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2542 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2543 DIUnit.getLanguage(), Die, Asm,
2544 this, &SkeletonHolder);
2546 SmallString<16> T(DIUnit.getFilename());
2547 sys::path::replace_extension(T, ".dwo");
2548 StringRef FN = sys::path::filename(T);
2549 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name, FN);
2551 // This should be a unique identifier when we want to build .dwp files.
2552 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2554 // FIXME: The addr base should be relative for each compile unit, however,
2555 // this one is going to be 0 anyhow.
2556 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset, 0);
2558 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2559 // into an entity. We're using 0, or a NULL label for this.
2560 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2562 // DW_AT_stmt_list is a offset of line number information for this
2563 // compile unit in debug_line section.
2564 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2565 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2566 DwarfLineSectionSym);
2568 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2570 if (!CompilationDir.empty())
2571 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2573 SkeletonHolder.addUnit(NewCU);
2574 SkeletonCUs.push_back(NewCU);
2579 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2580 assert(useSplitDwarf() && "No split dwarf debug info?");
2581 emitAbbrevs(Section, &SkeletonAbbrevs);
2584 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2585 // compile units that would normally be in debug_info.
2586 void DwarfDebug::emitDebugInfoDWO() {
2587 assert(useSplitDwarf() && "No split dwarf debug info?");
2588 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2589 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2590 DwarfAbbrevDWOSectionSym);
2593 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2594 // abbreviations for the .debug_info.dwo section.
2595 void DwarfDebug::emitDebugAbbrevDWO() {
2596 assert(useSplitDwarf() && "No split dwarf?");
2597 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2601 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2602 // string section and is identical in format to traditional .debug_str
2604 void DwarfDebug::emitDebugStrDWO() {
2605 assert(useSplitDwarf() && "No split dwarf?");
2606 const MCSection *OffSec = Asm->getObjFileLowering()
2607 .getDwarfStrOffDWOSection();
2608 const MCSymbol *StrSym = DwarfStrSectionSym;
2609 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),