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";
99 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
100 return lhs.first < rhs.first;
103 } // end anonymous namespace
105 //===----------------------------------------------------------------------===//
107 // Configuration values for initial hash set sizes (log2).
109 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
113 DIType DbgVariable::getType() const {
114 DIType Ty = Var.getType();
115 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
116 // addresses instead.
117 if (Var.isBlockByrefVariable()) {
118 /* Byref variables, in Blocks, are declared by the programmer as
119 "SomeType VarName;", but the compiler creates a
120 __Block_byref_x_VarName struct, and gives the variable VarName
121 either the struct, or a pointer to the struct, as its type. This
122 is necessary for various behind-the-scenes things the compiler
123 needs to do with by-reference variables in blocks.
125 However, as far as the original *programmer* is concerned, the
126 variable should still have type 'SomeType', as originally declared.
128 The following function dives into the __Block_byref_x_VarName
129 struct to find the original type of the variable. This will be
130 passed back to the code generating the type for the Debug
131 Information Entry for the variable 'VarName'. 'VarName' will then
132 have the original type 'SomeType' in its debug information.
134 The original type 'SomeType' will be the type of the field named
135 'VarName' inside the __Block_byref_x_VarName struct.
137 NOTE: In order for this to not completely fail on the debugger
138 side, the Debug Information Entry for the variable VarName needs to
139 have a DW_AT_location that tells the debugger how to unwind through
140 the pointers and __Block_byref_x_VarName struct to find the actual
141 value of the variable. The function addBlockByrefType does this. */
143 unsigned tag = Ty.getTag();
145 if (tag == dwarf::DW_TAG_pointer_type) {
146 DIDerivedType DTy = DIDerivedType(Ty);
147 subType = DTy.getTypeDerivedFrom();
150 DICompositeType blockStruct = DICompositeType(subType);
151 DIArray Elements = blockStruct.getTypeArray();
153 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
154 DIDescriptor Element = Elements.getElement(i);
155 DIDerivedType DT = DIDerivedType(Element);
156 if (getName() == DT.getName())
157 return (DT.getTypeDerivedFrom());
163 } // end llvm namespace
165 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
166 : Asm(A), MMI(Asm->MMI), FirstCU(0),
167 AbbreviationsSet(InitAbbreviationsSetSize),
168 SourceIdMap(DIEValueAllocator),
169 PrevLabel(NULL), GlobalCUIndexCount(0),
170 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
172 SkeletonAbbrevSet(InitAbbreviationsSetSize),
173 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
176 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
177 DwarfStrSectionSym = TextSectionSym = 0;
178 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
179 DwarfAddrSectionSym = 0;
180 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
181 FunctionBeginSym = FunctionEndSym = 0;
183 // Turn on accelerator tables and older gdb compatibility
185 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
186 if (DarwinGDBCompat == Default) {
188 IsDarwinGDBCompat = true;
190 IsDarwinGDBCompat = false;
192 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
194 if (DwarfAccelTables == Default) {
196 HasDwarfAccelTables = true;
198 HasDwarfAccelTables = false;
200 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
202 if (SplitDwarf == Default)
203 HasSplitDwarf = false;
205 HasSplitDwarf = SplitDwarf == Enable ? true : false;
208 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
212 DwarfDebug::~DwarfDebug() {
215 // Switch to the specified MCSection and emit an assembler
216 // temporary label to it if SymbolStem is specified.
217 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
218 const char *SymbolStem = 0) {
219 Asm->OutStreamer.SwitchSection(Section);
220 if (!SymbolStem) return 0;
222 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
223 Asm->OutStreamer.EmitLabel(TmpSym);
227 MCSymbol *DwarfUnits::getStringPoolSym() {
228 return Asm->GetTempSymbol(StringPref);
231 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
232 std::pair<MCSymbol*, unsigned> &Entry =
233 StringPool.GetOrCreateValue(Str).getValue();
234 if (Entry.first) return Entry.first;
236 Entry.second = NextStringPoolNumber++;
237 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
240 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
241 std::pair<MCSymbol*, unsigned> &Entry =
242 StringPool.GetOrCreateValue(Str).getValue();
243 if (Entry.first) return Entry.second;
245 Entry.second = NextStringPoolNumber++;
246 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
250 unsigned DwarfUnits::getAddrPoolIndex(MCSymbol *Sym) {
251 std::pair<MCSymbol*, unsigned> &Entry = AddressPool[Sym];
252 if (Entry.first) return Entry.second;
254 Entry.second = NextAddrPoolNumber++;
259 // Define a unique number for the abbreviation.
261 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
262 // Profile the node so that we can make it unique.
266 // Check the set for priors.
267 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
269 // If it's newly added.
270 if (InSet == &Abbrev) {
271 // Add to abbreviation list.
272 Abbreviations->push_back(&Abbrev);
274 // Assign the vector position + 1 as its number.
275 Abbrev.setNumber(Abbreviations->size());
277 // Assign existing abbreviation number.
278 Abbrev.setNumber(InSet->getNumber());
282 // If special LLVM prefix that is used to inform the asm
283 // printer to not emit usual symbol prefix before the symbol name is used then
284 // return linkage name after skipping this special LLVM prefix.
285 static StringRef getRealLinkageName(StringRef LinkageName) {
287 if (LinkageName.startswith(StringRef(&One, 1)))
288 return LinkageName.substr(1);
292 static bool isObjCClass(StringRef Name) {
293 return Name.startswith("+") || Name.startswith("-");
296 static bool hasObjCCategory(StringRef Name) {
297 if (!isObjCClass(Name)) return false;
299 size_t pos = Name.find(')');
300 if (pos != std::string::npos) {
301 if (Name[pos+1] != ' ') return false;
307 static void getObjCClassCategory(StringRef In, StringRef &Class,
308 StringRef &Category) {
309 if (!hasObjCCategory(In)) {
310 Class = In.slice(In.find('[') + 1, In.find(' '));
315 Class = In.slice(In.find('[') + 1, In.find('('));
316 Category = In.slice(In.find('[') + 1, In.find(' '));
320 static StringRef getObjCMethodName(StringRef In) {
321 return In.slice(In.find(' ') + 1, In.find(']'));
324 // Add the various names to the Dwarf accelerator table names.
325 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
327 if (!SP.isDefinition()) return;
329 TheCU->addAccelName(SP.getName(), Die);
331 // If the linkage name is different than the name, go ahead and output
332 // that as well into the name table.
333 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
334 TheCU->addAccelName(SP.getLinkageName(), Die);
336 // If this is an Objective-C selector name add it to the ObjC accelerator
338 if (isObjCClass(SP.getName())) {
339 StringRef Class, Category;
340 getObjCClassCategory(SP.getName(), Class, Category);
341 TheCU->addAccelObjC(Class, Die);
343 TheCU->addAccelObjC(Category, Die);
344 // Also add the base method name to the name table.
345 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
349 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
350 // and DW_AT_high_pc attributes. If there are global variables in this
351 // scope then create and insert DIEs for these variables.
352 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
353 const MDNode *SPNode) {
354 DIE *SPDie = SPCU->getDIE(SPNode);
356 assert(SPDie && "Unable to find subprogram DIE!");
357 DISubprogram SP(SPNode);
359 // If we're updating an abstract DIE, then we will be adding the children and
360 // object pointer later on. But what we don't want to do is process the
361 // concrete DIE twice.
362 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
364 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
365 // Pick up abstract subprogram DIE.
366 SPDie = new DIE(dwarf::DW_TAG_subprogram);
367 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
369 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
370 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
374 DISubprogram SPDecl = SP.getFunctionDeclaration();
375 if (!SPDecl.isSubprogram()) {
376 // There is not any need to generate specification DIE for a function
377 // defined at compile unit level. If a function is defined inside another
378 // function then gdb prefers the definition at top level and but does not
379 // expect specification DIE in parent function. So avoid creating
380 // specification DIE for a function defined inside a function.
381 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
382 !SP.getContext().isFile() &&
383 !isSubprogramContext(SP.getContext())) {
384 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
387 DICompositeType SPTy = SP.getType();
388 DIArray Args = SPTy.getTypeArray();
389 unsigned SPTag = SPTy.getTag();
390 if (SPTag == dwarf::DW_TAG_subroutine_type)
391 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
392 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
393 DIType ATy = DIType(Args.getElement(i));
394 SPCU->addType(Arg, ATy);
395 if (ATy.isArtificial())
396 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
397 if (ATy.isObjectPointer())
398 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
399 dwarf::DW_FORM_ref4, Arg);
400 SPDie->addChild(Arg);
402 DIE *SPDeclDie = SPDie;
403 SPDie = new DIE(dwarf::DW_TAG_subprogram);
404 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
405 dwarf::DW_FORM_ref4, SPDeclDie);
411 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
412 Asm->GetTempSymbol("func_begin",
413 Asm->getFunctionNumber()));
414 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
415 Asm->GetTempSymbol("func_end",
416 Asm->getFunctionNumber()));
417 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
418 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
419 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
421 // Add name to the name table, we do this here because we're guaranteed
422 // to have concrete versions of our DW_TAG_subprogram nodes.
423 addSubprogramNames(SPCU, SP, SPDie);
428 // Construct new DW_TAG_lexical_block for this scope and attach
429 // DW_AT_low_pc/DW_AT_high_pc labels.
430 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
431 LexicalScope *Scope) {
432 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
433 if (Scope->isAbstractScope())
436 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
440 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
441 if (Ranges.size() > 1) {
442 // .debug_range section has not been laid out yet. Emit offset in
443 // .debug_range as a uint, size 4, for now. emitDIE will handle
444 // DW_AT_ranges appropriately.
445 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
446 DebugRangeSymbols.size()
447 * Asm->getDataLayout().getPointerSize());
448 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
449 RE = Ranges.end(); RI != RE; ++RI) {
450 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
451 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
453 DebugRangeSymbols.push_back(NULL);
454 DebugRangeSymbols.push_back(NULL);
458 MCSymbol *Start = getLabelBeforeInsn(RI->first);
459 MCSymbol *End = getLabelAfterInsn(RI->second);
461 if (End == 0) return 0;
463 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
464 assert(End->isDefined() && "Invalid end label for an inlined scope!");
466 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
467 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
472 // This scope represents inlined body of a function. Construct DIE to
473 // represent this concrete inlined copy of the function.
474 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
475 LexicalScope *Scope) {
476 const SmallVector<InsnRange, 4> &Ranges = Scope->getRanges();
477 assert(Ranges.empty() == false &&
478 "LexicalScope does not have instruction markers!");
480 if (!Scope->getScopeNode())
482 DIScope DS(Scope->getScopeNode());
483 DISubprogram InlinedSP = getDISubprogram(DS);
484 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
486 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
490 SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin();
491 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
492 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
494 if (StartLabel == 0 || EndLabel == 0) {
495 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
497 assert(StartLabel->isDefined() &&
498 "Invalid starting label for an inlined scope!");
499 assert(EndLabel->isDefined() &&
500 "Invalid end label for an inlined scope!");
502 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
503 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
504 dwarf::DW_FORM_ref4, OriginDIE);
506 if (Ranges.size() > 1) {
507 // .debug_range section has not been laid out yet. Emit offset in
508 // .debug_range as a uint, size 4, for now. emitDIE will handle
509 // DW_AT_ranges appropriately.
510 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
511 DebugRangeSymbols.size()
512 * Asm->getDataLayout().getPointerSize());
513 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
514 RE = Ranges.end(); RI != RE; ++RI) {
515 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
516 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
518 DebugRangeSymbols.push_back(NULL);
519 DebugRangeSymbols.push_back(NULL);
521 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
522 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
525 InlinedSubprogramDIEs.insert(OriginDIE);
527 // Track the start label for this inlined function.
528 //.debug_inlined section specification does not clearly state how
529 // to emit inlined scope that is split into multiple instruction ranges.
530 // For now, use first instruction range and emit low_pc/high_pc pair and
531 // corresponding .debug_inlined section entry for this pair.
532 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator
533 I = InlineInfo.find(InlinedSP);
535 if (I == InlineInfo.end()) {
536 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
537 InlinedSPNodes.push_back(InlinedSP);
539 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
541 DILocation DL(Scope->getInlinedAt());
542 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
543 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
544 TheCU->getUniqueID()));
545 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
547 // Add name to the name table, we do this here because we're guaranteed
548 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
549 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
554 // Construct a DIE for this scope.
555 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
556 if (!Scope || !Scope->getScopeNode())
559 DIScope DS(Scope->getScopeNode());
560 // Early return to avoid creating dangling variable|scope DIEs.
561 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
565 SmallVector<DIE *, 8> Children;
566 DIE *ObjectPointer = NULL;
568 // Collect arguments for current function.
569 if (LScopes.isCurrentFunctionScope(Scope))
570 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
571 if (DbgVariable *ArgDV = CurrentFnArguments[i])
573 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
574 Children.push_back(Arg);
575 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
578 // Collect lexical scope children first.
579 const SmallVector<DbgVariable *, 8> &Variables = ScopeVariables.lookup(Scope);
580 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
582 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
583 Children.push_back(Variable);
584 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
586 const SmallVector<LexicalScope *, 4> &Scopes = Scope->getChildren();
587 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
588 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
589 Children.push_back(Nested);
590 DIE *ScopeDIE = NULL;
591 if (Scope->getInlinedAt())
592 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
593 else if (DS.isSubprogram()) {
594 ProcessedSPNodes.insert(DS);
595 if (Scope->isAbstractScope()) {
596 ScopeDIE = TheCU->getDIE(DS);
597 // Note down abstract DIE.
599 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
602 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
605 // There is no need to emit empty lexical block DIE.
606 std::pair<ImportedEntityMap::const_iterator,
607 ImportedEntityMap::const_iterator> Range = std::equal_range(
608 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
609 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
611 if (Children.empty() && Range.first == Range.second)
613 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
614 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second; ++i)
615 constructImportedModuleDIE(TheCU, i->second, ScopeDIE);
618 if (!ScopeDIE) return NULL;
621 for (SmallVector<DIE *, 8>::iterator I = Children.begin(),
622 E = Children.end(); I != E; ++I)
623 ScopeDIE->addChild(*I);
625 if (DS.isSubprogram() && ObjectPointer != NULL)
626 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
627 dwarf::DW_FORM_ref4, ObjectPointer);
629 if (DS.isSubprogram())
630 TheCU->addPubTypes(DISubprogram(DS));
635 // Look up the source id with the given directory and source file names.
636 // If none currently exists, create a new id and insert it in the
637 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
639 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
640 StringRef DirName, unsigned CUID) {
641 // If we use .loc in assembly, we can't separate .file entries according to
642 // compile units. Thus all files will belong to the default compile unit.
643 if (Asm->TM.hasMCUseLoc() &&
644 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
647 // If FE did not provide a file name, then assume stdin.
648 if (FileName.empty())
649 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
651 // TODO: this might not belong here. See if we can factor this better.
652 if (DirName == CompilationDir)
655 // FileIDCUMap stores the current ID for the given compile unit.
656 unsigned SrcId = FileIDCUMap[CUID] + 1;
658 // We look up the CUID/file/dir by concatenating them with a zero byte.
659 SmallString<128> NamePair;
660 NamePair += utostr(CUID);
663 NamePair += '\0'; // Zero bytes are not allowed in paths.
664 NamePair += FileName;
666 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
667 if (Ent.getValue() != SrcId)
668 return Ent.getValue();
670 FileIDCUMap[CUID] = SrcId;
671 // Print out a .file directive to specify files for .loc directives.
672 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
677 // Create new CompileUnit for the given metadata node with tag
678 // DW_TAG_compile_unit.
679 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
680 DICompileUnit DIUnit(N);
681 StringRef FN = DIUnit.getFilename();
682 CompilationDir = DIUnit.getDirectory();
684 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
685 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
686 DIUnit.getLanguage(), Die, Asm,
688 NewCU->insertDIE(N, Die);
690 FileIDCUMap[NewCU->getUniqueID()] = 0;
691 // Call this to emit a .file directive if it wasn't emitted for the source
692 // file this CU comes from yet.
693 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
695 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
696 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
697 DIUnit.getLanguage());
698 NewCU->addString(Die, dwarf::DW_AT_name, FN);
700 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
701 // into an entity. We're using 0 (or a NULL label) for this. For
702 // split dwarf it's in the skeleton CU so omit it here.
703 if (!useSplitDwarf())
704 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
706 // Define start line table label for each Compile Unit.
707 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
708 NewCU->getUniqueID());
709 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
710 NewCU->getUniqueID());
712 // DW_AT_stmt_list is a offset of line number information for this
713 // compile unit in debug_line section. For split dwarf this is
714 // left in the skeleton CU and so not included.
715 // The line table entries are not always emitted in assembly, so it
716 // is not okay to use line_table_start here.
717 if (!useSplitDwarf()) {
718 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
719 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
720 NewCU->getUniqueID() == 0 ?
721 Asm->GetTempSymbol("section_line") : LineTableStartSym);
722 else if (NewCU->getUniqueID() == 0)
723 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
725 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
726 LineTableStartSym, DwarfLineSectionSym);
729 // If we're using split dwarf the compilation dir is going to be in the
730 // skeleton CU and so we don't need to duplicate it here.
731 if (!useSplitDwarf() && !CompilationDir.empty())
732 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
733 if (DIUnit.isOptimized())
734 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
736 StringRef Flags = DIUnit.getFlags();
738 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
740 if (unsigned RVer = DIUnit.getRunTimeVersion())
741 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
742 dwarf::DW_FORM_data1, RVer);
747 InfoHolder.addUnit(NewCU);
749 CUMap.insert(std::make_pair(N, NewCU));
753 // Construct subprogram DIE.
754 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
756 CompileUnit *&CURef = SPMap[N];
762 if (!SP.isDefinition())
763 // This is a method declaration which will be handled while constructing
767 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
770 TheCU->insertDIE(N, SubprogramDie);
772 // Add to context owner.
773 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
775 // Expose as global, if requested.
776 if (GenerateDwarfPubNamesSection)
777 TheCU->addGlobalName(SP.getName(), SubprogramDie);
780 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
782 DIImportedEntity Module(N);
783 if (!Module.Verify())
785 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
786 constructImportedModuleDIE(TheCU, Module, D);
789 void DwarfDebug::constructImportedModuleDIE(CompileUnit *TheCU, const MDNode *N,
791 DIImportedEntity Module(N);
792 if (!Module.Verify())
794 return constructImportedModuleDIE(TheCU, Module, Context);
797 void DwarfDebug::constructImportedModuleDIE(CompileUnit *TheCU,
798 const DIImportedEntity &Module,
800 assert(Module.Verify() &&
801 "Use one of the MDNode * overloads to handle invalid metadata");
802 assert(Context && "Should always have a context for an imported_module");
803 DIE *IMDie = new DIE(Module.getTag());
804 TheCU->insertDIE(Module, IMDie);
806 DIDescriptor Entity = Module.getEntity();
807 if (Entity.isNameSpace())
808 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
809 else if (Entity.isSubprogram())
810 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
813 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
814 Module.getContext().getDirectory(),
815 TheCU->getUniqueID());
816 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
817 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
818 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4, EntityDie);
819 Context->addChild(IMDie);
822 // Emit all Dwarf sections that should come prior to the content. Create
823 // global DIEs and emit initial debug info sections. This is invoked by
824 // the target AsmPrinter.
825 void DwarfDebug::beginModule() {
826 if (DisableDebugInfoPrinting)
829 const Module *M = MMI->getModule();
831 // If module has named metadata anchors then use them, otherwise scan the
832 // module using debug info finder to collect debug info.
833 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
837 // Emit initial sections so we can reference labels later.
840 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
841 DICompileUnit CUNode(CU_Nodes->getOperand(i));
842 CompileUnit *CU = constructCompileUnit(CUNode);
843 DIArray ImportedEntities = CUNode.getImportedEntities();
844 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
845 ScopesWithImportedEntities.push_back(std::make_pair(
846 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
847 ImportedEntities.getElement(i)));
848 std::sort(ScopesWithImportedEntities.begin(),
849 ScopesWithImportedEntities.end(), CompareFirst());
850 DIArray GVs = CUNode.getGlobalVariables();
851 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
852 CU->createGlobalVariableDIE(GVs.getElement(i));
853 DIArray SPs = CUNode.getSubprograms();
854 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
855 constructSubprogramDIE(CU, SPs.getElement(i));
856 DIArray EnumTypes = CUNode.getEnumTypes();
857 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
858 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
859 DIArray RetainedTypes = CUNode.getRetainedTypes();
860 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
861 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
862 // Emit imported_modules last so that the relevant context is already
864 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
865 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
866 // If we're splitting the dwarf out now that we've got the entire
867 // CU then construct a skeleton CU based upon it.
868 if (useSplitDwarf()) {
869 // This should be a unique identifier when we want to build .dwp files.
870 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
871 dwarf::DW_FORM_data8, 0);
872 // Now construct the skeleton CU associated.
873 constructSkeletonCU(CUNode);
877 // Tell MMI that we have debug info.
878 MMI->setDebugInfoAvailability(true);
880 // Prime section data.
881 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
884 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
885 void DwarfDebug::computeInlinedDIEs() {
886 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
887 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
888 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
890 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
892 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
893 AE = AbstractSPDies.end(); AI != AE; ++AI) {
894 DIE *ISP = AI->second;
895 if (InlinedSubprogramDIEs.count(ISP))
897 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
901 // Collect info for variables that were optimized out.
902 void DwarfDebug::collectDeadVariables() {
903 const Module *M = MMI->getModule();
904 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
906 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
907 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
908 DICompileUnit TheCU(CU_Nodes->getOperand(i));
909 DIArray Subprograms = TheCU.getSubprograms();
910 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
911 DISubprogram SP(Subprograms.getElement(i));
912 if (ProcessedSPNodes.count(SP) != 0) continue;
913 if (!SP.Verify()) continue;
914 if (!SP.isDefinition()) continue;
915 DIArray Variables = SP.getVariables();
916 if (Variables.getNumElements() == 0) continue;
918 LexicalScope *Scope =
919 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
920 DeadFnScopeMap[SP] = Scope;
922 // Construct subprogram DIE and add variables DIEs.
923 CompileUnit *SPCU = CUMap.lookup(TheCU);
924 assert(SPCU && "Unable to find Compile Unit!");
925 constructSubprogramDIE(SPCU, SP);
926 DIE *ScopeDIE = SPCU->getDIE(SP);
927 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
928 DIVariable DV(Variables.getElement(vi));
929 if (!DV.Verify()) continue;
930 DbgVariable *NewVar = new DbgVariable(DV, NULL);
931 if (DIE *VariableDIE =
932 SPCU->constructVariableDIE(NewVar, Scope->isAbstractScope()))
933 ScopeDIE->addChild(VariableDIE);
938 DeleteContainerSeconds(DeadFnScopeMap);
941 void DwarfDebug::finalizeModuleInfo() {
942 // Collect info for variables that were optimized out.
943 collectDeadVariables();
945 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
946 computeInlinedDIEs();
948 // Emit DW_AT_containing_type attribute to connect types with their
949 // vtable holding type.
950 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
951 CUE = CUMap.end(); CUI != CUE; ++CUI) {
952 CompileUnit *TheCU = CUI->second;
953 TheCU->constructContainingTypeDIEs();
956 // Compute DIE offsets and sizes.
957 InfoHolder.computeSizeAndOffsets();
959 SkeletonHolder.computeSizeAndOffsets();
962 void DwarfDebug::endSections() {
963 // Standard sections final addresses.
964 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
965 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
966 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
967 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
969 // End text sections.
970 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
971 Asm->OutStreamer.SwitchSection(SectionMap[I]);
972 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
976 // Emit all Dwarf sections that should come after the content.
977 void DwarfDebug::endModule() {
979 if (!FirstCU) return;
981 // End any existing sections.
982 // TODO: Does this need to happen?
985 // Finalize the debug info for the module.
986 finalizeModuleInfo();
988 if (!useSplitDwarf()) {
989 // Emit all the DIEs into a debug info section.
992 // Corresponding abbreviations into a abbrev section.
995 // Emit info into a debug loc section.
998 // Emit info into a debug aranges section.
1001 // Emit info into a debug ranges section.
1004 // Emit info into a debug macinfo section.
1007 // Emit inline info.
1008 // TODO: When we don't need the option anymore we
1009 // can remove all of the code that this section
1011 if (useDarwinGDBCompat())
1012 emitDebugInlineInfo();
1014 // TODO: Fill this in for separated debug sections and separate
1015 // out information into new sections.
1017 // Emit the debug info section and compile units.
1021 // Corresponding abbreviations into a abbrev section.
1022 emitAbbreviations();
1023 emitDebugAbbrevDWO();
1025 // Emit info into a debug loc section.
1028 // Emit info into a debug aranges section.
1031 // Emit info into a debug ranges section.
1034 // Emit info into a debug macinfo section.
1037 // Emit DWO addresses.
1038 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1040 // Emit inline info.
1041 // TODO: When we don't need the option anymore we
1042 // can remove all of the code that this section
1044 if (useDarwinGDBCompat())
1045 emitDebugInlineInfo();
1048 // Emit info into the dwarf accelerator table sections.
1049 if (useDwarfAccelTables()) {
1052 emitAccelNamespaces();
1056 // Emit info into a debug pubnames section, if requested.
1057 if (GenerateDwarfPubNamesSection)
1058 emitDebugPubnames();
1060 // Emit info into a debug pubtypes section.
1061 // TODO: When we don't need the option anymore we can
1062 // remove all of the code that adds to the table.
1063 if (useDarwinGDBCompat())
1064 emitDebugPubTypes();
1066 // Finally emit string information into a string table.
1068 if (useSplitDwarf())
1073 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1074 E = CUMap.end(); I != E; ++I)
1077 for (SmallVector<CompileUnit *, 1>::iterator I = SkeletonCUs.begin(),
1078 E = SkeletonCUs.end(); I != E; ++I)
1081 // Reset these for the next Module if we have one.
1085 // Find abstract variable, if any, associated with Var.
1086 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1087 DebugLoc ScopeLoc) {
1088 LLVMContext &Ctx = DV->getContext();
1089 // More then one inlined variable corresponds to one abstract variable.
1090 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1091 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1093 return AbsDbgVariable;
1095 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1099 AbsDbgVariable = new DbgVariable(Var, NULL);
1100 addScopeVariable(Scope, AbsDbgVariable);
1101 AbstractVariables[Var] = AbsDbgVariable;
1102 return AbsDbgVariable;
1105 // If Var is a current function argument then add it to CurrentFnArguments list.
1106 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1107 DbgVariable *Var, LexicalScope *Scope) {
1108 if (!LScopes.isCurrentFunctionScope(Scope))
1110 DIVariable DV = Var->getVariable();
1111 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1113 unsigned ArgNo = DV.getArgNumber();
1117 size_t Size = CurrentFnArguments.size();
1119 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1120 // llvm::Function argument size is not good indicator of how many
1121 // arguments does the function have at source level.
1123 CurrentFnArguments.resize(ArgNo * 2);
1124 CurrentFnArguments[ArgNo - 1] = Var;
1128 // Collect variable information from side table maintained by MMI.
1130 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1131 SmallPtrSet<const MDNode *, 16> &Processed) {
1132 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1133 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1134 VE = VMap.end(); VI != VE; ++VI) {
1135 const MDNode *Var = VI->first;
1137 Processed.insert(Var);
1139 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1141 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1143 // If variable scope is not found then skip this variable.
1147 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1148 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1149 RegVar->setFrameIndex(VP.first);
1150 if (!addCurrentFnArgument(MF, RegVar, Scope))
1151 addScopeVariable(Scope, RegVar);
1153 AbsDbgVariable->setFrameIndex(VP.first);
1157 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1159 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1160 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1161 return MI->getNumOperands() == 3 &&
1162 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1163 MI->getOperand(1).isImm() && MI->getOperand(1).getImm() == 0;
1166 // Get .debug_loc entry for the instruction range starting at MI.
1167 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1168 const MCSymbol *FLabel,
1169 const MCSymbol *SLabel,
1170 const MachineInstr *MI) {
1171 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1173 if (MI->getNumOperands() != 3) {
1174 MachineLocation MLoc = Asm->getDebugValueLocation(MI);
1175 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1177 if (MI->getOperand(0).isReg() && MI->getOperand(1).isImm()) {
1178 MachineLocation MLoc;
1179 // TODO: Currently an offset of 0 in a DBG_VALUE means
1180 // we need to generate a direct register value.
1181 // There is no way to specify an indirect value with offset 0.
1182 if (MI->getOperand(1).getImm() == 0)
1183 MLoc.set(MI->getOperand(0).getReg());
1185 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1186 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1188 if (MI->getOperand(0).isImm())
1189 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1190 if (MI->getOperand(0).isFPImm())
1191 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1192 if (MI->getOperand(0).isCImm())
1193 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1195 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1198 // Find variables for each lexical scope.
1200 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1201 SmallPtrSet<const MDNode *, 16> &Processed) {
1203 // collection info from MMI table.
1204 collectVariableInfoFromMMITable(MF, Processed);
1206 for (SmallVectorImpl<const MDNode*>::const_iterator
1207 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1209 const MDNode *Var = *UVI;
1210 if (Processed.count(Var))
1213 // History contains relevant DBG_VALUE instructions for Var and instructions
1215 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1216 if (History.empty())
1218 const MachineInstr *MInsn = History.front();
1221 LexicalScope *Scope = NULL;
1222 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1223 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1224 Scope = LScopes.getCurrentFunctionScope();
1225 else if (MDNode *IA = DV.getInlinedAt())
1226 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1228 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1229 // If variable scope is not found then skip this variable.
1233 Processed.insert(DV);
1234 assert(MInsn->isDebugValue() && "History must begin with debug value");
1235 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1236 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1237 if (!addCurrentFnArgument(MF, RegVar, Scope))
1238 addScopeVariable(Scope, RegVar);
1240 AbsVar->setMInsn(MInsn);
1242 // Simplify ranges that are fully coalesced.
1243 if (History.size() <= 1 || (History.size() == 2 &&
1244 MInsn->isIdenticalTo(History.back()))) {
1245 RegVar->setMInsn(MInsn);
1249 // Handle multiple DBG_VALUE instructions describing one variable.
1250 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1252 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1253 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1254 const MachineInstr *Begin = *HI;
1255 assert(Begin->isDebugValue() && "Invalid History entry");
1257 // Check if DBG_VALUE is truncating a range.
1258 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1259 && !Begin->getOperand(0).getReg())
1262 // Compute the range for a register location.
1263 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1264 const MCSymbol *SLabel = 0;
1267 // If Begin is the last instruction in History then its value is valid
1268 // until the end of the function.
1269 SLabel = FunctionEndSym;
1271 const MachineInstr *End = HI[1];
1272 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1273 << "\t" << *Begin << "\t" << *End << "\n");
1274 if (End->isDebugValue())
1275 SLabel = getLabelBeforeInsn(End);
1277 // End is a normal instruction clobbering the range.
1278 SLabel = getLabelAfterInsn(End);
1279 assert(SLabel && "Forgot label after clobber instruction");
1284 // The value is valid until the next DBG_VALUE or clobber.
1285 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1288 DotDebugLocEntries.push_back(DotDebugLocEntry());
1291 // Collect info for variables that were optimized out.
1292 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1293 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1294 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1295 DIVariable DV(Variables.getElement(i));
1296 if (!DV || !DV.Verify() || !Processed.insert(DV))
1298 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1299 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1303 // Return Label preceding the instruction.
1304 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1305 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1306 assert(Label && "Didn't insert label before instruction");
1310 // Return Label immediately following the instruction.
1311 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1312 return LabelsAfterInsn.lookup(MI);
1315 // Process beginning of an instruction.
1316 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1317 // Check if source location changes, but ignore DBG_VALUE locations.
1318 if (!MI->isDebugValue()) {
1319 DebugLoc DL = MI->getDebugLoc();
1320 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1323 if (DL == PrologEndLoc) {
1324 Flags |= DWARF2_FLAG_PROLOGUE_END;
1325 PrologEndLoc = DebugLoc();
1327 if (PrologEndLoc.isUnknown())
1328 Flags |= DWARF2_FLAG_IS_STMT;
1330 if (!DL.isUnknown()) {
1331 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1332 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1334 recordSourceLine(0, 0, 0, 0);
1338 // Insert labels where requested.
1339 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1340 LabelsBeforeInsn.find(MI);
1343 if (I == LabelsBeforeInsn.end())
1346 // Label already assigned.
1351 PrevLabel = MMI->getContext().CreateTempSymbol();
1352 Asm->OutStreamer.EmitLabel(PrevLabel);
1354 I->second = PrevLabel;
1357 // Process end of an instruction.
1358 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1359 // Don't create a new label after DBG_VALUE instructions.
1360 // They don't generate code.
1361 if (!MI->isDebugValue())
1364 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1365 LabelsAfterInsn.find(MI);
1368 if (I == LabelsAfterInsn.end())
1371 // Label already assigned.
1375 // We need a label after this instruction.
1377 PrevLabel = MMI->getContext().CreateTempSymbol();
1378 Asm->OutStreamer.EmitLabel(PrevLabel);
1380 I->second = PrevLabel;
1383 // Each LexicalScope has first instruction and last instruction to mark
1384 // beginning and end of a scope respectively. Create an inverse map that list
1385 // scopes starts (and ends) with an instruction. One instruction may start (or
1386 // end) multiple scopes. Ignore scopes that are not reachable.
1387 void DwarfDebug::identifyScopeMarkers() {
1388 SmallVector<LexicalScope *, 4> WorkList;
1389 WorkList.push_back(LScopes.getCurrentFunctionScope());
1390 while (!WorkList.empty()) {
1391 LexicalScope *S = WorkList.pop_back_val();
1393 const SmallVector<LexicalScope *, 4> &Children = S->getChildren();
1394 if (!Children.empty())
1395 for (SmallVector<LexicalScope *, 4>::const_iterator SI = Children.begin(),
1396 SE = Children.end(); SI != SE; ++SI)
1397 WorkList.push_back(*SI);
1399 if (S->isAbstractScope())
1402 const SmallVector<InsnRange, 4> &Ranges = S->getRanges();
1405 for (SmallVector<InsnRange, 4>::const_iterator RI = Ranges.begin(),
1406 RE = Ranges.end(); RI != RE; ++RI) {
1407 assert(RI->first && "InsnRange does not have first instruction!");
1408 assert(RI->second && "InsnRange does not have second instruction!");
1409 requestLabelBeforeInsn(RI->first);
1410 requestLabelAfterInsn(RI->second);
1415 // Get MDNode for DebugLoc's scope.
1416 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1417 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1418 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1419 return DL.getScope(Ctx);
1422 // Walk up the scope chain of given debug loc and find line number info
1423 // for the function.
1424 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1425 const MDNode *Scope = getScopeNode(DL, Ctx);
1426 DISubprogram SP = getDISubprogram(Scope);
1428 // Check for number of operands since the compatibility is
1430 if (SP->getNumOperands() > 19)
1431 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1433 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1439 // Gather pre-function debug information. Assumes being called immediately
1440 // after the function entry point has been emitted.
1441 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1442 if (!MMI->hasDebugInfo()) return;
1443 LScopes.initialize(*MF);
1444 if (LScopes.empty()) return;
1445 identifyScopeMarkers();
1447 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1449 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1450 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1451 assert(TheCU && "Unable to find compile unit!");
1452 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1454 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1455 Asm->getFunctionNumber());
1456 // Assumes in correct section after the entry point.
1457 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1459 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1461 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1462 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1463 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1465 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1467 bool AtBlockEntry = true;
1468 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1470 const MachineInstr *MI = II;
1472 if (MI->isDebugValue()) {
1473 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1475 // Keep track of user variables.
1477 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1479 // Variable is in a register, we need to check for clobbers.
1480 if (isDbgValueInDefinedReg(MI))
1481 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1483 // Check the history of this variable.
1484 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1485 if (History.empty()) {
1486 UserVariables.push_back(Var);
1487 // The first mention of a function argument gets the FunctionBeginSym
1488 // label, so arguments are visible when breaking at function entry.
1490 if (DV.Verify() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1491 DISubprogram(getDISubprogram(DV.getContext()))
1492 .describes(MF->getFunction()))
1493 LabelsBeforeInsn[MI] = FunctionBeginSym;
1495 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1496 const MachineInstr *Prev = History.back();
1497 if (Prev->isDebugValue()) {
1498 // Coalesce identical entries at the end of History.
1499 if (History.size() >= 2 &&
1500 Prev->isIdenticalTo(History[History.size() - 2])) {
1501 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1503 << "\t" << *History[History.size() - 2] << "\n");
1507 // Terminate old register assignments that don't reach MI;
1508 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1509 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1510 isDbgValueInDefinedReg(Prev)) {
1511 // Previous register assignment needs to terminate at the end of
1513 MachineBasicBlock::const_iterator LastMI =
1514 PrevMBB->getLastNonDebugInstr();
1515 if (LastMI == PrevMBB->end()) {
1516 // Drop DBG_VALUE for empty range.
1517 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1518 << "\t" << *Prev << "\n");
1522 // Terminate after LastMI.
1523 History.push_back(LastMI);
1528 History.push_back(MI);
1530 // Not a DBG_VALUE instruction.
1532 AtBlockEntry = false;
1534 // First known non-DBG_VALUE and non-frame setup location marks
1535 // the beginning of the function body.
1536 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1537 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1538 PrologEndLoc = MI->getDebugLoc();
1540 // Check if the instruction clobbers any registers with debug vars.
1541 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1542 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1543 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1545 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1546 AI.isValid(); ++AI) {
1548 const MDNode *Var = LiveUserVar[Reg];
1551 // Reg is now clobbered.
1552 LiveUserVar[Reg] = 0;
1554 // Was MD last defined by a DBG_VALUE referring to Reg?
1555 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1556 if (HistI == DbgValues.end())
1558 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1559 if (History.empty())
1561 const MachineInstr *Prev = History.back();
1562 // Sanity-check: Register assignments are terminated at the end of
1564 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1566 // Is the variable still in Reg?
1567 if (!isDbgValueInDefinedReg(Prev) ||
1568 Prev->getOperand(0).getReg() != Reg)
1570 // Var is clobbered. Make sure the next instruction gets a label.
1571 History.push_back(MI);
1578 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1580 SmallVectorImpl<const MachineInstr*> &History = I->second;
1581 if (History.empty())
1584 // Make sure the final register assignments are terminated.
1585 const MachineInstr *Prev = History.back();
1586 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1587 const MachineBasicBlock *PrevMBB = Prev->getParent();
1588 MachineBasicBlock::const_iterator LastMI =
1589 PrevMBB->getLastNonDebugInstr();
1590 if (LastMI == PrevMBB->end())
1591 // Drop DBG_VALUE for empty range.
1594 // Terminate after LastMI.
1595 History.push_back(LastMI);
1598 // Request labels for the full history.
1599 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1600 const MachineInstr *MI = History[i];
1601 if (MI->isDebugValue())
1602 requestLabelBeforeInsn(MI);
1604 requestLabelAfterInsn(MI);
1608 PrevInstLoc = DebugLoc();
1609 PrevLabel = FunctionBeginSym;
1611 // Record beginning of function.
1612 if (!PrologEndLoc.isUnknown()) {
1613 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1614 MF->getFunction()->getContext());
1615 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1616 FnStartDL.getScope(MF->getFunction()->getContext()),
1617 // We'd like to list the prologue as "not statements" but GDB behaves
1618 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1619 DWARF2_FLAG_IS_STMT);
1623 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1624 // SmallVector<DbgVariable *, 8> &Vars = ScopeVariables.lookup(LS);
1625 ScopeVariables[LS].push_back(Var);
1626 // Vars.push_back(Var);
1629 // Gather and emit post-function debug information.
1630 void DwarfDebug::endFunction(const MachineFunction *MF) {
1631 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1633 // Define end label for subprogram.
1634 FunctionEndSym = Asm->GetTempSymbol("func_end",
1635 Asm->getFunctionNumber());
1636 // Assumes in correct section after the entry point.
1637 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1638 // Set DwarfCompileUnitID in MCContext to default value.
1639 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1641 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1642 collectVariableInfo(MF, ProcessedVars);
1644 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1645 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1646 assert(TheCU && "Unable to find compile unit!");
1648 // Construct abstract scopes.
1649 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1650 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1651 LexicalScope *AScope = AList[i];
1652 DISubprogram SP(AScope->getScopeNode());
1654 // Collect info for variables that were optimized out.
1655 DIArray Variables = SP.getVariables();
1656 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1657 DIVariable DV(Variables.getElement(i));
1658 if (!DV || !DV.Verify() || !ProcessedVars.insert(DV))
1660 // Check that DbgVariable for DV wasn't created earlier, when
1661 // findAbstractVariable() was called for inlined instance of DV.
1662 LLVMContext &Ctx = DV->getContext();
1663 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1664 if (AbstractVariables.lookup(CleanDV))
1666 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1667 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1670 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1671 constructScopeDIE(TheCU, AScope);
1674 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1676 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1677 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1679 DebugFrames.push_back(FunctionDebugFrameInfo(Asm->getFunctionNumber(),
1680 MMI->getFrameMoves()));
1683 for (DenseMap<LexicalScope *, SmallVector<DbgVariable *, 8> >::iterator
1684 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1685 DeleteContainerPointers(I->second);
1686 ScopeVariables.clear();
1687 DeleteContainerPointers(CurrentFnArguments);
1688 UserVariables.clear();
1690 AbstractVariables.clear();
1691 LabelsBeforeInsn.clear();
1692 LabelsAfterInsn.clear();
1696 // Register a source line with debug info. Returns the unique label that was
1697 // emitted and which provides correspondence to the source line list.
1698 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1704 DIDescriptor Scope(S);
1706 if (Scope.isCompileUnit()) {
1707 DICompileUnit CU(S);
1708 Fn = CU.getFilename();
1709 Dir = CU.getDirectory();
1710 } else if (Scope.isFile()) {
1712 Fn = F.getFilename();
1713 Dir = F.getDirectory();
1714 } else if (Scope.isSubprogram()) {
1716 Fn = SP.getFilename();
1717 Dir = SP.getDirectory();
1718 } else if (Scope.isLexicalBlockFile()) {
1719 DILexicalBlockFile DBF(S);
1720 Fn = DBF.getFilename();
1721 Dir = DBF.getDirectory();
1722 } else if (Scope.isLexicalBlock()) {
1723 DILexicalBlock DB(S);
1724 Fn = DB.getFilename();
1725 Dir = DB.getDirectory();
1727 llvm_unreachable("Unexpected scope info");
1729 Src = getOrCreateSourceID(Fn, Dir,
1730 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1732 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1735 //===----------------------------------------------------------------------===//
1737 //===----------------------------------------------------------------------===//
1739 // Compute the size and offset of a DIE.
1741 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1742 // Get the children.
1743 const std::vector<DIE *> &Children = Die->getChildren();
1745 // Record the abbreviation.
1746 assignAbbrevNumber(Die->getAbbrev());
1748 // Get the abbreviation for this DIE.
1749 unsigned AbbrevNumber = Die->getAbbrevNumber();
1750 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1753 Die->setOffset(Offset);
1755 // Start the size with the size of abbreviation code.
1756 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1758 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1759 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1761 // Size the DIE attribute values.
1762 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1763 // Size attribute value.
1764 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1766 // Size the DIE children if any.
1767 if (!Children.empty()) {
1768 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1769 "Children flag not set");
1771 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1772 Offset = computeSizeAndOffset(Children[j], Offset);
1774 // End of children marker.
1775 Offset += sizeof(int8_t);
1778 Die->setSize(Offset - Die->getOffset());
1782 // Compute the size and offset of all the DIEs.
1783 void DwarfUnits::computeSizeAndOffsets() {
1784 // Offset from the beginning of debug info section.
1785 unsigned AccuOffset = 0;
1786 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1787 E = CUs.end(); I != E; ++I) {
1788 (*I)->setDebugInfoOffset(AccuOffset);
1790 sizeof(int32_t) + // Length of Compilation Unit Info
1791 sizeof(int16_t) + // DWARF version number
1792 sizeof(int32_t) + // Offset Into Abbrev. Section
1793 sizeof(int8_t); // Pointer Size (in bytes)
1795 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1796 AccuOffset += EndOffset;
1800 // Emit initial Dwarf sections with a label at the start of each one.
1801 void DwarfDebug::emitSectionLabels() {
1802 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1804 // Dwarf sections base addresses.
1805 DwarfInfoSectionSym =
1806 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1807 DwarfAbbrevSectionSym =
1808 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1809 if (useSplitDwarf())
1810 DwarfAbbrevDWOSectionSym =
1811 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1812 "section_abbrev_dwo");
1813 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1815 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1816 emitSectionSym(Asm, MacroInfo);
1818 DwarfLineSectionSym =
1819 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1820 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1821 if (GenerateDwarfPubNamesSection)
1822 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1823 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1824 DwarfStrSectionSym =
1825 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1826 if (useSplitDwarf()) {
1827 DwarfStrDWOSectionSym =
1828 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1829 DwarfAddrSectionSym =
1830 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1832 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1835 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1836 "section_debug_loc");
1838 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1839 emitSectionSym(Asm, TLOF.getDataSection());
1842 // Recursively emits a debug information entry.
1843 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1844 // Get the abbreviation for this DIE.
1845 unsigned AbbrevNumber = Die->getAbbrevNumber();
1846 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1848 // Emit the code (index) for the abbreviation.
1849 if (Asm->isVerbose())
1850 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1851 Twine::utohexstr(Die->getOffset()) + ":0x" +
1852 Twine::utohexstr(Die->getSize()) + " " +
1853 dwarf::TagString(Abbrev->getTag()));
1854 Asm->EmitULEB128(AbbrevNumber);
1856 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1857 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1859 // Emit the DIE attribute values.
1860 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1861 unsigned Attr = AbbrevData[i].getAttribute();
1862 unsigned Form = AbbrevData[i].getForm();
1863 assert(Form && "Too many attributes for DIE (check abbreviation)");
1865 if (Asm->isVerbose())
1866 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1869 case dwarf::DW_AT_abstract_origin: {
1870 DIEEntry *E = cast<DIEEntry>(Values[i]);
1871 DIE *Origin = E->getEntry();
1872 unsigned Addr = Origin->getOffset();
1873 if (Form == dwarf::DW_FORM_ref_addr) {
1874 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1875 // section. Origin->getOffset() returns the offset from start of the
1877 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1878 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1880 Asm->EmitInt32(Addr);
1883 case dwarf::DW_AT_ranges: {
1884 // DW_AT_range Value encodes offset in debug_range section.
1885 DIEInteger *V = cast<DIEInteger>(Values[i]);
1887 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1888 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1892 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1894 DwarfDebugRangeSectionSym,
1899 case dwarf::DW_AT_location: {
1900 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1901 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1902 Asm->EmitLabelReference(L->getValue(), 4);
1904 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1906 Values[i]->EmitValue(Asm, Form);
1910 case dwarf::DW_AT_accessibility: {
1911 if (Asm->isVerbose()) {
1912 DIEInteger *V = cast<DIEInteger>(Values[i]);
1913 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1915 Values[i]->EmitValue(Asm, Form);
1919 // Emit an attribute using the defined form.
1920 Values[i]->EmitValue(Asm, Form);
1925 // Emit the DIE children if any.
1926 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1927 const std::vector<DIE *> &Children = Die->getChildren();
1929 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1930 emitDIE(Children[j], Abbrevs);
1932 if (Asm->isVerbose())
1933 Asm->OutStreamer.AddComment("End Of Children Mark");
1938 // Emit the various dwarf units to the unit section USection with
1939 // the abbreviations going into ASection.
1940 void DwarfUnits::emitUnits(DwarfDebug *DD,
1941 const MCSection *USection,
1942 const MCSection *ASection,
1943 const MCSymbol *ASectionSym) {
1944 Asm->OutStreamer.SwitchSection(USection);
1945 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1946 E = CUs.end(); I != E; ++I) {
1947 CompileUnit *TheCU = *I;
1948 DIE *Die = TheCU->getCUDie();
1950 // Emit the compile units header.
1952 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
1953 TheCU->getUniqueID()));
1955 // Emit size of content not including length itself
1956 unsigned ContentSize = Die->getSize() +
1957 sizeof(int16_t) + // DWARF version number
1958 sizeof(int32_t) + // Offset Into Abbrev. Section
1959 sizeof(int8_t); // Pointer Size (in bytes)
1961 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
1962 Asm->EmitInt32(ContentSize);
1963 Asm->OutStreamer.AddComment("DWARF version number");
1964 Asm->EmitInt16(dwarf::DWARF_VERSION);
1965 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
1966 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
1968 Asm->OutStreamer.AddComment("Address Size (in bytes)");
1969 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
1971 DD->emitDIE(Die, Abbreviations);
1972 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
1973 TheCU->getUniqueID()));
1977 /// For a given compile unit DIE, returns offset from beginning of debug info.
1978 unsigned DwarfUnits::getCUOffset(DIE *Die) {
1979 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
1980 "Input DIE should be compile unit in getCUOffset.");
1981 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1982 E = CUs.end(); I != E; ++I) {
1983 CompileUnit *TheCU = *I;
1984 if (TheCU->getCUDie() == Die)
1985 return TheCU->getDebugInfoOffset();
1987 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
1990 // Emit the debug info section.
1991 void DwarfDebug::emitDebugInfo() {
1992 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1994 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
1995 Asm->getObjFileLowering().getDwarfAbbrevSection(),
1996 DwarfAbbrevSectionSym);
1999 // Emit the abbreviation section.
2000 void DwarfDebug::emitAbbreviations() {
2001 if (!useSplitDwarf())
2002 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2005 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2008 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2009 std::vector<DIEAbbrev *> *Abbrevs) {
2010 // Check to see if it is worth the effort.
2011 if (!Abbrevs->empty()) {
2012 // Start the debug abbrev section.
2013 Asm->OutStreamer.SwitchSection(Section);
2015 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2016 Asm->OutStreamer.EmitLabel(Begin);
2018 // For each abbrevation.
2019 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2020 // Get abbreviation data
2021 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2023 // Emit the abbrevations code (base 1 index.)
2024 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2026 // Emit the abbreviations data.
2030 // Mark end of abbreviations.
2031 Asm->EmitULEB128(0, "EOM(3)");
2033 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2034 Asm->OutStreamer.EmitLabel(End);
2038 // Emit the last address of the section and the end of the line matrix.
2039 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2040 // Define last address of section.
2041 Asm->OutStreamer.AddComment("Extended Op");
2044 Asm->OutStreamer.AddComment("Op size");
2045 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2046 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2047 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2049 Asm->OutStreamer.AddComment("Section end label");
2051 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2052 Asm->getDataLayout().getPointerSize());
2054 // Mark end of matrix.
2055 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2061 // Emit visible names into a hashed accelerator table section.
2062 void DwarfDebug::emitAccelNames() {
2063 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2064 dwarf::DW_FORM_data4));
2065 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2066 E = CUMap.end(); I != E; ++I) {
2067 CompileUnit *TheCU = I->second;
2068 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2069 for (StringMap<std::vector<DIE*> >::const_iterator
2070 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2071 const char *Name = GI->getKeyData();
2072 const std::vector<DIE *> &Entities = GI->second;
2073 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2074 DE = Entities.end(); DI != DE; ++DI)
2075 AT.AddName(Name, (*DI));
2079 AT.FinalizeTable(Asm, "Names");
2080 Asm->OutStreamer.SwitchSection(
2081 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2082 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2083 Asm->OutStreamer.EmitLabel(SectionBegin);
2085 // Emit the full data.
2086 AT.Emit(Asm, SectionBegin, &InfoHolder);
2089 // Emit objective C classes and categories into a hashed accelerator table
2091 void DwarfDebug::emitAccelObjC() {
2092 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2093 dwarf::DW_FORM_data4));
2094 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2095 E = CUMap.end(); I != E; ++I) {
2096 CompileUnit *TheCU = I->second;
2097 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2098 for (StringMap<std::vector<DIE*> >::const_iterator
2099 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2100 const char *Name = GI->getKeyData();
2101 const std::vector<DIE *> &Entities = GI->second;
2102 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2103 DE = Entities.end(); DI != DE; ++DI)
2104 AT.AddName(Name, (*DI));
2108 AT.FinalizeTable(Asm, "ObjC");
2109 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2110 .getDwarfAccelObjCSection());
2111 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2112 Asm->OutStreamer.EmitLabel(SectionBegin);
2114 // Emit the full data.
2115 AT.Emit(Asm, SectionBegin, &InfoHolder);
2118 // Emit namespace dies into a hashed accelerator table.
2119 void DwarfDebug::emitAccelNamespaces() {
2120 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2121 dwarf::DW_FORM_data4));
2122 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2123 E = CUMap.end(); I != E; ++I) {
2124 CompileUnit *TheCU = I->second;
2125 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2126 for (StringMap<std::vector<DIE*> >::const_iterator
2127 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2128 const char *Name = GI->getKeyData();
2129 const std::vector<DIE *> &Entities = GI->second;
2130 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2131 DE = Entities.end(); DI != DE; ++DI)
2132 AT.AddName(Name, (*DI));
2136 AT.FinalizeTable(Asm, "namespac");
2137 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2138 .getDwarfAccelNamespaceSection());
2139 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2140 Asm->OutStreamer.EmitLabel(SectionBegin);
2142 // Emit the full data.
2143 AT.Emit(Asm, SectionBegin, &InfoHolder);
2146 // Emit type dies into a hashed accelerator table.
2147 void DwarfDebug::emitAccelTypes() {
2148 std::vector<DwarfAccelTable::Atom> Atoms;
2149 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2150 dwarf::DW_FORM_data4));
2151 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2152 dwarf::DW_FORM_data2));
2153 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2154 dwarf::DW_FORM_data1));
2155 DwarfAccelTable AT(Atoms);
2156 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2157 E = CUMap.end(); I != E; ++I) {
2158 CompileUnit *TheCU = I->second;
2159 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2160 = TheCU->getAccelTypes();
2161 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2162 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2163 const char *Name = GI->getKeyData();
2164 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2165 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2166 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2167 AT.AddName(Name, (*DI).first, (*DI).second);
2171 AT.FinalizeTable(Asm, "types");
2172 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2173 .getDwarfAccelTypesSection());
2174 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2175 Asm->OutStreamer.EmitLabel(SectionBegin);
2177 // Emit the full data.
2178 AT.Emit(Asm, SectionBegin, &InfoHolder);
2181 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2183 void DwarfDebug::emitDebugPubnames() {
2184 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2186 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2187 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2188 CompileUnit *TheCU = I->second;
2189 unsigned ID = TheCU->getUniqueID();
2191 if (TheCU->getGlobalNames().empty())
2194 // Start the dwarf pubnames section.
2195 Asm->OutStreamer.SwitchSection(
2196 Asm->getObjFileLowering().getDwarfPubNamesSection());
2198 Asm->OutStreamer.AddComment("Length of Public Names Info");
2199 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2200 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2202 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2204 Asm->OutStreamer.AddComment("DWARF Version");
2205 Asm->EmitInt16(dwarf::DWARF_VERSION);
2207 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2208 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2209 DwarfInfoSectionSym);
2211 Asm->OutStreamer.AddComment("Compilation Unit Length");
2212 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2213 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2216 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2217 for (StringMap<DIE*>::const_iterator
2218 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2219 const char *Name = GI->getKeyData();
2220 const DIE *Entity = GI->second;
2222 Asm->OutStreamer.AddComment("DIE offset");
2223 Asm->EmitInt32(Entity->getOffset());
2225 if (Asm->isVerbose())
2226 Asm->OutStreamer.AddComment("External Name");
2227 Asm->OutStreamer.EmitBytes(StringRef(Name, strlen(Name)+1), 0);
2230 Asm->OutStreamer.AddComment("End Mark");
2232 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2236 void DwarfDebug::emitDebugPubTypes() {
2237 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2238 E = CUMap.end(); I != E; ++I) {
2239 CompileUnit *TheCU = I->second;
2240 // Start the dwarf pubtypes section.
2241 Asm->OutStreamer.SwitchSection(
2242 Asm->getObjFileLowering().getDwarfPubTypesSection());
2243 Asm->OutStreamer.AddComment("Length of Public Types Info");
2244 Asm->EmitLabelDifference(
2245 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2246 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2248 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2249 TheCU->getUniqueID()));
2251 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2252 Asm->EmitInt16(dwarf::DWARF_VERSION);
2254 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2255 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2256 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2257 TheCU->getUniqueID()),
2258 DwarfInfoSectionSym);
2260 Asm->OutStreamer.AddComment("Compilation Unit Length");
2261 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2262 TheCU->getUniqueID()),
2263 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2264 TheCU->getUniqueID()),
2267 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2268 for (StringMap<DIE*>::const_iterator
2269 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2270 const char *Name = GI->getKeyData();
2271 DIE *Entity = GI->second;
2273 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2274 Asm->EmitInt32(Entity->getOffset());
2276 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2277 // Emit the name with a terminating null byte.
2278 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2281 Asm->OutStreamer.AddComment("End Mark");
2283 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2284 TheCU->getUniqueID()));
2288 // Emit strings into a string section.
2289 void DwarfUnits::emitStrings(const MCSection *StrSection,
2290 const MCSection *OffsetSection = NULL,
2291 const MCSymbol *StrSecSym = NULL) {
2293 if (StringPool.empty()) return;
2295 // Start the dwarf str section.
2296 Asm->OutStreamer.SwitchSection(StrSection);
2298 // Get all of the string pool entries and put them in an array by their ID so
2299 // we can sort them.
2300 SmallVector<std::pair<unsigned,
2301 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2303 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2304 I = StringPool.begin(), E = StringPool.end();
2306 Entries.push_back(std::make_pair(I->second.second, &*I));
2308 array_pod_sort(Entries.begin(), Entries.end());
2310 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2311 // Emit a label for reference from debug information entries.
2312 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2314 // Emit the string itself with a terminating null byte.
2315 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2316 Entries[i].second->getKeyLength()+1));
2319 // If we've got an offset section go ahead and emit that now as well.
2320 if (OffsetSection) {
2321 Asm->OutStreamer.SwitchSection(OffsetSection);
2322 unsigned offset = 0;
2323 unsigned size = 4; // FIXME: DWARF64 is 8.
2324 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2325 Asm->OutStreamer.EmitIntValue(offset, size);
2326 offset += Entries[i].second->getKeyLength() + 1;
2331 // Emit strings into a string section.
2332 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2334 if (AddressPool.empty()) return;
2336 // Start the dwarf addr section.
2337 Asm->OutStreamer.SwitchSection(AddrSection);
2339 // Get all of the string pool entries and put them in an array by their ID so
2340 // we can sort them.
2341 SmallVector<std::pair<unsigned,
2342 std::pair<MCSymbol*, unsigned>* >, 64> Entries;
2344 for (DenseMap<MCSymbol*, std::pair<MCSymbol*, unsigned> >::iterator
2345 I = AddressPool.begin(), E = AddressPool.end();
2347 Entries.push_back(std::make_pair(I->second.second, &(I->second)));
2349 array_pod_sort(Entries.begin(), Entries.end());
2351 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2352 // Emit a label for reference from debug information entries.
2353 MCSymbol *Sym = Entries[i].second->first;
2355 Asm->EmitLabelReference(Entries[i].second->first,
2356 Asm->getDataLayout().getPointerSize());
2358 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2363 // Emit visible names into a debug str section.
2364 void DwarfDebug::emitDebugStr() {
2365 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2366 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2369 // Emit visible names into a debug loc section.
2370 void DwarfDebug::emitDebugLoc() {
2371 if (DotDebugLocEntries.empty())
2374 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2375 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2377 DotDebugLocEntry &Entry = *I;
2378 if (I + 1 != DotDebugLocEntries.end())
2382 // Start the dwarf loc section.
2383 Asm->OutStreamer.SwitchSection(
2384 Asm->getObjFileLowering().getDwarfLocSection());
2385 unsigned char Size = Asm->getDataLayout().getPointerSize();
2386 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2388 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2389 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2390 I != E; ++I, ++index) {
2391 DotDebugLocEntry &Entry = *I;
2392 if (Entry.isMerged()) continue;
2393 if (Entry.isEmpty()) {
2394 Asm->OutStreamer.EmitIntValue(0, Size);
2395 Asm->OutStreamer.EmitIntValue(0, Size);
2396 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2398 Asm->OutStreamer.EmitSymbolValue(Entry.Begin, Size);
2399 Asm->OutStreamer.EmitSymbolValue(Entry.End, Size);
2400 DIVariable DV(Entry.Variable);
2401 Asm->OutStreamer.AddComment("Loc expr size");
2402 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2403 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2404 Asm->EmitLabelDifference(end, begin, 2);
2405 Asm->OutStreamer.EmitLabel(begin);
2406 if (Entry.isInt()) {
2407 DIBasicType BTy(DV.getType());
2409 (BTy.getEncoding() == dwarf::DW_ATE_signed
2410 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2411 Asm->OutStreamer.AddComment("DW_OP_consts");
2412 Asm->EmitInt8(dwarf::DW_OP_consts);
2413 Asm->EmitSLEB128(Entry.getInt());
2415 Asm->OutStreamer.AddComment("DW_OP_constu");
2416 Asm->EmitInt8(dwarf::DW_OP_constu);
2417 Asm->EmitULEB128(Entry.getInt());
2419 } else if (Entry.isLocation()) {
2420 if (!DV.hasComplexAddress())
2422 Asm->EmitDwarfRegOp(Entry.Loc);
2424 // Complex address entry.
2425 unsigned N = DV.getNumAddrElements();
2427 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2428 if (Entry.Loc.getOffset()) {
2430 Asm->EmitDwarfRegOp(Entry.Loc);
2431 Asm->OutStreamer.AddComment("DW_OP_deref");
2432 Asm->EmitInt8(dwarf::DW_OP_deref);
2433 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2434 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2435 Asm->EmitSLEB128(DV.getAddrElement(1));
2437 // If first address element is OpPlus then emit
2438 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2439 MachineLocation Loc(Entry.Loc.getReg(), DV.getAddrElement(1));
2440 Asm->EmitDwarfRegOp(Loc);
2444 Asm->EmitDwarfRegOp(Entry.Loc);
2447 // Emit remaining complex address elements.
2448 for (; i < N; ++i) {
2449 uint64_t Element = DV.getAddrElement(i);
2450 if (Element == DIBuilder::OpPlus) {
2451 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2452 Asm->EmitULEB128(DV.getAddrElement(++i));
2453 } else if (Element == DIBuilder::OpDeref) {
2454 if (!Entry.Loc.isReg())
2455 Asm->EmitInt8(dwarf::DW_OP_deref);
2457 llvm_unreachable("unknown Opcode found in complex address");
2461 // else ... ignore constant fp. There is not any good way to
2462 // to represent them here in dwarf.
2463 Asm->OutStreamer.EmitLabel(end);
2468 // Emit visible names into a debug aranges section.
2469 void DwarfDebug::emitDebugARanges() {
2470 // Start the dwarf aranges section.
2471 Asm->OutStreamer.SwitchSection(
2472 Asm->getObjFileLowering().getDwarfARangesSection());
2475 // Emit visible names into a debug ranges section.
2476 void DwarfDebug::emitDebugRanges() {
2477 // Start the dwarf ranges section.
2478 Asm->OutStreamer.SwitchSection(
2479 Asm->getObjFileLowering().getDwarfRangesSection());
2480 unsigned char Size = Asm->getDataLayout().getPointerSize();
2481 for (SmallVectorImpl<const MCSymbol *>::iterator
2482 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2485 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2487 Asm->OutStreamer.EmitIntValue(0, Size);
2491 // Emit visible names into a debug macinfo section.
2492 void DwarfDebug::emitDebugMacInfo() {
2493 if (const MCSection *LineInfo =
2494 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2495 // Start the dwarf macinfo section.
2496 Asm->OutStreamer.SwitchSection(LineInfo);
2500 // Emit inline info using following format.
2502 // 1. length of section
2503 // 2. Dwarf version number
2506 // Entries (one "entry" for each function that was inlined):
2508 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2509 // otherwise offset into __debug_str for regular function name.
2510 // 2. offset into __debug_str section for regular function name.
2511 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2512 // instances for the function.
2514 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2515 // inlined instance; the die_offset points to the inlined_subroutine die in the
2516 // __debug_info section, and the low_pc is the starting address for the
2517 // inlining instance.
2518 void DwarfDebug::emitDebugInlineInfo() {
2519 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2525 Asm->OutStreamer.SwitchSection(
2526 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2528 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2529 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2530 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2532 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2534 Asm->OutStreamer.AddComment("Dwarf Version");
2535 Asm->EmitInt16(dwarf::DWARF_VERSION);
2536 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2537 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2539 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2540 E = InlinedSPNodes.end(); I != E; ++I) {
2542 const MDNode *Node = *I;
2543 DenseMap<const MDNode *, SmallVector<InlineInfoLabels, 4> >::iterator II
2544 = InlineInfo.find(Node);
2545 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2546 DISubprogram SP(Node);
2547 StringRef LName = SP.getLinkageName();
2548 StringRef Name = SP.getName();
2550 Asm->OutStreamer.AddComment("MIPS linkage name");
2552 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2553 DwarfStrSectionSym);
2555 Asm->EmitSectionOffset(InfoHolder
2556 .getStringPoolEntry(getRealLinkageName(LName)),
2557 DwarfStrSectionSym);
2559 Asm->OutStreamer.AddComment("Function name");
2560 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2561 DwarfStrSectionSym);
2562 Asm->EmitULEB128(Labels.size(), "Inline count");
2564 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2565 LE = Labels.end(); LI != LE; ++LI) {
2566 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2567 Asm->EmitInt32(LI->second->getOffset());
2569 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2570 Asm->OutStreamer.EmitSymbolValue(LI->first,
2571 Asm->getDataLayout().getPointerSize());
2575 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2578 // DWARF5 Experimental Separate Dwarf emitters.
2580 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2581 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2582 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2583 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2584 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2585 DICompileUnit DIUnit(N);
2586 CompilationDir = DIUnit.getDirectory();
2588 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2589 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2590 DIUnit.getLanguage(), Die, Asm,
2591 this, &SkeletonHolder);
2593 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2594 DIUnit.getSplitDebugFilename());
2596 // This should be a unique identifier when we want to build .dwp files.
2597 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2599 // Relocate to the beginning of the addr_base section, else 0 for the
2600 // beginning of the one for this compile unit.
2601 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2602 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2603 DwarfAddrSectionSym);
2605 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2606 dwarf::DW_FORM_sec_offset, 0);
2608 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2609 // into an entity. We're using 0, or a NULL label for this.
2610 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2612 // DW_AT_stmt_list is a offset of line number information for this
2613 // compile unit in debug_line section.
2614 // FIXME: Should handle multiple compile units.
2615 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2616 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2617 DwarfLineSectionSym);
2619 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2621 if (!CompilationDir.empty())
2622 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2624 SkeletonHolder.addUnit(NewCU);
2625 SkeletonCUs.push_back(NewCU);
2630 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2631 assert(useSplitDwarf() && "No split dwarf debug info?");
2632 emitAbbrevs(Section, &SkeletonAbbrevs);
2635 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2636 // compile units that would normally be in debug_info.
2637 void DwarfDebug::emitDebugInfoDWO() {
2638 assert(useSplitDwarf() && "No split dwarf debug info?");
2639 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2640 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2641 DwarfAbbrevDWOSectionSym);
2644 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2645 // abbreviations for the .debug_info.dwo section.
2646 void DwarfDebug::emitDebugAbbrevDWO() {
2647 assert(useSplitDwarf() && "No split dwarf?");
2648 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2652 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2653 // string section and is identical in format to traditional .debug_str
2655 void DwarfDebug::emitDebugStrDWO() {
2656 assert(useSplitDwarf() && "No split dwarf?");
2657 const MCSection *OffSec = Asm->getObjFileLowering()
2658 .getDwarfStrOffDWOSection();
2659 const MCSymbol *StrSym = DwarfStrSectionSym;
2660 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),