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 void DwarfDebug::constructImportedModuleDIE(CompileUnit *TheCU,
768 DIImportedModule Module(N);
769 if (!Module.Verify())
771 DIE *IMDie = new DIE(dwarf::DW_TAG_imported_module);
772 TheCU->insertDIE(Module, IMDie);
773 DIE *NSDie = TheCU->getOrCreateNameSpace(Module.getNameSpace());
774 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
775 Module.getContext().getDirectory(),
776 TheCU->getUniqueID());
777 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
778 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
779 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4, NSDie);
780 TheCU->addToContextOwner(IMDie, Module.getContext());
783 // Emit all Dwarf sections that should come prior to the content. Create
784 // global DIEs and emit initial debug info sections. This is invoked by
785 // the target AsmPrinter.
786 void DwarfDebug::beginModule() {
787 if (DisableDebugInfoPrinting)
790 const Module *M = MMI->getModule();
792 // If module has named metadata anchors then use them, otherwise scan the
793 // module using debug info finder to collect debug info.
794 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
798 // Emit initial sections so we can reference labels later.
801 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
802 DICompileUnit CUNode(CU_Nodes->getOperand(i));
803 CompileUnit *CU = constructCompileUnit(CUNode);
804 DIArray GVs = CUNode.getGlobalVariables();
805 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
806 CU->createGlobalVariableDIE(GVs.getElement(i));
807 DIArray SPs = CUNode.getSubprograms();
808 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
809 constructSubprogramDIE(CU, SPs.getElement(i));
810 DIArray EnumTypes = CUNode.getEnumTypes();
811 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
812 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
813 DIArray RetainedTypes = CUNode.getRetainedTypes();
814 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
815 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
816 // Emit imported_modules last so that the relevant context is already
818 DIArray ImportedModules = CUNode.getImportedModules();
819 for (unsigned i = 0, e = ImportedModules.getNumElements(); i != e; ++i)
820 constructImportedModuleDIE(CU, ImportedModules.getElement(i));
821 // If we're splitting the dwarf out now that we've got the entire
822 // CU then construct a skeleton CU based upon it.
823 if (useSplitDwarf()) {
824 // This should be a unique identifier when we want to build .dwp files.
825 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
826 dwarf::DW_FORM_data8, 0);
827 // Now construct the skeleton CU associated.
828 constructSkeletonCU(CUNode);
832 // Tell MMI that we have debug info.
833 MMI->setDebugInfoAvailability(true);
835 // Prime section data.
836 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
839 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
840 void DwarfDebug::computeInlinedDIEs() {
841 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
842 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
843 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
845 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
847 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
848 AE = AbstractSPDies.end(); AI != AE; ++AI) {
849 DIE *ISP = AI->second;
850 if (InlinedSubprogramDIEs.count(ISP))
852 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
856 // Collect info for variables that were optimized out.
857 void DwarfDebug::collectDeadVariables() {
858 const Module *M = MMI->getModule();
859 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
861 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
862 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
863 DICompileUnit TheCU(CU_Nodes->getOperand(i));
864 DIArray Subprograms = TheCU.getSubprograms();
865 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
866 DISubprogram SP(Subprograms.getElement(i));
867 if (ProcessedSPNodes.count(SP) != 0) continue;
868 if (!SP.Verify()) continue;
869 if (!SP.isDefinition()) continue;
870 DIArray Variables = SP.getVariables();
871 if (Variables.getNumElements() == 0) continue;
873 LexicalScope *Scope =
874 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
875 DeadFnScopeMap[SP] = Scope;
877 // Construct subprogram DIE and add variables DIEs.
878 CompileUnit *SPCU = CUMap.lookup(TheCU);
879 assert(SPCU && "Unable to find Compile Unit!");
880 constructSubprogramDIE(SPCU, SP);
881 DIE *ScopeDIE = SPCU->getDIE(SP);
882 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
883 DIVariable DV(Variables.getElement(vi));
884 if (!DV.Verify()) continue;
885 DbgVariable *NewVar = new DbgVariable(DV, NULL);
886 if (DIE *VariableDIE =
887 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
888 ScopeDIE->addChild(VariableDIE);
893 DeleteContainerSeconds(DeadFnScopeMap);
896 void DwarfDebug::finalizeModuleInfo() {
897 // Collect info for variables that were optimized out.
898 collectDeadVariables();
900 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
901 computeInlinedDIEs();
903 // Emit DW_AT_containing_type attribute to connect types with their
904 // vtable holding type.
905 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
906 CUE = CUMap.end(); CUI != CUE; ++CUI) {
907 CompileUnit *TheCU = CUI->second;
908 TheCU->constructContainingTypeDIEs();
911 // Compute DIE offsets and sizes.
912 InfoHolder.computeSizeAndOffsets();
914 SkeletonHolder.computeSizeAndOffsets();
917 void DwarfDebug::endSections() {
918 // Standard sections final addresses.
919 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
920 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
921 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
922 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
924 // End text sections.
925 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
926 Asm->OutStreamer.SwitchSection(SectionMap[I]);
927 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
931 // Emit all Dwarf sections that should come after the content.
932 void DwarfDebug::endModule() {
934 if (!FirstCU) return;
936 // End any existing sections.
937 // TODO: Does this need to happen?
940 // Finalize the debug info for the module.
941 finalizeModuleInfo();
943 if (!useSplitDwarf()) {
944 // Emit all the DIEs into a debug info section.
947 // Corresponding abbreviations into a abbrev section.
950 // Emit info into a debug loc section.
953 // Emit info into a debug aranges section.
956 // Emit info into a debug ranges section.
959 // Emit info into a debug macinfo section.
963 // TODO: When we don't need the option anymore we
964 // can remove all of the code that this section
966 if (useDarwinGDBCompat())
967 emitDebugInlineInfo();
969 // TODO: Fill this in for separated debug sections and separate
970 // out information into new sections.
972 // Emit the debug info section and compile units.
976 // Corresponding abbreviations into a abbrev section.
978 emitDebugAbbrevDWO();
980 // Emit info into a debug loc section.
983 // Emit info into a debug aranges section.
986 // Emit info into a debug ranges section.
989 // Emit info into a debug macinfo section.
992 // Emit DWO addresses.
993 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
996 // TODO: When we don't need the option anymore we
997 // can remove all of the code that this section
999 if (useDarwinGDBCompat())
1000 emitDebugInlineInfo();
1003 // Emit info into the dwarf accelerator table sections.
1004 if (useDwarfAccelTables()) {
1007 emitAccelNamespaces();
1011 // Emit info into a debug pubnames section, if requested.
1012 if (GenerateDwarfPubNamesSection)
1013 emitDebugPubnames();
1015 // Emit info into a debug pubtypes section.
1016 // TODO: When we don't need the option anymore we can
1017 // remove all of the code that adds to the table.
1018 if (useDarwinGDBCompat())
1019 emitDebugPubTypes();
1021 // Finally emit string information into a string table.
1023 if (useSplitDwarf())
1028 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1029 E = CUMap.end(); I != E; ++I)
1032 for (SmallVector<CompileUnit *, 1>::iterator I = SkeletonCUs.begin(),
1033 E = SkeletonCUs.end(); I != E; ++I)
1036 // Reset these for the next Module if we have one.
1040 // Find abstract variable, if any, associated with Var.
1041 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1042 DebugLoc ScopeLoc) {
1043 LLVMContext &Ctx = DV->getContext();
1044 // More then one inlined variable corresponds to one abstract variable.
1045 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1046 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1048 return AbsDbgVariable;
1050 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1054 AbsDbgVariable = new DbgVariable(Var, NULL);
1055 addScopeVariable(Scope, AbsDbgVariable);
1056 AbstractVariables[Var] = AbsDbgVariable;
1057 return AbsDbgVariable;
1060 // If Var is a current function argument then add it to CurrentFnArguments list.
1061 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1062 DbgVariable *Var, LexicalScope *Scope) {
1063 if (!LScopes.isCurrentFunctionScope(Scope))
1065 DIVariable DV = Var->getVariable();
1066 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1068 unsigned ArgNo = DV.getArgNumber();
1072 size_t Size = CurrentFnArguments.size();
1074 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1075 // llvm::Function argument size is not good indicator of how many
1076 // arguments does the function have at source level.
1078 CurrentFnArguments.resize(ArgNo * 2);
1079 CurrentFnArguments[ArgNo - 1] = Var;
1083 // Collect variable information from side table maintained by MMI.
1085 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1086 SmallPtrSet<const MDNode *, 16> &Processed) {
1087 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1088 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1089 VE = VMap.end(); VI != VE; ++VI) {
1090 const MDNode *Var = VI->first;
1092 Processed.insert(Var);
1094 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1096 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1098 // If variable scope is not found then skip this variable.
1102 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1103 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1104 RegVar->setFrameIndex(VP.first);
1105 if (!addCurrentFnArgument(MF, RegVar, Scope))
1106 addScopeVariable(Scope, RegVar);
1108 AbsDbgVariable->setFrameIndex(VP.first);
1112 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1114 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1115 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1116 return MI->getNumOperands() == 3 &&
1117 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1118 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1121 // Get .debug_loc entry for the instruction range starting at MI.
1122 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1123 const MCSymbol *FLabel,
1124 const MCSymbol *SLabel,
1125 const MachineInstr *MI) {
1126 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1128 if (MI->getNumOperands() != 3) {
1129 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1130 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1132 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1133 MachineLocation MLoc;
1134 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1135 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1137 if (MI->getOperand(0).isImm())
1138 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1139 if (MI->getOperand(0).isFPImm())
1140 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1141 if (MI->getOperand(0).isCImm())
1142 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1144 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1147 // Find variables for each lexical scope.
1149 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1150 SmallPtrSet<const MDNode *, 16> &Processed) {
1152 // collection info from MMI table.
1153 collectVariableInfoFromMMITable(MF, Processed);
1155 for (SmallVectorImpl<const MDNode*>::const_iterator
1156 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1158 const MDNode *Var = *UVI;
1159 if (Processed.count(Var))
1162 // History contains relevant DBG_VALUE instructions for Var and instructions
1164 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1165 if (History.empty())
1167 const MachineInstr *MInsn = History.front();
1170 LexicalScope *Scope = NULL;
1171 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1172 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1173 Scope = LScopes.getCurrentFunctionScope();
1174 else if (MDNode *IA = DV.getInlinedAt())
1175 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1177 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1178 // If variable scope is not found then skip this variable.
1182 Processed.insert(DV);
1183 assert(MInsn->isDebugValue() && "History must begin with debug value");
1184 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1185 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1186 if (!addCurrentFnArgument(MF, RegVar, Scope))
1187 addScopeVariable(Scope, RegVar);
1189 AbsVar->setMInsn(MInsn);
1191 // Simplify ranges that are fully coalesced.
1192 if (History.size() <= 1 || (History.size() == 2 &&
1193 MInsn->isIdenticalTo(History.back()))) {
1194 RegVar->setMInsn(MInsn);
1198 // Handle multiple DBG_VALUE instructions describing one variable.
1199 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1201 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1202 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1203 const MachineInstr *Begin = *HI;
1204 assert(Begin->isDebugValue() && "Invalid History entry");
1206 // Check if DBG_VALUE is truncating a range.
1207 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1208 && !Begin->getOperand(0).getReg())
1211 // Compute the range for a register location.
1212 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1213 const MCSymbol *SLabel = 0;
1216 // If Begin is the last instruction in History then its value is valid
1217 // until the end of the function.
1218 SLabel = FunctionEndSym;
1220 const MachineInstr *End = HI[1];
1221 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1222 << "\t" << *Begin << "\t" << *End << "\n");
1223 if (End->isDebugValue())
1224 SLabel = getLabelBeforeInsn(End);
1226 // End is a normal instruction clobbering the range.
1227 SLabel = getLabelAfterInsn(End);
1228 assert(SLabel && "Forgot label after clobber instruction");
1233 // The value is valid until the next DBG_VALUE or clobber.
1234 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1237 DotDebugLocEntries.push_back(DotDebugLocEntry());
1240 // Collect info for variables that were optimized out.
1241 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1242 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1243 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1244 DIVariable DV(Variables.getElement(i));
1245 if (!DV || !DV.Verify() || !Processed.insert(DV))
1247 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1248 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1252 // Return Label preceding the instruction.
1253 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1254 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1255 assert(Label && "Didn't insert label before instruction");
1259 // Return Label immediately following the instruction.
1260 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1261 return LabelsAfterInsn.lookup(MI);
1264 // Process beginning of an instruction.
1265 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1266 // Check if source location changes, but ignore DBG_VALUE locations.
1267 if (!MI->isDebugValue()) {
1268 DebugLoc DL = MI->getDebugLoc();
1269 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1272 if (DL == PrologEndLoc) {
1273 Flags |= DWARF2_FLAG_PROLOGUE_END;
1274 PrologEndLoc = DebugLoc();
1276 if (PrologEndLoc.isUnknown())
1277 Flags |= DWARF2_FLAG_IS_STMT;
1279 if (!DL.isUnknown()) {
1280 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1281 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1283 recordSourceLine(0, 0, 0, 0);
1287 // Insert labels where requested.
1288 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1289 LabelsBeforeInsn.find(MI);
1292 if (I == LabelsBeforeInsn.end())
1295 // Label already assigned.
1300 PrevLabel = MMI->getContext().CreateTempSymbol();
1301 Asm->OutStreamer.EmitLabel(PrevLabel);
1303 I->second = PrevLabel;
1306 // Process end of an instruction.
1307 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1308 // Don't create a new label after DBG_VALUE instructions.
1309 // They don't generate code.
1310 if (!MI->isDebugValue())
1313 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1314 LabelsAfterInsn.find(MI);
1317 if (I == LabelsAfterInsn.end())
1320 // Label already assigned.
1324 // We need a label after this instruction.
1326 PrevLabel = MMI->getContext().CreateTempSymbol();
1327 Asm->OutStreamer.EmitLabel(PrevLabel);
1329 I->second = PrevLabel;
1332 // Each LexicalScope has first instruction and last instruction to mark
1333 // beginning and end of a scope respectively. Create an inverse map that list
1334 // scopes starts (and ends) with an instruction. One instruction may start (or
1335 // end) multiple scopes. Ignore scopes that are not reachable.
1336 void DwarfDebug::identifyScopeMarkers() {
1337 SmallVector<LexicalScope *, 4> WorkList;
1338 WorkList.push_back(LScopes.getCurrentFunctionScope());
1339 while (!WorkList.empty()) {
1340 LexicalScope *S = WorkList.pop_back_val();
1342 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1343 if (!Children.empty())
1344 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1345 SE = Children.end(); SI != SE; ++SI)
1346 WorkList.push_back(*SI);
1348 if (S->isAbstractScope())
1351 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1354 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1355 RE = Ranges.end(); RI != RE; ++RI) {
1356 assert(RI->first && "InsnRange does not have first instruction!");
1357 assert(RI->second && "InsnRange does not have second instruction!");
1358 requestLabelBeforeInsn(RI->first);
1359 requestLabelAfterInsn(RI->second);
1364 // Get MDNode for DebugLoc's scope.
1365 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1366 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1367 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1368 return DL.getScope(Ctx);
1371 // Walk up the scope chain of given debug loc and find line number info
1372 // for the function.
1373 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1374 const MDNode *Scope = getScopeNode(DL, Ctx);
1375 DISubprogram SP = getDISubprogram(Scope);
1377 // Check for number of operands since the compatibility is
1379 if (SP->getNumOperands() > 19)
1380 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1382 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1388 // Gather pre-function debug information. Assumes being called immediately
1389 // after the function entry point has been emitted.
1390 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1391 if (!MMI->hasDebugInfo()) return;
1392 LScopes.initialize(*MF);
1393 if (LScopes.empty()) return;
1394 identifyScopeMarkers();
1396 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1398 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1399 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1400 assert(TheCU && "Unable to find compile unit!");
1401 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1403 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1404 Asm->getFunctionNumber());
1405 // Assumes in correct section after the entry point.
1406 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1408 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1410 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1411 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1412 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1414 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1416 bool AtBlockEntry = true;
1417 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1419 const MachineInstr *MI = II;
1421 if (MI->isDebugValue()) {
1422 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1424 // Keep track of user variables.
1426 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1428 // Variable is in a register, we need to check for clobbers.
1429 if (isDbgValueInDefinedReg(MI))
1430 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1432 // Check the history of this variable.
1433 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1434 if (History.empty()) {
1435 UserVariables.push_back(Var);
1436 // The first mention of a function argument gets the FunctionBeginSym
1437 // label, so arguments are visible when breaking at function entry.
1439 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1440 DISubprogram(getDISubprogram(DV.getContext()))
1441 .describes(MF->getFunction()))
1442 LabelsBeforeInsn[MI] = FunctionBeginSym;
1444 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1445 const MachineInstr *Prev = History.back();
1446 if (Prev->isDebugValue()) {
1447 // Coalesce identical entries at the end of History.
1448 if (History.size() >= 2 &&
1449 Prev->isIdenticalTo(History[History.size() - 2])) {
1450 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1452 << "\t" << *History[History.size() - 2] << "\n");
1456 // Terminate old register assignments that don't reach MI;
1457 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1458 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1459 isDbgValueInDefinedReg(Prev)) {
1460 // Previous register assignment needs to terminate at the end of
1462 MachineBasicBlock::const_iterator LastMI =
1463 PrevMBB->getLastNonDebugInstr();
1464 if (LastMI == PrevMBB->end()) {
1465 // Drop DBG_VALUE for empty range.
1466 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1467 << "\t" << *Prev << "\n");
1471 // Terminate after LastMI.
1472 History.push_back(LastMI);
1477 History.push_back(MI);
1479 // Not a DBG_VALUE instruction.
1481 AtBlockEntry = false;
1483 // First known non-DBG_VALUE and non-frame setup location marks
1484 // the beginning of the function body.
1485 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1486 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1487 PrologEndLoc = MI->getDebugLoc();
1489 // Check if the instruction clobbers any registers with debug vars.
1490 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1491 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1492 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1494 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1495 AI.isValid(); ++AI) {
1497 const MDNode *Var = LiveUserVar[Reg];
1500 // Reg is now clobbered.
1501 LiveUserVar[Reg] = 0;
1503 // Was MD last defined by a DBG_VALUE referring to Reg?
1504 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1505 if (HistI == DbgValues.end())
1507 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1508 if (History.empty())
1510 const MachineInstr *Prev = History.back();
1511 // Sanity-check: Register assignments are terminated at the end of
1513 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1515 // Is the variable still in Reg?
1516 if (!isDbgValueInDefinedReg(Prev) ||
1517 Prev->getOperand(0).getReg() != Reg)
1519 // Var is clobbered. Make sure the next instruction gets a label.
1520 History.push_back(MI);
1527 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1529 SmallVectorImpl<const MachineInstr*> &History = I->second;
1530 if (History.empty())
1533 // Make sure the final register assignments are terminated.
1534 const MachineInstr *Prev = History.back();
1535 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1536 const MachineBasicBlock *PrevMBB = Prev->getParent();
1537 MachineBasicBlock::const_iterator LastMI =
1538 PrevMBB->getLastNonDebugInstr();
1539 if (LastMI == PrevMBB->end())
1540 // Drop DBG_VALUE for empty range.
1543 // Terminate after LastMI.
1544 History.push_back(LastMI);
1547 // Request labels for the full history.
1548 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1549 const MachineInstr *MI = History[i];
1550 if (MI->isDebugValue())
1551 requestLabelBeforeInsn(MI);
1553 requestLabelAfterInsn(MI);
1557 PrevInstLoc = DebugLoc();
1558 PrevLabel = FunctionBeginSym;
1560 // Record beginning of function.
1561 if (!PrologEndLoc.isUnknown()) {
1562 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1563 MF->getFunction()->getContext());
1564 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1565 FnStartDL.getScope(MF->getFunction()->getContext()),
1566 // We'd like to list the prologue as "not statements" but GDB behaves
1567 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1568 DWARF2_FLAG_IS_STMT);
1572 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1573 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1574 ScopeVariables[LS].push_back(Var);
1575 // Vars.push_back(Var);
1578 // Gather and emit post-function debug information.
1579 void DwarfDebug::endFunction(const MachineFunction *MF) {
1580 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1582 // Define end label for subprogram.
1583 FunctionEndSym = Asm->GetTempSymbol("func_end",
1584 Asm->getFunctionNumber());
1585 // Assumes in correct section after the entry point.
1586 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1587 // Set DwarfCompileUnitID in MCContext to default value.
1588 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1590 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1591 collectVariableInfo(MF, ProcessedVars);
1593 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1594 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1595 assert(TheCU && "Unable to find compile unit!");
1597 // Construct abstract scopes.
1598 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1599 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1600 LexicalScope *AScope = AList[i];
1601 DISubprogram SP(AScope->getScopeNode());
1603 // Collect info for variables that were optimized out.
1604 DIArray Variables = SP.getVariables();
1605 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1606 DIVariable DV(Variables.getElement(i));
1607 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1609 // Check that DbgVariable for DV wasn't created earlier, when
1610 // findAbstractVariable() was called for inlined instance of DV.
1611 LLVMContext &Ctx = DV->getContext();
1612 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1613 if (AbstractVariables.lookup(CleanDV))
1615 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1616 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1619 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1620 constructScopeDIE(TheCU, AScope);
1623 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1625 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1626 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1628 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1629 MMI->getFrameMoves()));
1632 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1633 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1634 DeleteContainerPointers(I->second);
1635 ScopeVariables.clear();
1636 DeleteContainerPointers(CurrentFnArguments);
1637 UserVariables.clear();
1639 AbstractVariables.clear();
1640 LabelsBeforeInsn.clear();
1641 LabelsAfterInsn.clear();
1645 // Register a source line with debug info. Returns the unique label that was
1646 // emitted and which provides correspondence to the source line list.
1647 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1653 DIDescriptor Scope(S);
1655 if (Scope.isCompileUnit()) {
1656 DICompileUnit CU(S);
1657 Fn = CU.getFilename();
1658 Dir = CU.getDirectory();
1659 } else if (Scope.isFile()) {
1661 Fn = F.getFilename();
1662 Dir = F.getDirectory();
1663 } else if (Scope.isSubprogram()) {
1665 Fn = SP.getFilename();
1666 Dir = SP.getDirectory();
1667 } else if (Scope.isLexicalBlockFile()) {
1668 DILexicalBlockFile DBF(S);
1669 Fn = DBF.getFilename();
1670 Dir = DBF.getDirectory();
1671 } else if (Scope.isLexicalBlock()) {
1672 DILexicalBlock DB(S);
1673 Fn = DB.getFilename();
1674 Dir = DB.getDirectory();
1676 llvm_unreachable("Unexpected scope info");
1678 Src = getOrCreateSourceID(Fn, Dir,
1679 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1681 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1684 //===----------------------------------------------------------------------===//
1686 //===----------------------------------------------------------------------===//
1688 // Compute the size and offset of a DIE.
1690 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1691 // Get the children.
1692 const std::vector<DIE *> &Children = Die->getChildren();
1694 // Record the abbreviation.
1695 assignAbbrevNumber(Die->getAbbrev());
1697 // Get the abbreviation for this DIE.
1698 unsigned AbbrevNumber = Die->getAbbrevNumber();
1699 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1702 Die->setOffset(Offset);
1704 // Start the size with the size of abbreviation code.
1705 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1707 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1708 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1710 // Size the DIE attribute values.
1711 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1712 // Size attribute value.
1713 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1715 // Size the DIE children if any.
1716 if (!Children.empty()) {
1717 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1718 "Children flag not set");
1720 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1721 Offset = computeSizeAndOffset(Children[j], Offset);
1723 // End of children marker.
1724 Offset += sizeof(int8_t);
1727 Die->setSize(Offset - Die->getOffset());
1731 // Compute the size and offset of all the DIEs.
1732 void DwarfUnits::computeSizeAndOffsets() {
1733 // Offset from the beginning of debug info section.
1734 unsigned AccuOffset = 0;
1735 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1736 E = CUs.end(); I != E; ++I) {
1737 (*I)->setDebugInfoOffset(AccuOffset);
1739 sizeof(int32_t) + // Length of Compilation Unit Info
1740 sizeof(int16_t) + // DWARF version number
1741 sizeof(int32_t) + // Offset Into Abbrev. Section
1742 sizeof(int8_t); // Pointer Size (in bytes)
1744 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1745 AccuOffset += EndOffset;
1749 // Emit initial Dwarf sections with a label at the start of each one.
1750 void DwarfDebug::emitSectionLabels() {
1751 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1753 // Dwarf sections base addresses.
1754 DwarfInfoSectionSym =
1755 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1756 DwarfAbbrevSectionSym =
1757 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1758 if (useSplitDwarf())
1759 DwarfAbbrevDWOSectionSym =
1760 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1761 "section_abbrev_dwo");
1762 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1764 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1765 emitSectionSym(Asm, MacroInfo);
1767 DwarfLineSectionSym =
1768 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1769 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1770 if (GenerateDwarfPubNamesSection)
1771 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1772 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1773 DwarfStrSectionSym =
1774 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1775 if (useSplitDwarf()) {
1776 DwarfStrDWOSectionSym =
1777 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1778 DwarfAddrSectionSym =
1779 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1781 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1784 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1785 "section_debug_loc");
1787 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1788 emitSectionSym(Asm, TLOF.getDataSection());
1791 // Recursively emits a debug information entry.
1792 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1793 // Get the abbreviation for this DIE.
1794 unsigned AbbrevNumber = Die->getAbbrevNumber();
1795 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1797 // Emit the code (index) for the abbreviation.
1798 if (Asm->isVerbose())
1799 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1800 Twine::utohexstr(Die->getOffset()) + ":0x" +
1801 Twine::utohexstr(Die->getSize()) + " " +
1802 dwarf::TagString(Abbrev->getTag()));
1803 Asm->EmitULEB128(AbbrevNumber);
1805 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1806 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1808 // Emit the DIE attribute values.
1809 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1810 unsigned Attr = AbbrevData[i].getAttribute();
1811 unsigned Form = AbbrevData[i].getForm();
1812 assert(Form && "Too many attributes for DIE (check abbreviation)");
1814 if (Asm->isVerbose())
1815 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1818 case dwarf::DW_AT_abstract_origin: {
1819 DIEEntry *E = cast<DIEEntry>(Values[i]);
1820 DIE *Origin = E->getEntry();
1821 unsigned Addr = Origin->getOffset();
1822 if (Form == dwarf::DW_FORM_ref_addr) {
1823 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1824 // section. Origin->getOffset() returns the offset from start of the
1826 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1827 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1829 Asm->EmitInt32(Addr);
1832 case dwarf::DW_AT_ranges: {
1833 // DW_AT_range Value encodes offset in debug_range section.
1834 DIEInteger *V = cast<DIEInteger>(Values[i]);
1836 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1837 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1841 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1843 DwarfDebugRangeSectionSym,
1848 case dwarf::DW_AT_location: {
1849 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1850 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1851 Asm->EmitLabelReference(L->getValue(), 4);
1853 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1855 Values[i]->EmitValue(Asm, Form);
1859 case dwarf::DW_AT_accessibility: {
1860 if (Asm->isVerbose()) {
1861 DIEInteger *V = cast<DIEInteger>(Values[i]);
1862 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1864 Values[i]->EmitValue(Asm, Form);
1868 // Emit an attribute using the defined form.
1869 Values[i]->EmitValue(Asm, Form);
1874 // Emit the DIE children if any.
1875 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1876 const std::vector<DIE *> &Children = Die->getChildren();
1878 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1879 emitDIE(Children[j], Abbrevs);
1881 if (Asm->isVerbose())
1882 Asm->OutStreamer.AddComment("End Of Children Mark");
1887 // Emit the various dwarf units to the unit section USection with
1888 // the abbreviations going into ASection.
1889 void DwarfUnits::emitUnits(DwarfDebug *DD,
1890 const MCSection *USection,
1891 const MCSection *ASection,
1892 const MCSymbol *ASectionSym) {
1893 Asm->OutStreamer.SwitchSection(USection);
1894 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1895 E = CUs.end(); I != E; ++I) {
1896 CompileUnit *TheCU = *I;
1897 DIE *Die = TheCU->getCUDie();
1899 // Emit the compile units header.
1901 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1902 TheCU->getUniqueID()));
1904 // Emit size of content not including length itself
1905 unsigned ContentSize = Die->getSize() +
1906 sizeof(int16_t) + // DWARF version number
1907 sizeof(int32_t) + // Offset Into Abbrev. Section
1908 sizeof(int8_t); // Pointer Size (in bytes)
1910 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1911 Asm->EmitInt32(ContentSize);
1912 Asm->OutStreamer.AddComment("DWARF version number");
1913 Asm->EmitInt16(dwarf::DWARF_VERSION);
1914 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1915 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1917 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1918 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1920 DD->emitDIE(Die, Abbreviations);
1921 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1922 TheCU->getUniqueID()));
1926 /// For a given compile unit DIE, returns offset from beginning of debug info.
1927 unsigned DwarfUnits::getCUOffset(DIE *Die) {
1928 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
1929 "Input DIE should be compile unit in getCUOffset.");
1930 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1931 E = CUs.end(); I != E; ++I) {
1932 CompileUnit *TheCU = *I;
1933 if (TheCU->getCUDie() == Die)
1934 return TheCU->getDebugInfoOffset();
1936 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
1939 // Emit the debug info section.
1940 void DwarfDebug::emitDebugInfo() {
1941 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1943 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1944 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1945 DwarfAbbrevSectionSym);
1948 // Emit the abbreviation section.
1949 void DwarfDebug::emitAbbreviations() {
1950 if (!useSplitDwarf())
1951 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
1954 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1957 void DwarfDebug::emitAbbrevs(const MCSection *Section,
1958 std::vector<DIEAbbrev *> *Abbrevs) {
1959 // Check to see if it is worth the effort.
1960 if (!Abbrevs->empty()) {
1961 // Start the debug abbrev section.
1962 Asm->OutStreamer.SwitchSection(Section);
1964 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
1965 Asm->OutStreamer.EmitLabel(Begin);
1967 // For each abbrevation.
1968 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
1969 // Get abbreviation data
1970 const DIEAbbrev *Abbrev = Abbrevs->at(i);
1972 // Emit the abbrevations code (base 1 index.)
1973 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1975 // Emit the abbreviations data.
1979 // Mark end of abbreviations.
1980 Asm->EmitULEB128(0, "EOM(3)");
1982 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
1983 Asm->OutStreamer.EmitLabel(End);
1987 // Emit the last address of the section and the end of the line matrix.
1988 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1989 // Define last address of section.
1990 Asm->OutStreamer.AddComment("Extended Op");
1993 Asm->OutStreamer.AddComment("Op size");
1994 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1995 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1996 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1998 Asm->OutStreamer.AddComment("Section end label");
2000 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2001 Asm->getDataLayout().getPointerSize());
2003 // Mark end of matrix.
2004 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2010 // Emit visible names into a hashed accelerator table section.
2011 void DwarfDebug::emitAccelNames() {
2012 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2013 dwarf::DW_FORM_data4));
2014 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2015 E = CUMap.end(); I != E; ++I) {
2016 CompileUnit *TheCU = I->second;
2017 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2018 for (StringMap<std::vector<DIE*> >::const_iterator
2019 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2020 const char *Name = GI->getKeyData();
2021 const std::vector<DIE *> &Entities = GI->second;
2022 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2023 DE = Entities.end(); DI != DE; ++DI)
2024 AT.AddName(Name, (*DI));
2028 AT.FinalizeTable(Asm, "Names");
2029 Asm->OutStreamer.SwitchSection(
2030 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2031 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2032 Asm->OutStreamer.EmitLabel(SectionBegin);
2034 // Emit the full data.
2035 AT.Emit(Asm, SectionBegin, &InfoHolder);
2038 // Emit objective C classes and categories into a hashed accelerator table
2040 void DwarfDebug::emitAccelObjC() {
2041 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2042 dwarf::DW_FORM_data4));
2043 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2044 E = CUMap.end(); I != E; ++I) {
2045 CompileUnit *TheCU = I->second;
2046 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2047 for (StringMap<std::vector<DIE*> >::const_iterator
2048 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2049 const char *Name = GI->getKeyData();
2050 const std::vector<DIE *> &Entities = GI->second;
2051 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2052 DE = Entities.end(); DI != DE; ++DI)
2053 AT.AddName(Name, (*DI));
2057 AT.FinalizeTable(Asm, "ObjC");
2058 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2059 .getDwarfAccelObjCSection());
2060 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2061 Asm->OutStreamer.EmitLabel(SectionBegin);
2063 // Emit the full data.
2064 AT.Emit(Asm, SectionBegin, &InfoHolder);
2067 // Emit namespace dies into a hashed accelerator table.
2068 void DwarfDebug::emitAccelNamespaces() {
2069 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2070 dwarf::DW_FORM_data4));
2071 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2072 E = CUMap.end(); I != E; ++I) {
2073 CompileUnit *TheCU = I->second;
2074 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2075 for (StringMap<std::vector<DIE*> >::const_iterator
2076 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2077 const char *Name = GI->getKeyData();
2078 const std::vector<DIE *> &Entities = GI->second;
2079 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2080 DE = Entities.end(); DI != DE; ++DI)
2081 AT.AddName(Name, (*DI));
2085 AT.FinalizeTable(Asm, "namespac");
2086 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2087 .getDwarfAccelNamespaceSection());
2088 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2089 Asm->OutStreamer.EmitLabel(SectionBegin);
2091 // Emit the full data.
2092 AT.Emit(Asm, SectionBegin, &InfoHolder);
2095 // Emit type dies into a hashed accelerator table.
2096 void DwarfDebug::emitAccelTypes() {
2097 std::vector<DwarfAccelTable::Atom> Atoms;
2098 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2099 dwarf::DW_FORM_data4));
2100 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2101 dwarf::DW_FORM_data2));
2102 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2103 dwarf::DW_FORM_data1));
2104 DwarfAccelTable AT(Atoms);
2105 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2106 E = CUMap.end(); I != E; ++I) {
2107 CompileUnit *TheCU = I->second;
2108 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2109 = TheCU->getAccelTypes();
2110 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2111 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2112 const char *Name = GI->getKeyData();
2113 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2114 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2115 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2116 AT.AddName(Name, (*DI).first, (*DI).second);
2120 AT.FinalizeTable(Asm, "types");
2121 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2122 .getDwarfAccelTypesSection());
2123 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2124 Asm->OutStreamer.EmitLabel(SectionBegin);
2126 // Emit the full data.
2127 AT.Emit(Asm, SectionBegin, &InfoHolder);
2130 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2132 void DwarfDebug::emitDebugPubnames() {
2133 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2135 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2136 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2137 CompileUnit *TheCU = I->second;
2138 unsigned ID = TheCU->getUniqueID();
2140 if (TheCU->getGlobalNames().empty())
2143 // Start the dwarf pubnames section.
2144 Asm->OutStreamer.SwitchSection(
2145 Asm->getObjFileLowering().getDwarfPubNamesSection());
2147 Asm->OutStreamer.AddComment("Length of Public Names Info");
2148 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2149 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2151 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2153 Asm->OutStreamer.AddComment("DWARF Version");
2154 Asm->EmitInt16(dwarf::DWARF_VERSION);
2156 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2157 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2158 DwarfInfoSectionSym);
2160 Asm->OutStreamer.AddComment("Compilation Unit Length");
2161 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2162 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2165 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2166 for (StringMap<DIE*>::const_iterator
2167 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2168 const char *Name = GI->getKeyData();
2169 const DIE *Entity = GI->second;
2171 Asm->OutStreamer.AddComment("DIE offset");
2172 Asm->EmitInt32(Entity->getOffset());
2174 if (Asm->isVerbose())
2175 Asm->OutStreamer.AddComment("External Name");
2176 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2179 Asm->OutStreamer.AddComment("End Mark");
2181 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2185 void DwarfDebug::emitDebugPubTypes() {
2186 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2187 E = CUMap.end(); I != E; ++I) {
2188 CompileUnit *TheCU = I->second;
2189 // Start the dwarf pubtypes section.
2190 Asm->OutStreamer.SwitchSection(
2191 Asm->getObjFileLowering().getDwarfPubTypesSection());
2192 Asm->OutStreamer.AddComment("Length of Public Types Info");
2193 Asm->EmitLabelDifference(
2194 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2195 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2197 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2198 TheCU->getUniqueID()));
2200 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2201 Asm->EmitInt16(dwarf::DWARF_VERSION);
2203 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2204 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2205 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2206 TheCU->getUniqueID()),
2207 DwarfInfoSectionSym);
2209 Asm->OutStreamer.AddComment("Compilation Unit Length");
2210 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2211 TheCU->getUniqueID()),
2212 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2213 TheCU->getUniqueID()),
2216 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2217 for (StringMap<DIE*>::const_iterator
2218 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2219 const char *Name = GI->getKeyData();
2220 DIE *Entity = GI->second;
2222 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2223 Asm->EmitInt32(Entity->getOffset());
2225 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2226 // Emit the name with a terminating null byte.
2227 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2230 Asm->OutStreamer.AddComment("End Mark");
2232 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2233 TheCU->getUniqueID()));
2237 // Emit strings into a string section.
2238 void DwarfUnits::emitStrings(const MCSection *StrSection,
2239 const MCSection *OffsetSection = NULL,
2240 const MCSymbol *StrSecSym = NULL) {
2242 if (StringPool.empty()) return;
2244 // Start the dwarf str section.
2245 Asm->OutStreamer.SwitchSection(StrSection);
2247 // Get all of the string pool entries and put them in an array by their ID so
2248 // we can sort them.
2249 SmallVector<std::pair<unsigned,
2250 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2252 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2253 I = StringPool.begin(), E = StringPool.end();
2255 Entries.push_back(std::make_pair(I->second.second, &*I));
2257 array_pod_sort(Entries.begin(), Entries.end());
2259 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2260 // Emit a label for reference from debug information entries.
2261 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2263 // Emit the string itself with a terminating null byte.
2264 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2265 Entries[i].second->getKeyLength()+1));
2268 // If we've got an offset section go ahead and emit that now as well.
2269 if (OffsetSection) {
2270 Asm->OutStreamer.SwitchSection(OffsetSection);
2271 unsigned offset = 0;
2272 unsigned size = 4; // FIXME: DWARF64 is 8.
2273 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2274 Asm->OutStreamer.EmitIntValue(offset, size);
2275 offset += Entries[i].second->getKeyLength() + 1;
2280 // Emit strings into a string section.
2281 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2283 if (AddressPool.empty()) return;
2285 // Start the dwarf addr section.
2286 Asm->OutStreamer.SwitchSection(AddrSection);
2288 // Get all of the string pool entries and put them in an array by their ID so
2289 // we can sort them.
2290 SmallVector<std::pair<unsigned,
2291 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2293 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2294 I = AddressPool.begin(), E = AddressPool.end();
2296 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2298 array_pod_sort(Entries.begin(), Entries.end());
2300 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2301 // Emit a label for reference from debug information entries.
2302 MCSymbol *Sym = Entries[i].second->first;
2304 Asm->EmitLabelReference(Entries[i].second->first,
2305 Asm->getDataLayout().getPointerSize());
2307 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2312 // Emit visible names into a debug str section.
2313 void DwarfDebug::emitDebugStr() {
2314 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2315 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2318 // Emit visible names into a debug loc section.
2319 void DwarfDebug::emitDebugLoc() {
2320 if (DotDebugLocEntries.empty())
2323 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2324 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2326 DotDebugLocEntry &Entry = *I;
2327 if (I + 1 != DotDebugLocEntries.end())
2331 // Start the dwarf loc section.
2332 Asm->OutStreamer.SwitchSection(
2333 Asm->getObjFileLowering().getDwarfLocSection());
2334 unsigned char Size = Asm->getDataLayout().getPointerSize();
2335 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2337 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2338 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2339 I != E; ++I, ++index) {
2340 DotDebugLocEntry &Entry = *I;
2341 if (Entry.isMerged()) continue;
2342 if (Entry.isEmpty()) {
2343 Asm->OutStreamer.EmitIntValue(0, Size);
2344 Asm->OutStreamer.EmitIntValue(0, Size);
2345 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2347 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2348 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2349 DIVariable DV(Entry.Variable);
2350 Asm->OutStreamer.AddComment("Loc expr size");
2351 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2352 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2353 Asm->EmitLabelDifference(end, begin, 2);
2354 Asm->OutStreamer.EmitLabel(begin);
2355 if (Entry.isInt()) {
2356 DIBasicType BTy(DV.getType());
2358 (BTy.getEncoding() == dwarf::DW_ATE_signed
2359 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2360 Asm->OutStreamer.AddComment("DW_OP_consts");
2361 Asm->EmitInt8(dwarf::DW_OP_consts);
2362 Asm->EmitSLEB128(Entry.getInt());
2364 Asm->OutStreamer.AddComment("DW_OP_constu");
2365 Asm->EmitInt8(dwarf::DW_OP_constu);
2366 Asm->EmitULEB128(Entry.getInt());
2368 } else if (Entry.isLocation()) {
2369 if (!DV.hasComplexAddress())
2371 Asm->EmitDwarfRegOp(Entry.Loc);
2373 // Complex address entry.
2374 unsigned N = DV.getNumAddrElements();
2376 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2377 if (Entry.Loc.getOffset()) {
2379 Asm->EmitDwarfRegOp(Entry.Loc);
2380 Asm->OutStreamer.AddComment("DW_OP_deref");
2381 Asm->EmitInt8(dwarf::DW_OP_deref);
2382 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2383 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2384 Asm->EmitSLEB128(DV.getAddrElement(1));
2386 // If first address element is OpPlus then emit
2387 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2388 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2389 Asm->EmitDwarfRegOp(Loc);
2393 Asm->EmitDwarfRegOp(Entry.Loc);
2396 // Emit remaining complex address elements.
2397 for (; i < N; ++i) {
2398 uint64_t Element = DV.getAddrElement(i);
2399 if (Element == DIBuilder::OpPlus) {
2400 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2401 Asm->EmitULEB128(DV.getAddrElement(++i));
2402 } else if (Element == DIBuilder::OpDeref) {
2403 if (!Entry.Loc.isReg())
2404 Asm->EmitInt8(dwarf::DW_OP_deref);
2406 llvm_unreachable("unknown Opcode found in complex address");
2410 // else ... ignore constant fp. There is not any good way to
2411 // to represent them here in dwarf.
2412 Asm->OutStreamer.EmitLabel(end);
2417 // Emit visible names into a debug aranges section.
2418 void DwarfDebug::emitDebugARanges() {
2419 // Start the dwarf aranges section.
2420 Asm->OutStreamer.SwitchSection(
2421 Asm->getObjFileLowering().getDwarfARangesSection());
2424 // Emit visible names into a debug ranges section.
2425 void DwarfDebug::emitDebugRanges() {
2426 // Start the dwarf ranges section.
2427 Asm->OutStreamer.SwitchSection(
2428 Asm->getObjFileLowering().getDwarfRangesSection());
2429 unsigned char Size = Asm->getDataLayout().getPointerSize();
2430 for (SmallVectorImpl<const MCSymbol *>::iterator
2431 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2434 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2436 Asm->OutStreamer.EmitIntValue(0, Size);
2440 // Emit visible names into a debug macinfo section.
2441 void DwarfDebug::emitDebugMacInfo() {
2442 if (const MCSection *LineInfo =
2443 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2444 // Start the dwarf macinfo section.
2445 Asm->OutStreamer.SwitchSection(LineInfo);
2449 // Emit inline info using following format.
2451 // 1. length of section
2452 // 2. Dwarf version number
2455 // Entries (one "entry" for each function that was inlined):
2457 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2458 // otherwise offset into __debug_str for regular function name.
2459 // 2. offset into __debug_str section for regular function name.
2460 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2461 // instances for the function.
2463 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2464 // inlined instance; the die_offset points to the inlined_subroutine die in the
2465 // __debug_info section, and the low_pc is the starting address for the
2466 // inlining instance.
2467 void DwarfDebug::emitDebugInlineInfo() {
2468 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2474 Asm->OutStreamer.SwitchSection(
2475 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2477 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2478 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2479 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2481 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2483 Asm->OutStreamer.AddComment("Dwarf Version");
2484 Asm->EmitInt16(dwarf::DWARF_VERSION);
2485 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2486 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2488 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2489 E = InlinedSPNodes.end(); I != E; ++I) {
2491 const MDNode *Node = *I;
2492 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2493 = InlineInfo.find(Node);
2494 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2495 DISubprogram SP(Node);
2496 StringRef LName = SP.getLinkageName();
2497 StringRef Name = SP.getName();
2499 Asm->OutStreamer.AddComment("MIPS linkage name");
2501 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2502 DwarfStrSectionSym);
2504 Asm->EmitSectionOffset(InfoHolder
2505 .getStringPoolEntry(getRealLinkageName(LName)),
2506 DwarfStrSectionSym);
2508 Asm->OutStreamer.AddComment("Function name");
2509 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2510 DwarfStrSectionSym);
2511 Asm->EmitULEB128(Labels.size(), "Inline count");
2513 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2514 LE = Labels.end(); LI != LE; ++LI) {
2515 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2516 Asm->EmitInt32(LI->second->getOffset());
2518 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2519 Asm->OutStreamer.EmitSymbolValue(LI->first,
2520 Asm->getDataLayout().getPointerSize());
2524 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2527 // DWARF5 Experimental Separate Dwarf emitters.
2529 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2530 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2531 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2532 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2533 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2534 DICompileUnit DIUnit(N);
2535 CompilationDir = DIUnit.getDirectory();
2537 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2538 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2539 DIUnit.getLanguage(), Die, Asm,
2540 this, &SkeletonHolder);
2542 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2543 DIUnit.getSplitDebugFilename());
2545 // This should be a unique identifier when we want to build .dwp files.
2546 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2548 // Relocate to the beginning of the addr_base section, else 0 for the
2549 // beginning of the one for this compile unit.
2550 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2551 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2552 DwarfAddrSectionSym);
2554 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2555 dwarf::DW_FORM_sec_offset, 0);
2557 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2558 // into an entity. We're using 0, or a NULL label for this.
2559 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2561 // DW_AT_stmt_list is a offset of line number information for this
2562 // compile unit in debug_line section.
2563 // FIXME: Should handle multiple compile units.
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(),