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"
18 #include "DwarfAccelTable.h"
19 #include "DwarfCompileUnit.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Triple.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/DIBuilder.h"
27 #include "llvm/DebugInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCSection.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/MD5.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/Timer.h"
43 #include "llvm/Support/ValueHandle.h"
44 #include "llvm/Target/TargetFrameLowering.h"
45 #include "llvm/Target/TargetLoweringObjectFile.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
48 #include "llvm/Target/TargetRegisterInfo.h"
52 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
53 cl::desc("Disable debug info printing"));
55 static cl::opt<bool> UnknownLocations(
56 "use-unknown-locations", cl::Hidden,
57 cl::desc("Make an absence of debug location information explicit."),
61 GenerateDwarfPubNamesSection("generate-dwarf-pubnames", cl::Hidden,
63 cl::desc("Generate DWARF pubnames section"));
66 GenerateODRHash("generate-odr-hash", cl::Hidden,
67 cl::desc("Add an ODR hash to external type DIEs."),
78 static cl::opt<DefaultOnOff>
79 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
80 cl::desc("Output prototype dwarf accelerator tables."),
81 cl::values(clEnumVal(Default, "Default for platform"),
82 clEnumVal(Enable, "Enabled"),
83 clEnumVal(Disable, "Disabled"), clEnumValEnd),
86 static cl::opt<DefaultOnOff>
87 DarwinGDBCompat("darwin-gdb-compat", cl::Hidden,
88 cl::desc("Compatibility with Darwin gdb."),
89 cl::values(clEnumVal(Default, "Default for platform"),
90 clEnumVal(Enable, "Enabled"),
91 clEnumVal(Disable, "Disabled"), clEnumValEnd),
94 static cl::opt<DefaultOnOff>
95 SplitDwarf("split-dwarf", cl::Hidden,
96 cl::desc("Output prototype dwarf split debug info."),
97 cl::values(clEnumVal(Default, "Default for platform"),
98 clEnumVal(Enable, "Enabled"),
99 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 const char *const DWARFGroupName = "DWARF Emission";
104 const char *const DbgTimerName = "DWARF Debug Writer";
106 struct CompareFirst {
107 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
108 return lhs.first < rhs.first;
111 } // end anonymous namespace
113 //===----------------------------------------------------------------------===//
115 // Configuration values for initial hash set sizes (log2).
117 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
121 DIType DbgVariable::getType() const {
122 DIType Ty = Var.getType();
123 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
124 // addresses instead.
125 if (Var.isBlockByrefVariable()) {
126 /* Byref variables, in Blocks, are declared by the programmer as
127 "SomeType VarName;", but the compiler creates a
128 __Block_byref_x_VarName struct, and gives the variable VarName
129 either the struct, or a pointer to the struct, as its type. This
130 is necessary for various behind-the-scenes things the compiler
131 needs to do with by-reference variables in blocks.
133 However, as far as the original *programmer* is concerned, the
134 variable should still have type 'SomeType', as originally declared.
136 The following function dives into the __Block_byref_x_VarName
137 struct to find the original type of the variable. This will be
138 passed back to the code generating the type for the Debug
139 Information Entry for the variable 'VarName'. 'VarName' will then
140 have the original type 'SomeType' in its debug information.
142 The original type 'SomeType' will be the type of the field named
143 'VarName' inside the __Block_byref_x_VarName struct.
145 NOTE: In order for this to not completely fail on the debugger
146 side, the Debug Information Entry for the variable VarName needs to
147 have a DW_AT_location that tells the debugger how to unwind through
148 the pointers and __Block_byref_x_VarName struct to find the actual
149 value of the variable. The function addBlockByrefType does this. */
151 uint16_t tag = Ty.getTag();
153 if (tag == dwarf::DW_TAG_pointer_type) {
154 DIDerivedType DTy = DIDerivedType(Ty);
155 subType = DTy.getTypeDerivedFrom();
158 DICompositeType blockStruct = DICompositeType(subType);
159 DIArray Elements = blockStruct.getTypeArray();
161 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
162 DIDescriptor Element = Elements.getElement(i);
163 DIDerivedType DT = DIDerivedType(Element);
164 if (getName() == DT.getName())
165 return (DT.getTypeDerivedFrom());
171 } // end llvm namespace
173 /// Return Dwarf Version by checking module flags.
174 static unsigned getDwarfVersionFromModule(const Module *M) {
175 Value *Val = M->getModuleFlag("Dwarf Version");
177 return dwarf::DWARF_VERSION;
178 return cast<ConstantInt>(Val)->getZExtValue();
181 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
182 : Asm(A), MMI(Asm->MMI), FirstCU(0),
183 AbbreviationsSet(InitAbbreviationsSetSize),
184 SourceIdMap(DIEValueAllocator),
185 PrevLabel(NULL), GlobalCUIndexCount(0),
186 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
188 SkeletonAbbrevSet(InitAbbreviationsSetSize),
189 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
192 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
193 DwarfStrSectionSym = TextSectionSym = 0;
194 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
195 DwarfAddrSectionSym = 0;
196 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
197 FunctionBeginSym = FunctionEndSym = 0;
199 // Turn on accelerator tables and older gdb compatibility
201 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
202 if (DarwinGDBCompat == Default) {
204 IsDarwinGDBCompat = true;
206 IsDarwinGDBCompat = false;
208 IsDarwinGDBCompat = DarwinGDBCompat == Enable ? true : false;
210 if (DwarfAccelTables == Default) {
212 HasDwarfAccelTables = true;
214 HasDwarfAccelTables = false;
216 HasDwarfAccelTables = DwarfAccelTables == Enable ? true : false;
218 if (SplitDwarf == Default)
219 HasSplitDwarf = false;
221 HasSplitDwarf = SplitDwarf == Enable ? true : false;
223 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
226 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
230 DwarfDebug::~DwarfDebug() {
233 // Switch to the specified MCSection and emit an assembler
234 // temporary label to it if SymbolStem is specified.
235 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
236 const char *SymbolStem = 0) {
237 Asm->OutStreamer.SwitchSection(Section);
238 if (!SymbolStem) return 0;
240 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
241 Asm->OutStreamer.EmitLabel(TmpSym);
245 MCSymbol *DwarfUnits::getStringPoolSym() {
246 return Asm->GetTempSymbol(StringPref);
249 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
250 std::pair<MCSymbol*, unsigned> &Entry =
251 StringPool.GetOrCreateValue(Str).getValue();
252 if (Entry.first) return Entry.first;
254 Entry.second = NextStringPoolNumber++;
255 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
258 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
259 std::pair<MCSymbol*, unsigned> &Entry =
260 StringPool.GetOrCreateValue(Str).getValue();
261 if (Entry.first) return Entry.second;
263 Entry.second = NextStringPoolNumber++;
264 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
268 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
269 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
272 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
273 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
274 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
276 ++NextAddrPoolNumber;
277 return P.first->second;
280 // Define a unique number for the abbreviation.
282 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
283 // Check the set for priors.
284 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
286 // If it's newly added.
287 if (InSet == &Abbrev) {
288 // Add to abbreviation list.
289 Abbreviations->push_back(&Abbrev);
291 // Assign the vector position + 1 as its number.
292 Abbrev.setNumber(Abbreviations->size());
294 // Assign existing abbreviation number.
295 Abbrev.setNumber(InSet->getNumber());
299 static bool isObjCClass(StringRef Name) {
300 return Name.startswith("+") || Name.startswith("-");
303 static bool hasObjCCategory(StringRef Name) {
304 if (!isObjCClass(Name)) return false;
306 size_t pos = Name.find(')');
307 if (pos != std::string::npos) {
308 if (Name[pos+1] != ' ') return false;
314 static void getObjCClassCategory(StringRef In, StringRef &Class,
315 StringRef &Category) {
316 if (!hasObjCCategory(In)) {
317 Class = In.slice(In.find('[') + 1, In.find(' '));
322 Class = In.slice(In.find('[') + 1, In.find('('));
323 Category = In.slice(In.find('[') + 1, In.find(' '));
327 static StringRef getObjCMethodName(StringRef In) {
328 return In.slice(In.find(' ') + 1, In.find(']'));
331 // Add the various names to the Dwarf accelerator table names.
332 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
334 if (!SP.isDefinition()) return;
336 TheCU->addAccelName(SP.getName(), Die);
338 // If the linkage name is different than the name, go ahead and output
339 // that as well into the name table.
340 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
341 TheCU->addAccelName(SP.getLinkageName(), Die);
343 // If this is an Objective-C selector name add it to the ObjC accelerator
345 if (isObjCClass(SP.getName())) {
346 StringRef Class, Category;
347 getObjCClassCategory(SP.getName(), Class, Category);
348 TheCU->addAccelObjC(Class, Die);
350 TheCU->addAccelObjC(Category, Die);
351 // Also add the base method name to the name table.
352 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
356 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
357 // and DW_AT_high_pc attributes. If there are global variables in this
358 // scope then create and insert DIEs for these variables.
359 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
360 const MDNode *SPNode) {
361 DIE *SPDie = SPCU->getDIE(SPNode);
363 assert(SPDie && "Unable to find subprogram DIE!");
364 DISubprogram SP(SPNode);
366 // If we're updating an abstract DIE, then we will be adding the children and
367 // object pointer later on. But what we don't want to do is process the
368 // concrete DIE twice.
369 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
371 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
372 // Pick up abstract subprogram DIE.
373 SPDie = new DIE(dwarf::DW_TAG_subprogram);
374 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
376 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
377 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
381 DISubprogram SPDecl = SP.getFunctionDeclaration();
382 if (!SPDecl.isSubprogram()) {
383 // There is not any need to generate specification DIE for a function
384 // defined at compile unit level. If a function is defined inside another
385 // function then gdb prefers the definition at top level and but does not
386 // expect specification DIE in parent function. So avoid creating
387 // specification DIE for a function defined inside a function.
388 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
389 !SP.getContext().isFile() &&
390 !isSubprogramContext(SP.getContext())) {
391 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
394 DICompositeType SPTy = SP.getType();
395 DIArray Args = SPTy.getTypeArray();
396 uint16_t SPTag = SPTy.getTag();
397 if (SPTag == dwarf::DW_TAG_subroutine_type)
398 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
399 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
400 DIType ATy = DIType(Args.getElement(i));
401 SPCU->addType(Arg, ATy);
402 if (ATy.isArtificial())
403 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
404 if (ATy.isObjectPointer())
405 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
406 dwarf::DW_FORM_ref4, Arg);
407 SPDie->addChild(Arg);
409 DIE *SPDeclDie = SPDie;
410 SPDie = new DIE(dwarf::DW_TAG_subprogram);
411 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
412 dwarf::DW_FORM_ref4, SPDeclDie);
418 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
419 Asm->GetTempSymbol("func_begin",
420 Asm->getFunctionNumber()));
421 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
422 Asm->GetTempSymbol("func_end",
423 Asm->getFunctionNumber()));
424 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
425 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
426 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
428 // Add name to the name table, we do this here because we're guaranteed
429 // to have concrete versions of our DW_TAG_subprogram nodes.
430 addSubprogramNames(SPCU, SP, SPDie);
435 // Construct new DW_TAG_lexical_block for this scope and attach
436 // DW_AT_low_pc/DW_AT_high_pc labels.
437 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
438 LexicalScope *Scope) {
439 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
440 if (Scope->isAbstractScope())
443 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
447 // If we have multiple ranges, emit them into the range section.
448 if (Ranges.size() > 1) {
449 // .debug_range section has not been laid out yet. Emit offset in
450 // .debug_range as a uint, size 4, for now. emitDIE will handle
451 // DW_AT_ranges appropriately.
452 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
453 DebugRangeSymbols.size()
454 * Asm->getDataLayout().getPointerSize());
455 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
456 RE = Ranges.end(); RI != RE; ++RI) {
457 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
458 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
461 // Terminate the range list.
462 DebugRangeSymbols.push_back(NULL);
463 DebugRangeSymbols.push_back(NULL);
467 // Construct the address range for this DIE.
468 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
469 MCSymbol *Start = getLabelBeforeInsn(RI->first);
470 MCSymbol *End = getLabelAfterInsn(RI->second);
472 if (End == 0) return 0;
474 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
475 assert(End->isDefined() && "Invalid end label for an inlined scope!");
477 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
478 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
483 // This scope represents inlined body of a function. Construct DIE to
484 // represent this concrete inlined copy of the function.
485 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
486 LexicalScope *Scope) {
487 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
488 assert(Ranges.empty() == false &&
489 "LexicalScope does not have instruction markers!");
491 if (!Scope->getScopeNode())
493 DIScope DS(Scope->getScopeNode());
494 DISubprogram InlinedSP = getDISubprogram(DS);
495 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
497 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
501 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
502 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
503 dwarf::DW_FORM_ref4, OriginDIE);
505 if (Ranges.size() > 1) {
506 // .debug_range section has not been laid out yet. Emit offset in
507 // .debug_range as a uint, size 4, for now. emitDIE will handle
508 // DW_AT_ranges appropriately.
509 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
510 DebugRangeSymbols.size()
511 * Asm->getDataLayout().getPointerSize());
512 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
513 RE = Ranges.end(); RI != RE; ++RI) {
514 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
515 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
517 DebugRangeSymbols.push_back(NULL);
518 DebugRangeSymbols.push_back(NULL);
520 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
521 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
522 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
524 if (StartLabel == 0 || EndLabel == 0)
525 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
527 assert(StartLabel->isDefined() &&
528 "Invalid starting label for an inlined scope!");
529 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
531 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
532 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
535 InlinedSubprogramDIEs.insert(OriginDIE);
537 // Add the call site information to the DIE.
538 DILocation DL(Scope->getInlinedAt());
539 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
540 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
541 TheCU->getUniqueID()));
542 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
544 // Track the start label for this inlined function.
545 //.debug_inlined section specification does not clearly state how
546 // to emit inlined scopes that are split into multiple instruction ranges.
547 // For now, use the first instruction range and emit low_pc/high_pc pair and
548 // corresponding the .debug_inlined section entry for this pair.
549 if (Asm->MAI->doesDwarfUseInlineInfoSection()) {
550 MCSymbol *StartLabel = getLabelBeforeInsn(Ranges.begin()->first);
551 InlineInfoMap::iterator I = InlineInfo.find(InlinedSP);
553 if (I == InlineInfo.end()) {
554 InlineInfo[InlinedSP].push_back(std::make_pair(StartLabel, ScopeDIE));
555 InlinedSPNodes.push_back(InlinedSP);
557 I->second.push_back(std::make_pair(StartLabel, ScopeDIE));
560 // Add name to the name table, we do this here because we're guaranteed
561 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
562 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
567 // Construct a DIE for this scope.
568 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
569 if (!Scope || !Scope->getScopeNode())
572 DIScope DS(Scope->getScopeNode());
573 // Early return to avoid creating dangling variable|scope DIEs.
574 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
578 SmallVector<DIE *, 8> Children;
579 DIE *ObjectPointer = NULL;
581 // Collect arguments for current function.
582 if (LScopes.isCurrentFunctionScope(Scope))
583 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
584 if (DbgVariable *ArgDV = CurrentFnArguments[i])
586 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
587 Children.push_back(Arg);
588 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
591 // Collect lexical scope children first.
592 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
593 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
595 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
596 Children.push_back(Variable);
597 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
599 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
600 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
601 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
602 Children.push_back(Nested);
603 DIE *ScopeDIE = NULL;
604 if (Scope->getInlinedAt())
605 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
606 else if (DS.isSubprogram()) {
607 ProcessedSPNodes.insert(DS);
608 if (Scope->isAbstractScope()) {
609 ScopeDIE = TheCU->getDIE(DS);
610 // Note down abstract DIE.
612 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
615 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
618 // There is no need to emit empty lexical block DIE.
619 std::pair<ImportedEntityMap::const_iterator,
620 ImportedEntityMap::const_iterator> Range = std::equal_range(
621 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
622 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
624 if (Children.empty() && Range.first == Range.second)
626 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
627 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
629 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
632 if (!ScopeDIE) return NULL;
635 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
636 E = Children.end(); I != E; ++I)
637 ScopeDIE->addChild(*I);
639 if (DS.isSubprogram() && ObjectPointer != NULL)
640 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
641 dwarf::DW_FORM_ref4, ObjectPointer);
643 if (DS.isSubprogram())
644 TheCU->addPubTypes(DISubprogram(DS));
649 // Look up the source id with the given directory and source file names.
650 // If none currently exists, create a new id and insert it in the
651 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
653 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
654 StringRef DirName, unsigned CUID) {
655 // If we use .loc in assembly, we can't separate .file entries according to
656 // compile units. Thus all files will belong to the default compile unit.
657 if (Asm->TM.hasMCUseLoc() &&
658 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
661 // If FE did not provide a file name, then assume stdin.
662 if (FileName.empty())
663 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
665 // TODO: this might not belong here. See if we can factor this better.
666 if (DirName == CompilationDir)
669 // FileIDCUMap stores the current ID for the given compile unit.
670 unsigned SrcId = FileIDCUMap[CUID] + 1;
672 // We look up the CUID/file/dir by concatenating them with a zero byte.
673 SmallString<128> NamePair;
674 NamePair += utostr(CUID);
677 NamePair += '\0'; // Zero bytes are not allowed in paths.
678 NamePair += FileName;
680 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
681 if (Ent.getValue() != SrcId)
682 return Ent.getValue();
684 FileIDCUMap[CUID] = SrcId;
685 // Print out a .file directive to specify files for .loc directives.
686 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
691 // Create new CompileUnit for the given metadata node with tag
692 // DW_TAG_compile_unit.
693 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
694 DICompileUnit DIUnit(N);
695 StringRef FN = DIUnit.getFilename();
696 CompilationDir = DIUnit.getDirectory();
698 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
699 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
700 DIUnit.getLanguage(), Die, N, Asm,
703 FileIDCUMap[NewCU->getUniqueID()] = 0;
704 // Call this to emit a .file directive if it wasn't emitted for the source
705 // file this CU comes from yet.
706 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
708 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
709 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
710 DIUnit.getLanguage());
711 NewCU->addString(Die, dwarf::DW_AT_name, FN);
713 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
714 // into an entity. We're using 0 (or a NULL label) for this. For
715 // split dwarf it's in the skeleton CU so omit it here.
716 if (!useSplitDwarf())
717 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
719 // Define start line table label for each Compile Unit.
720 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
721 NewCU->getUniqueID());
722 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
723 NewCU->getUniqueID());
725 // Use a single line table if we are using .loc and generating assembly.
727 (Asm->TM.hasMCUseLoc() &&
728 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
729 (NewCU->getUniqueID() == 0);
731 // DW_AT_stmt_list is a offset of line number information for this
732 // compile unit in debug_line section. For split dwarf this is
733 // left in the skeleton CU and so not included.
734 // The line table entries are not always emitted in assembly, so it
735 // is not okay to use line_table_start here.
736 if (!useSplitDwarf()) {
737 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
738 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
740 Asm->GetTempSymbol("section_line") : LineTableStartSym);
741 else if (UseTheFirstCU)
742 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
744 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
745 LineTableStartSym, DwarfLineSectionSym);
748 // If we're using split dwarf the compilation dir is going to be in the
749 // skeleton CU and so we don't need to duplicate it here.
750 if (!useSplitDwarf() && !CompilationDir.empty())
751 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
752 if (DIUnit.isOptimized())
753 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
755 StringRef Flags = DIUnit.getFlags();
757 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
759 if (unsigned RVer = DIUnit.getRunTimeVersion())
760 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
761 dwarf::DW_FORM_data1, RVer);
766 InfoHolder.addUnit(NewCU);
768 CUMap.insert(std::make_pair(N, NewCU));
772 // Construct subprogram DIE.
773 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
775 CompileUnit *&CURef = SPMap[N];
781 if (!SP.isDefinition())
782 // This is a method declaration which will be handled while constructing
786 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
789 TheCU->insertDIE(N, SubprogramDie);
791 // Add to context owner.
792 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
794 // Expose as global, if requested.
795 if (GenerateDwarfPubNamesSection)
796 TheCU->addGlobalName(SP.getName(), SubprogramDie);
799 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
801 DIImportedEntity Module(N);
802 if (!Module.Verify())
804 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
805 constructImportedEntityDIE(TheCU, Module, D);
808 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
810 DIImportedEntity Module(N);
811 if (!Module.Verify())
813 return constructImportedEntityDIE(TheCU, Module, Context);
816 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
817 const DIImportedEntity &Module,
819 assert(Module.Verify() &&
820 "Use one of the MDNode * overloads to handle invalid metadata");
821 assert(Context && "Should always have a context for an imported_module");
822 DIE *IMDie = new DIE(Module.getTag());
823 TheCU->insertDIE(Module, IMDie);
825 DIDescriptor Entity = Module.getEntity();
826 if (Entity.isNameSpace())
827 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
828 else if (Entity.isSubprogram())
829 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
830 else if (Entity.isType())
831 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
833 EntityDie = TheCU->getDIE(Entity);
834 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
835 Module.getContext().getDirectory(),
836 TheCU->getUniqueID());
837 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
838 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
839 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
841 StringRef Name = Module.getName();
843 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
844 Context->addChild(IMDie);
847 // Emit all Dwarf sections that should come prior to the content. Create
848 // global DIEs and emit initial debug info sections. This is invoked by
849 // the target AsmPrinter.
850 void DwarfDebug::beginModule() {
851 if (DisableDebugInfoPrinting)
854 const Module *M = MMI->getModule();
856 // If module has named metadata anchors then use them, otherwise scan the
857 // module using debug info finder to collect debug info.
858 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
862 // Emit initial sections so we can reference labels later.
865 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
866 DICompileUnit CUNode(CU_Nodes->getOperand(i));
867 CompileUnit *CU = constructCompileUnit(CUNode);
868 DIArray ImportedEntities = CUNode.getImportedEntities();
869 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
870 ScopesWithImportedEntities.push_back(std::make_pair(
871 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
872 ImportedEntities.getElement(i)));
873 std::sort(ScopesWithImportedEntities.begin(),
874 ScopesWithImportedEntities.end(), CompareFirst());
875 DIArray GVs = CUNode.getGlobalVariables();
876 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
877 CU->createGlobalVariableDIE(GVs.getElement(i));
878 DIArray SPs = CUNode.getSubprograms();
879 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
880 constructSubprogramDIE(CU, SPs.getElement(i));
881 DIArray EnumTypes = CUNode.getEnumTypes();
882 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
883 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
884 DIArray RetainedTypes = CUNode.getRetainedTypes();
885 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
886 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
887 // Emit imported_modules last so that the relevant context is already
889 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
890 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
891 // If we're splitting the dwarf out now that we've got the entire
892 // CU then construct a skeleton CU based upon it.
893 if (useSplitDwarf()) {
894 // This should be a unique identifier when we want to build .dwp files.
895 CU->addUInt(CU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
896 dwarf::DW_FORM_data8, 0);
897 // Now construct the skeleton CU associated.
898 constructSkeletonCU(CUNode);
902 // Tell MMI that we have debug info.
903 MMI->setDebugInfoAvailability(true);
905 // Prime section data.
906 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
909 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
910 void DwarfDebug::computeInlinedDIEs() {
911 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
912 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
913 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
915 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
917 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
918 AE = AbstractSPDies.end(); AI != AE; ++AI) {
919 DIE *ISP = AI->second;
920 if (InlinedSubprogramDIEs.count(ISP))
922 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
926 // Collect info for variables that were optimized out.
927 void DwarfDebug::collectDeadVariables() {
928 const Module *M = MMI->getModule();
929 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
931 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
932 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
933 DICompileUnit TheCU(CU_Nodes->getOperand(i));
934 DIArray Subprograms = TheCU.getSubprograms();
935 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
936 DISubprogram SP(Subprograms.getElement(i));
937 if (ProcessedSPNodes.count(SP) != 0) continue;
938 if (!SP.isSubprogram()) continue;
939 if (!SP.isDefinition()) continue;
940 DIArray Variables = SP.getVariables();
941 if (Variables.getNumElements() == 0) continue;
943 LexicalScope *Scope =
944 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
945 DeadFnScopeMap[SP] = Scope;
947 // Construct subprogram DIE and add variables DIEs.
948 CompileUnit *SPCU = CUMap.lookup(TheCU);
949 assert(SPCU && "Unable to find Compile Unit!");
950 constructSubprogramDIE(SPCU, SP);
951 DIE *ScopeDIE = SPCU->getDIE(SP);
952 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
953 DIVariable DV(Variables.getElement(vi));
954 if (!DV.isVariable()) continue;
955 DbgVariable NewVar(DV, NULL);
956 if (DIE *VariableDIE =
957 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
958 ScopeDIE->addChild(VariableDIE);
963 DeleteContainerSeconds(DeadFnScopeMap);
966 // Type Signature [7.27] and ODR Hash code.
968 /// \brief Grabs the string in whichever attribute is passed in and returns
969 /// a reference to it. Returns "" if the attribute doesn't exist.
970 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
971 DIEValue *V = Die->findAttribute(Attr);
973 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
974 return S->getString();
976 return StringRef("");
979 /// Return true if the current DIE is contained within an anonymous namespace.
980 static bool isContainedInAnonNamespace(DIE *Die) {
981 DIE *Parent = Die->getParent();
984 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
985 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
987 Parent = Parent->getParent();
993 /// Test if the current CU language is C++ and that we have
994 /// a named type that is not contained in an anonymous namespace.
995 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
996 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
997 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
998 !isContainedInAnonNamespace(Die);
1001 void DwarfDebug::finalizeModuleInfo() {
1002 // Collect info for variables that were optimized out.
1003 collectDeadVariables();
1005 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
1006 computeInlinedDIEs();
1008 // Emit DW_AT_containing_type attribute to connect types with their
1009 // vtable holding type.
1010 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
1011 CUE = CUMap.end(); CUI != CUE; ++CUI) {
1012 CompileUnit *TheCU = CUI->second;
1013 TheCU->constructContainingTypeDIEs();
1016 // Split out type units and conditionally add an ODR tag to the split
1018 // FIXME: Do type splitting.
1019 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
1020 DIE *Die = TypeUnits[i];
1022 // If we've requested ODR hashes and it's applicable for an ODR hash then
1023 // add the ODR signature now.
1024 // FIXME: This should be added onto the type unit, not the type, but this
1025 // works as an intermediate stage.
1026 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
1027 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
1028 dwarf::DW_FORM_data8,
1029 Hash.computeDIEODRSignature(Die));
1032 // Compute DIE offsets and sizes.
1033 InfoHolder.computeSizeAndOffsets();
1034 if (useSplitDwarf())
1035 SkeletonHolder.computeSizeAndOffsets();
1038 void DwarfDebug::endSections() {
1039 // Standard sections final addresses.
1040 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1041 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1042 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1043 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1045 // End text sections.
1046 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1047 Asm->OutStreamer.SwitchSection(SectionMap[I]);
1048 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1052 // Emit all Dwarf sections that should come after the content.
1053 void DwarfDebug::endModule() {
1055 if (!FirstCU) return;
1057 // End any existing sections.
1058 // TODO: Does this need to happen?
1061 // Finalize the debug info for the module.
1062 finalizeModuleInfo();
1064 if (!useSplitDwarf()) {
1065 // Emit all the DIEs into a debug info section.
1068 // Corresponding abbreviations into a abbrev section.
1069 emitAbbreviations();
1071 // Emit info into a debug loc section.
1074 // Emit info into a debug aranges section.
1077 // Emit info into a debug ranges section.
1080 // Emit info into a debug macinfo section.
1083 // Emit inline info.
1084 // TODO: When we don't need the option anymore we
1085 // can remove all of the code that this section
1087 if (useDarwinGDBCompat())
1088 emitDebugInlineInfo();
1090 // TODO: Fill this in for separated debug sections and separate
1091 // out information into new sections.
1093 // Emit the debug info section and compile units.
1097 // Corresponding abbreviations into a abbrev section.
1098 emitAbbreviations();
1099 emitDebugAbbrevDWO();
1101 // Emit info into a debug loc section.
1104 // Emit info into a debug aranges section.
1107 // Emit info into a debug ranges section.
1110 // Emit info into a debug macinfo section.
1113 // Emit DWO addresses.
1114 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1116 // Emit inline info.
1117 // TODO: When we don't need the option anymore we
1118 // can remove all of the code that this section
1120 if (useDarwinGDBCompat())
1121 emitDebugInlineInfo();
1124 // Emit info into the dwarf accelerator table sections.
1125 if (useDwarfAccelTables()) {
1128 emitAccelNamespaces();
1132 // Emit info into a debug pubnames section, if requested.
1133 if (GenerateDwarfPubNamesSection)
1134 emitDebugPubnames();
1136 // Emit info into a debug pubtypes section.
1137 // TODO: When we don't need the option anymore we can
1138 // remove all of the code that adds to the table.
1139 if (useDarwinGDBCompat())
1140 emitDebugPubTypes();
1142 // Finally emit string information into a string table.
1144 if (useSplitDwarf())
1149 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1150 E = CUMap.end(); I != E; ++I)
1153 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1154 E = SkeletonCUs.end(); I != E; ++I)
1157 // Reset these for the next Module if we have one.
1161 // Find abstract variable, if any, associated with Var.
1162 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1163 DebugLoc ScopeLoc) {
1164 LLVMContext &Ctx = DV->getContext();
1165 // More then one inlined variable corresponds to one abstract variable.
1166 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1167 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1169 return AbsDbgVariable;
1171 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1175 AbsDbgVariable = new DbgVariable(Var, NULL);
1176 addScopeVariable(Scope, AbsDbgVariable);
1177 AbstractVariables[Var] = AbsDbgVariable;
1178 return AbsDbgVariable;
1181 // If Var is a current function argument then add it to CurrentFnArguments list.
1182 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1183 DbgVariable *Var, LexicalScope *Scope) {
1184 if (!LScopes.isCurrentFunctionScope(Scope))
1186 DIVariable DV = Var->getVariable();
1187 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1189 unsigned ArgNo = DV.getArgNumber();
1193 size_t Size = CurrentFnArguments.size();
1195 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1196 // llvm::Function argument size is not good indicator of how many
1197 // arguments does the function have at source level.
1199 CurrentFnArguments.resize(ArgNo * 2);
1200 CurrentFnArguments[ArgNo - 1] = Var;
1204 // Collect variable information from side table maintained by MMI.
1206 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1207 SmallPtrSet<const MDNode *, 16> &Processed) {
1208 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1209 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1210 VE = VMap.end(); VI != VE; ++VI) {
1211 const MDNode *Var = VI->first;
1213 Processed.insert(Var);
1215 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1217 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1219 // If variable scope is not found then skip this variable.
1223 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1224 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1225 RegVar->setFrameIndex(VP.first);
1226 if (!addCurrentFnArgument(MF, RegVar, Scope))
1227 addScopeVariable(Scope, RegVar);
1229 AbsDbgVariable->setFrameIndex(VP.first);
1233 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1235 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1236 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1237 return MI->getNumOperands() == 3 &&
1238 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1239 (MI->getOperand(1).isImm() ||
1240 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1243 // Get .debug_loc entry for the instruction range starting at MI.
1244 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1245 const MCSymbol *FLabel,
1246 const MCSymbol *SLabel,
1247 const MachineInstr *MI) {
1248 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1250 assert(MI->getNumOperands() == 3);
1251 if (MI->getOperand(0).isReg()) {
1252 MachineLocation MLoc;
1253 // If the second operand is an immediate, this is a
1254 // register-indirect address.
1255 if (!MI->getOperand(1).isImm())
1256 MLoc.set(MI->getOperand(0).getReg());
1258 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1259 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1261 if (MI->getOperand(0).isImm())
1262 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1263 if (MI->getOperand(0).isFPImm())
1264 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1265 if (MI->getOperand(0).isCImm())
1266 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1268 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1271 // Find variables for each lexical scope.
1273 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1274 SmallPtrSet<const MDNode *, 16> &Processed) {
1276 // Grab the variable info that was squirreled away in the MMI side-table.
1277 collectVariableInfoFromMMITable(MF, Processed);
1279 for (SmallVectorImpl<const MDNode*>::const_iterator
1280 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1282 const MDNode *Var = *UVI;
1283 if (Processed.count(Var))
1286 // History contains relevant DBG_VALUE instructions for Var and instructions
1288 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1289 if (History.empty())
1291 const MachineInstr *MInsn = History.front();
1294 LexicalScope *Scope = NULL;
1295 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1296 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1297 Scope = LScopes.getCurrentFunctionScope();
1298 else if (MDNode *IA = DV.getInlinedAt())
1299 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1301 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1302 // If variable scope is not found then skip this variable.
1306 Processed.insert(DV);
1307 assert(MInsn->isDebugValue() && "History must begin with debug value");
1308 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1309 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1310 if (!addCurrentFnArgument(MF, RegVar, Scope))
1311 addScopeVariable(Scope, RegVar);
1313 AbsVar->setMInsn(MInsn);
1315 // Simplify ranges that are fully coalesced.
1316 if (History.size() <= 1 || (History.size() == 2 &&
1317 MInsn->isIdenticalTo(History.back()))) {
1318 RegVar->setMInsn(MInsn);
1322 // Handle multiple DBG_VALUE instructions describing one variable.
1323 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1325 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1326 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1327 const MachineInstr *Begin = *HI;
1328 assert(Begin->isDebugValue() && "Invalid History entry");
1330 // Check if DBG_VALUE is truncating a range.
1331 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1332 && !Begin->getOperand(0).getReg())
1335 // Compute the range for a register location.
1336 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1337 const MCSymbol *SLabel = 0;
1340 // If Begin is the last instruction in History then its value is valid
1341 // until the end of the function.
1342 SLabel = FunctionEndSym;
1344 const MachineInstr *End = HI[1];
1345 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1346 << "\t" << *Begin << "\t" << *End << "\n");
1347 if (End->isDebugValue())
1348 SLabel = getLabelBeforeInsn(End);
1350 // End is a normal instruction clobbering the range.
1351 SLabel = getLabelAfterInsn(End);
1352 assert(SLabel && "Forgot label after clobber instruction");
1357 // The value is valid until the next DBG_VALUE or clobber.
1358 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1361 DotDebugLocEntries.push_back(DotDebugLocEntry());
1364 // Collect info for variables that were optimized out.
1365 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1366 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1367 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1368 DIVariable DV(Variables.getElement(i));
1369 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1371 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1372 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1376 // Return Label preceding the instruction.
1377 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1378 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1379 assert(Label && "Didn't insert label before instruction");
1383 // Return Label immediately following the instruction.
1384 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1385 return LabelsAfterInsn.lookup(MI);
1388 // Process beginning of an instruction.
1389 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1390 // Check if source location changes, but ignore DBG_VALUE locations.
1391 if (!MI->isDebugValue()) {
1392 DebugLoc DL = MI->getDebugLoc();
1393 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1396 if (DL == PrologEndLoc) {
1397 Flags |= DWARF2_FLAG_PROLOGUE_END;
1398 PrologEndLoc = DebugLoc();
1400 if (PrologEndLoc.isUnknown())
1401 Flags |= DWARF2_FLAG_IS_STMT;
1403 if (!DL.isUnknown()) {
1404 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1405 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1407 recordSourceLine(0, 0, 0, 0);
1411 // Insert labels where requested.
1412 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1413 LabelsBeforeInsn.find(MI);
1416 if (I == LabelsBeforeInsn.end())
1419 // Label already assigned.
1424 PrevLabel = MMI->getContext().CreateTempSymbol();
1425 Asm->OutStreamer.EmitLabel(PrevLabel);
1427 I->second = PrevLabel;
1430 // Process end of an instruction.
1431 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1432 // Don't create a new label after DBG_VALUE instructions.
1433 // They don't generate code.
1434 if (!MI->isDebugValue())
1437 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1438 LabelsAfterInsn.find(MI);
1441 if (I == LabelsAfterInsn.end())
1444 // Label already assigned.
1448 // We need a label after this instruction.
1450 PrevLabel = MMI->getContext().CreateTempSymbol();
1451 Asm->OutStreamer.EmitLabel(PrevLabel);
1453 I->second = PrevLabel;
1456 // Each LexicalScope has first instruction and last instruction to mark
1457 // beginning and end of a scope respectively. Create an inverse map that list
1458 // scopes starts (and ends) with an instruction. One instruction may start (or
1459 // end) multiple scopes. Ignore scopes that are not reachable.
1460 void DwarfDebug::identifyScopeMarkers() {
1461 SmallVector<LexicalScope *, 4> WorkList;
1462 WorkList.push_back(LScopes.getCurrentFunctionScope());
1463 while (!WorkList.empty()) {
1464 LexicalScope *S = WorkList.pop_back_val();
1466 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1467 if (!Children.empty())
1468 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1469 SE = Children.end(); SI != SE; ++SI)
1470 WorkList.push_back(*SI);
1472 if (S->isAbstractScope())
1475 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1478 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1479 RE = Ranges.end(); RI != RE; ++RI) {
1480 assert(RI->first && "InsnRange does not have first instruction!");
1481 assert(RI->second && "InsnRange does not have second instruction!");
1482 requestLabelBeforeInsn(RI->first);
1483 requestLabelAfterInsn(RI->second);
1488 // Get MDNode for DebugLoc's scope.
1489 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1490 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1491 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1492 return DL.getScope(Ctx);
1495 // Walk up the scope chain of given debug loc and find line number info
1496 // for the function.
1497 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1498 const MDNode *Scope = getScopeNode(DL, Ctx);
1499 DISubprogram SP = getDISubprogram(Scope);
1500 if (SP.isSubprogram()) {
1501 // Check for number of operands since the compatibility is
1503 if (SP->getNumOperands() > 19)
1504 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1506 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1512 // Gather pre-function debug information. Assumes being called immediately
1513 // after the function entry point has been emitted.
1514 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1515 if (!MMI->hasDebugInfo()) return;
1516 LScopes.initialize(*MF);
1517 if (LScopes.empty()) return;
1518 identifyScopeMarkers();
1520 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1522 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1523 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1524 assert(TheCU && "Unable to find compile unit!");
1525 if (Asm->TM.hasMCUseLoc() &&
1526 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1527 // Use a single line table if we are using .loc and generating assembly.
1528 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1530 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1532 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1533 Asm->getFunctionNumber());
1534 // Assumes in correct section after the entry point.
1535 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1537 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1539 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1540 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1541 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1543 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1545 bool AtBlockEntry = true;
1546 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1548 const MachineInstr *MI = II;
1550 if (MI->isDebugValue()) {
1551 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1553 // Keep track of user variables.
1555 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1557 // Variable is in a register, we need to check for clobbers.
1558 if (isDbgValueInDefinedReg(MI))
1559 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1561 // Check the history of this variable.
1562 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1563 if (History.empty()) {
1564 UserVariables.push_back(Var);
1565 // The first mention of a function argument gets the FunctionBeginSym
1566 // label, so arguments are visible when breaking at function entry.
1568 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1569 DISubprogram(getDISubprogram(DV.getContext()))
1570 .describes(MF->getFunction()))
1571 LabelsBeforeInsn[MI] = FunctionBeginSym;
1573 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1574 const MachineInstr *Prev = History.back();
1575 if (Prev->isDebugValue()) {
1576 // Coalesce identical entries at the end of History.
1577 if (History.size() >= 2 &&
1578 Prev->isIdenticalTo(History[History.size() - 2])) {
1579 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1581 << "\t" << *History[History.size() - 2] << "\n");
1585 // Terminate old register assignments that don't reach MI;
1586 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1587 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1588 isDbgValueInDefinedReg(Prev)) {
1589 // Previous register assignment needs to terminate at the end of
1591 MachineBasicBlock::const_iterator LastMI =
1592 PrevMBB->getLastNonDebugInstr();
1593 if (LastMI == PrevMBB->end()) {
1594 // Drop DBG_VALUE for empty range.
1595 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1596 << "\t" << *Prev << "\n");
1598 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1599 // Terminate after LastMI.
1600 History.push_back(LastMI);
1604 History.push_back(MI);
1606 // Not a DBG_VALUE instruction.
1608 AtBlockEntry = false;
1610 // First known non-DBG_VALUE and non-frame setup location marks
1611 // the beginning of the function body.
1612 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1613 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1614 PrologEndLoc = MI->getDebugLoc();
1616 // Check if the instruction clobbers any registers with debug vars.
1617 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1618 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1619 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1621 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1622 AI.isValid(); ++AI) {
1624 const MDNode *Var = LiveUserVar[Reg];
1627 // Reg is now clobbered.
1628 LiveUserVar[Reg] = 0;
1630 // Was MD last defined by a DBG_VALUE referring to Reg?
1631 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1632 if (HistI == DbgValues.end())
1634 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1635 if (History.empty())
1637 const MachineInstr *Prev = History.back();
1638 // Sanity-check: Register assignments are terminated at the end of
1640 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1642 // Is the variable still in Reg?
1643 if (!isDbgValueInDefinedReg(Prev) ||
1644 Prev->getOperand(0).getReg() != Reg)
1646 // Var is clobbered. Make sure the next instruction gets a label.
1647 History.push_back(MI);
1654 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1656 SmallVectorImpl<const MachineInstr*> &History = I->second;
1657 if (History.empty())
1660 // Make sure the final register assignments are terminated.
1661 const MachineInstr *Prev = History.back();
1662 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1663 const MachineBasicBlock *PrevMBB = Prev->getParent();
1664 MachineBasicBlock::const_iterator LastMI =
1665 PrevMBB->getLastNonDebugInstr();
1666 if (LastMI == PrevMBB->end())
1667 // Drop DBG_VALUE for empty range.
1669 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1670 // Terminate after LastMI.
1671 History.push_back(LastMI);
1674 // Request labels for the full history.
1675 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1676 const MachineInstr *MI = History[i];
1677 if (MI->isDebugValue())
1678 requestLabelBeforeInsn(MI);
1680 requestLabelAfterInsn(MI);
1684 PrevInstLoc = DebugLoc();
1685 PrevLabel = FunctionBeginSym;
1687 // Record beginning of function.
1688 if (!PrologEndLoc.isUnknown()) {
1689 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1690 MF->getFunction()->getContext());
1691 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1692 FnStartDL.getScope(MF->getFunction()->getContext()),
1693 // We'd like to list the prologue as "not statements" but GDB behaves
1694 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1695 DWARF2_FLAG_IS_STMT);
1699 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1700 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1701 DIVariable DV = Var->getVariable();
1702 // Variables with positive arg numbers are parameters.
1703 if (unsigned ArgNum = DV.getArgNumber()) {
1704 // Keep all parameters in order at the start of the variable list to ensure
1705 // function types are correct (no out-of-order parameters)
1707 // This could be improved by only doing it for optimized builds (unoptimized
1708 // builds have the right order to begin with), searching from the back (this
1709 // would catch the unoptimized case quickly), or doing a binary search
1710 // rather than linear search.
1711 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1712 while (I != Vars.end()) {
1713 unsigned CurNum = (*I)->getVariable().getArgNumber();
1714 // A local (non-parameter) variable has been found, insert immediately
1718 // A later indexed parameter has been found, insert immediately before it.
1719 if (CurNum > ArgNum)
1723 Vars.insert(I, Var);
1727 Vars.push_back(Var);
1730 // Gather and emit post-function debug information.
1731 void DwarfDebug::endFunction(const MachineFunction *MF) {
1732 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1734 // Define end label for subprogram.
1735 FunctionEndSym = Asm->GetTempSymbol("func_end",
1736 Asm->getFunctionNumber());
1737 // Assumes in correct section after the entry point.
1738 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1739 // Set DwarfCompileUnitID in MCContext to default value.
1740 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1742 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1743 collectVariableInfo(MF, ProcessedVars);
1745 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1746 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1747 assert(TheCU && "Unable to find compile unit!");
1749 // Construct abstract scopes.
1750 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1751 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1752 LexicalScope *AScope = AList[i];
1753 DISubprogram SP(AScope->getScopeNode());
1754 if (SP.isSubprogram()) {
1755 // Collect info for variables that were optimized out.
1756 DIArray Variables = SP.getVariables();
1757 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1758 DIVariable DV(Variables.getElement(i));
1759 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1761 // Check that DbgVariable for DV wasn't created earlier, when
1762 // findAbstractVariable() was called for inlined instance of DV.
1763 LLVMContext &Ctx = DV->getContext();
1764 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1765 if (AbstractVariables.lookup(CleanDV))
1767 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1768 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1771 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1772 constructScopeDIE(TheCU, AScope);
1775 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1777 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1778 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1781 for (ScopeVariablesMap::iterator
1782 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1783 DeleteContainerPointers(I->second);
1784 ScopeVariables.clear();
1785 DeleteContainerPointers(CurrentFnArguments);
1786 UserVariables.clear();
1788 AbstractVariables.clear();
1789 LabelsBeforeInsn.clear();
1790 LabelsAfterInsn.clear();
1794 // Register a source line with debug info. Returns the unique label that was
1795 // emitted and which provides correspondence to the source line list.
1796 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1802 DIDescriptor Scope(S);
1804 if (Scope.isCompileUnit()) {
1805 DICompileUnit CU(S);
1806 Fn = CU.getFilename();
1807 Dir = CU.getDirectory();
1808 } else if (Scope.isFile()) {
1810 Fn = F.getFilename();
1811 Dir = F.getDirectory();
1812 } else if (Scope.isSubprogram()) {
1814 Fn = SP.getFilename();
1815 Dir = SP.getDirectory();
1816 } else if (Scope.isLexicalBlockFile()) {
1817 DILexicalBlockFile DBF(S);
1818 Fn = DBF.getFilename();
1819 Dir = DBF.getDirectory();
1820 } else if (Scope.isLexicalBlock()) {
1821 DILexicalBlock DB(S);
1822 Fn = DB.getFilename();
1823 Dir = DB.getDirectory();
1825 llvm_unreachable("Unexpected scope info");
1827 Src = getOrCreateSourceID(Fn, Dir,
1828 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1830 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1833 //===----------------------------------------------------------------------===//
1835 //===----------------------------------------------------------------------===//
1837 // Compute the size and offset of a DIE.
1839 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1840 // Get the children.
1841 const std::vector<DIE *> &Children = Die->getChildren();
1843 // Record the abbreviation.
1844 assignAbbrevNumber(Die->getAbbrev());
1846 // Get the abbreviation for this DIE.
1847 unsigned AbbrevNumber = Die->getAbbrevNumber();
1848 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1851 Die->setOffset(Offset);
1853 // Start the size with the size of abbreviation code.
1854 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1856 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1857 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1859 // Size the DIE attribute values.
1860 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1861 // Size attribute value.
1862 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1864 // Size the DIE children if any.
1865 if (!Children.empty()) {
1866 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1867 "Children flag not set");
1869 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1870 Offset = computeSizeAndOffset(Children[j], Offset);
1872 // End of children marker.
1873 Offset += sizeof(int8_t);
1876 Die->setSize(Offset - Die->getOffset());
1880 // Compute the size and offset of all the DIEs.
1881 void DwarfUnits::computeSizeAndOffsets() {
1882 // Offset from the beginning of debug info section.
1883 unsigned SecOffset = 0;
1884 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1885 E = CUs.end(); I != E; ++I) {
1886 (*I)->setDebugInfoOffset(SecOffset);
1888 sizeof(int32_t) + // Length of Compilation Unit Info
1889 sizeof(int16_t) + // DWARF version number
1890 sizeof(int32_t) + // Offset Into Abbrev. Section
1891 sizeof(int8_t); // Pointer Size (in bytes)
1893 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1894 SecOffset += EndOffset;
1898 // Emit initial Dwarf sections with a label at the start of each one.
1899 void DwarfDebug::emitSectionLabels() {
1900 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1902 // Dwarf sections base addresses.
1903 DwarfInfoSectionSym =
1904 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1905 DwarfAbbrevSectionSym =
1906 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1907 if (useSplitDwarf())
1908 DwarfAbbrevDWOSectionSym =
1909 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1910 "section_abbrev_dwo");
1911 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1913 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1914 emitSectionSym(Asm, MacroInfo);
1916 DwarfLineSectionSym =
1917 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1918 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1919 if (GenerateDwarfPubNamesSection)
1920 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1921 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1922 DwarfStrSectionSym =
1923 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1924 if (useSplitDwarf()) {
1925 DwarfStrDWOSectionSym =
1926 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1927 DwarfAddrSectionSym =
1928 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1930 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1933 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1934 "section_debug_loc");
1936 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1937 emitSectionSym(Asm, TLOF.getDataSection());
1940 // Recursively emits a debug information entry.
1941 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1942 // Get the abbreviation for this DIE.
1943 unsigned AbbrevNumber = Die->getAbbrevNumber();
1944 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1946 // Emit the code (index) for the abbreviation.
1947 if (Asm->isVerbose())
1948 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1949 Twine::utohexstr(Die->getOffset()) + ":0x" +
1950 Twine::utohexstr(Die->getSize()) + " " +
1951 dwarf::TagString(Abbrev->getTag()));
1952 Asm->EmitULEB128(AbbrevNumber);
1954 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1955 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1957 // Emit the DIE attribute values.
1958 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1959 unsigned Attr = AbbrevData[i].getAttribute();
1960 unsigned Form = AbbrevData[i].getForm();
1961 assert(Form && "Too many attributes for DIE (check abbreviation)");
1963 if (Asm->isVerbose())
1964 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1967 case dwarf::DW_AT_abstract_origin: {
1968 DIEEntry *E = cast<DIEEntry>(Values[i]);
1969 DIE *Origin = E->getEntry();
1970 unsigned Addr = Origin->getOffset();
1971 if (Form == dwarf::DW_FORM_ref_addr) {
1972 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1973 // section. Origin->getOffset() returns the offset from start of the
1975 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1976 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1978 Asm->OutStreamer.EmitIntValue(Addr,
1979 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1982 case dwarf::DW_AT_ranges: {
1983 // DW_AT_range Value encodes offset in debug_range section.
1984 DIEInteger *V = cast<DIEInteger>(Values[i]);
1986 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1987 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1991 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1993 DwarfDebugRangeSectionSym,
1998 case dwarf::DW_AT_location: {
1999 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
2000 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2001 Asm->EmitLabelReference(L->getValue(), 4);
2003 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
2005 Values[i]->EmitValue(Asm, Form);
2009 case dwarf::DW_AT_accessibility: {
2010 if (Asm->isVerbose()) {
2011 DIEInteger *V = cast<DIEInteger>(Values[i]);
2012 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
2014 Values[i]->EmitValue(Asm, Form);
2018 // Emit an attribute using the defined form.
2019 Values[i]->EmitValue(Asm, Form);
2024 // Emit the DIE children if any.
2025 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
2026 const std::vector<DIE *> &Children = Die->getChildren();
2028 for (unsigned j = 0, M = Children.size(); j < M; ++j)
2029 emitDIE(Children[j], Abbrevs);
2031 if (Asm->isVerbose())
2032 Asm->OutStreamer.AddComment("End Of Children Mark");
2037 // Emit the various dwarf units to the unit section USection with
2038 // the abbreviations going into ASection.
2039 void DwarfUnits::emitUnits(DwarfDebug *DD,
2040 const MCSection *USection,
2041 const MCSection *ASection,
2042 const MCSymbol *ASectionSym) {
2043 Asm->OutStreamer.SwitchSection(USection);
2044 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2045 E = CUs.end(); I != E; ++I) {
2046 CompileUnit *TheCU = *I;
2047 DIE *Die = TheCU->getCUDie();
2049 // Emit the compile units header.
2051 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2052 TheCU->getUniqueID()));
2054 // Emit size of content not including length itself
2055 unsigned ContentSize = Die->getSize() +
2056 sizeof(int16_t) + // DWARF version number
2057 sizeof(int32_t) + // Offset Into Abbrev. Section
2058 sizeof(int8_t); // Pointer Size (in bytes)
2060 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2061 Asm->EmitInt32(ContentSize);
2062 Asm->OutStreamer.AddComment("DWARF version number");
2063 Asm->EmitInt16(DD->getDwarfVersion());
2064 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2065 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2067 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2068 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2070 DD->emitDIE(Die, Abbreviations);
2071 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2072 TheCU->getUniqueID()));
2076 /// For a given compile unit DIE, returns offset from beginning of debug info.
2077 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2078 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2079 "Input DIE should be compile unit in getCUOffset.");
2080 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2082 CompileUnit *TheCU = *I;
2083 if (TheCU->getCUDie() == Die)
2084 return TheCU->getDebugInfoOffset();
2086 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2089 // Emit the debug info section.
2090 void DwarfDebug::emitDebugInfo() {
2091 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2093 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2094 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2095 DwarfAbbrevSectionSym);
2098 // Emit the abbreviation section.
2099 void DwarfDebug::emitAbbreviations() {
2100 if (!useSplitDwarf())
2101 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2104 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2107 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2108 std::vector<DIEAbbrev *> *Abbrevs) {
2109 // Check to see if it is worth the effort.
2110 if (!Abbrevs->empty()) {
2111 // Start the debug abbrev section.
2112 Asm->OutStreamer.SwitchSection(Section);
2114 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2115 Asm->OutStreamer.EmitLabel(Begin);
2117 // For each abbrevation.
2118 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2119 // Get abbreviation data
2120 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2122 // Emit the abbrevations code (base 1 index.)
2123 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2125 // Emit the abbreviations data.
2129 // Mark end of abbreviations.
2130 Asm->EmitULEB128(0, "EOM(3)");
2132 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2133 Asm->OutStreamer.EmitLabel(End);
2137 // Emit the last address of the section and the end of the line matrix.
2138 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2139 // Define last address of section.
2140 Asm->OutStreamer.AddComment("Extended Op");
2143 Asm->OutStreamer.AddComment("Op size");
2144 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2145 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2146 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2148 Asm->OutStreamer.AddComment("Section end label");
2150 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2151 Asm->getDataLayout().getPointerSize());
2153 // Mark end of matrix.
2154 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2160 // Emit visible names into a hashed accelerator table section.
2161 void DwarfDebug::emitAccelNames() {
2162 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2163 dwarf::DW_FORM_data4));
2164 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2165 E = CUMap.end(); I != E; ++I) {
2166 CompileUnit *TheCU = I->second;
2167 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2168 for (StringMap<std::vector<DIE*> >::const_iterator
2169 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2170 StringRef Name = GI->getKey();
2171 const std::vector<DIE *> &Entities = GI->second;
2172 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2173 DE = Entities.end(); DI != DE; ++DI)
2174 AT.AddName(Name, (*DI));
2178 AT.FinalizeTable(Asm, "Names");
2179 Asm->OutStreamer.SwitchSection(
2180 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2181 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2182 Asm->OutStreamer.EmitLabel(SectionBegin);
2184 // Emit the full data.
2185 AT.Emit(Asm, SectionBegin, &InfoHolder);
2188 // Emit objective C classes and categories into a hashed accelerator table
2190 void DwarfDebug::emitAccelObjC() {
2191 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2192 dwarf::DW_FORM_data4));
2193 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2194 E = CUMap.end(); I != E; ++I) {
2195 CompileUnit *TheCU = I->second;
2196 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2197 for (StringMap<std::vector<DIE*> >::const_iterator
2198 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2199 StringRef Name = GI->getKey();
2200 const std::vector<DIE *> &Entities = GI->second;
2201 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2202 DE = Entities.end(); DI != DE; ++DI)
2203 AT.AddName(Name, (*DI));
2207 AT.FinalizeTable(Asm, "ObjC");
2208 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2209 .getDwarfAccelObjCSection());
2210 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2211 Asm->OutStreamer.EmitLabel(SectionBegin);
2213 // Emit the full data.
2214 AT.Emit(Asm, SectionBegin, &InfoHolder);
2217 // Emit namespace dies into a hashed accelerator table.
2218 void DwarfDebug::emitAccelNamespaces() {
2219 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2220 dwarf::DW_FORM_data4));
2221 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2222 E = CUMap.end(); I != E; ++I) {
2223 CompileUnit *TheCU = I->second;
2224 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2225 for (StringMap<std::vector<DIE*> >::const_iterator
2226 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2227 StringRef Name = GI->getKey();
2228 const std::vector<DIE *> &Entities = GI->second;
2229 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2230 DE = Entities.end(); DI != DE; ++DI)
2231 AT.AddName(Name, (*DI));
2235 AT.FinalizeTable(Asm, "namespac");
2236 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2237 .getDwarfAccelNamespaceSection());
2238 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2239 Asm->OutStreamer.EmitLabel(SectionBegin);
2241 // Emit the full data.
2242 AT.Emit(Asm, SectionBegin, &InfoHolder);
2245 // Emit type dies into a hashed accelerator table.
2246 void DwarfDebug::emitAccelTypes() {
2247 std::vector<DwarfAccelTable::Atom> Atoms;
2248 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2249 dwarf::DW_FORM_data4));
2250 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2251 dwarf::DW_FORM_data2));
2252 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2253 dwarf::DW_FORM_data1));
2254 DwarfAccelTable AT(Atoms);
2255 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2256 E = CUMap.end(); I != E; ++I) {
2257 CompileUnit *TheCU = I->second;
2258 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2259 = TheCU->getAccelTypes();
2260 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2261 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2262 StringRef Name = GI->getKey();
2263 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2264 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2265 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2266 AT.AddName(Name, (*DI).first, (*DI).second);
2270 AT.FinalizeTable(Asm, "types");
2271 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2272 .getDwarfAccelTypesSection());
2273 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2274 Asm->OutStreamer.EmitLabel(SectionBegin);
2276 // Emit the full data.
2277 AT.Emit(Asm, SectionBegin, &InfoHolder);
2280 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2282 void DwarfDebug::emitDebugPubnames() {
2283 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2285 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2286 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2287 CompileUnit *TheCU = I->second;
2288 unsigned ID = TheCU->getUniqueID();
2290 if (TheCU->getGlobalNames().empty())
2293 // Start the dwarf pubnames section.
2294 Asm->OutStreamer.SwitchSection(
2295 Asm->getObjFileLowering().getDwarfPubNamesSection());
2297 Asm->OutStreamer.AddComment("Length of Public Names Info");
2298 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2299 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2301 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2303 Asm->OutStreamer.AddComment("DWARF Version");
2304 Asm->EmitInt16(DwarfVersion);
2306 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2307 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2308 DwarfInfoSectionSym);
2310 Asm->OutStreamer.AddComment("Compilation Unit Length");
2311 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2312 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2315 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2316 for (StringMap<DIE*>::const_iterator
2317 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2318 const char *Name = GI->getKeyData();
2319 const DIE *Entity = GI->second;
2321 Asm->OutStreamer.AddComment("DIE offset");
2322 Asm->EmitInt32(Entity->getOffset());
2324 if (Asm->isVerbose())
2325 Asm->OutStreamer.AddComment("External Name");
2326 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2329 Asm->OutStreamer.AddComment("End Mark");
2331 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2335 void DwarfDebug::emitDebugPubTypes() {
2336 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2337 E = CUMap.end(); I != E; ++I) {
2338 CompileUnit *TheCU = I->second;
2339 // Start the dwarf pubtypes section.
2340 Asm->OutStreamer.SwitchSection(
2341 Asm->getObjFileLowering().getDwarfPubTypesSection());
2342 Asm->OutStreamer.AddComment("Length of Public Types Info");
2343 Asm->EmitLabelDifference(
2344 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2345 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2347 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2348 TheCU->getUniqueID()));
2350 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2351 Asm->EmitInt16(DwarfVersion);
2353 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2354 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2355 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2356 TheCU->getUniqueID()),
2357 DwarfInfoSectionSym);
2359 Asm->OutStreamer.AddComment("Compilation Unit Length");
2360 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2361 TheCU->getUniqueID()),
2362 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2363 TheCU->getUniqueID()),
2366 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2367 for (StringMap<DIE*>::const_iterator
2368 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2369 const char *Name = GI->getKeyData();
2370 DIE *Entity = GI->second;
2372 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2373 Asm->EmitInt32(Entity->getOffset());
2375 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2376 // Emit the name with a terminating null byte.
2377 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2380 Asm->OutStreamer.AddComment("End Mark");
2382 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2383 TheCU->getUniqueID()));
2387 // Emit strings into a string section.
2388 void DwarfUnits::emitStrings(const MCSection *StrSection,
2389 const MCSection *OffsetSection = NULL,
2390 const MCSymbol *StrSecSym = NULL) {
2392 if (StringPool.empty()) return;
2394 // Start the dwarf str section.
2395 Asm->OutStreamer.SwitchSection(StrSection);
2397 // Get all of the string pool entries and put them in an array by their ID so
2398 // we can sort them.
2399 SmallVector<std::pair<unsigned,
2400 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2402 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2403 I = StringPool.begin(), E = StringPool.end();
2405 Entries.push_back(std::make_pair(I->second.second, &*I));
2407 array_pod_sort(Entries.begin(), Entries.end());
2409 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2410 // Emit a label for reference from debug information entries.
2411 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2413 // Emit the string itself with a terminating null byte.
2414 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2415 Entries[i].second->getKeyLength()+1));
2418 // If we've got an offset section go ahead and emit that now as well.
2419 if (OffsetSection) {
2420 Asm->OutStreamer.SwitchSection(OffsetSection);
2421 unsigned offset = 0;
2422 unsigned size = 4; // FIXME: DWARF64 is 8.
2423 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2424 Asm->OutStreamer.EmitIntValue(offset, size);
2425 offset += Entries[i].second->getKeyLength() + 1;
2430 // Emit strings into a string section.
2431 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2433 if (AddressPool.empty()) return;
2435 // Start the dwarf addr section.
2436 Asm->OutStreamer.SwitchSection(AddrSection);
2438 // Order the address pool entries by ID
2439 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2441 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2442 E = AddressPool.end();
2444 Entries[I->second] = I->first;
2446 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2447 // Emit an expression for reference from debug information entries.
2448 if (const MCExpr *Expr = Entries[i])
2449 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2451 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2456 // Emit visible names into a debug str section.
2457 void DwarfDebug::emitDebugStr() {
2458 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2459 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2462 // Emit locations into the debug loc section.
2463 void DwarfDebug::emitDebugLoc() {
2464 if (DotDebugLocEntries.empty())
2467 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2468 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2470 DotDebugLocEntry &Entry = *I;
2471 if (I + 1 != DotDebugLocEntries.end())
2475 // Start the dwarf loc section.
2476 Asm->OutStreamer.SwitchSection(
2477 Asm->getObjFileLowering().getDwarfLocSection());
2478 unsigned char Size = Asm->getDataLayout().getPointerSize();
2479 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2481 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2482 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2483 I != E; ++I, ++index) {
2484 DotDebugLocEntry &Entry = *I;
2485 if (Entry.isMerged()) continue;
2486 if (Entry.isEmpty()) {
2487 Asm->OutStreamer.EmitIntValue(0, Size);
2488 Asm->OutStreamer.EmitIntValue(0, Size);
2489 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2491 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2492 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2493 DIVariable DV(Entry.getVariable());
2494 Asm->OutStreamer.AddComment("Loc expr size");
2495 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2496 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2497 Asm->EmitLabelDifference(end, begin, 2);
2498 Asm->OutStreamer.EmitLabel(begin);
2499 if (Entry.isInt()) {
2500 DIBasicType BTy(DV.getType());
2502 (BTy.getEncoding() == dwarf::DW_ATE_signed
2503 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2504 Asm->OutStreamer.AddComment("DW_OP_consts");
2505 Asm->EmitInt8(dwarf::DW_OP_consts);
2506 Asm->EmitSLEB128(Entry.getInt());
2508 Asm->OutStreamer.AddComment("DW_OP_constu");
2509 Asm->EmitInt8(dwarf::DW_OP_constu);
2510 Asm->EmitULEB128(Entry.getInt());
2512 } else if (Entry.isLocation()) {
2513 MachineLocation Loc = Entry.getLoc();
2514 if (!DV.hasComplexAddress())
2516 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2518 // Complex address entry.
2519 unsigned N = DV.getNumAddrElements();
2521 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2522 if (Loc.getOffset()) {
2524 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2525 Asm->OutStreamer.AddComment("DW_OP_deref");
2526 Asm->EmitInt8(dwarf::DW_OP_deref);
2527 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2528 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2529 Asm->EmitSLEB128(DV.getAddrElement(1));
2531 // If first address element is OpPlus then emit
2532 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2533 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2534 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2538 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2541 // Emit remaining complex address elements.
2542 for (; i < N; ++i) {
2543 uint64_t Element = DV.getAddrElement(i);
2544 if (Element == DIBuilder::OpPlus) {
2545 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2546 Asm->EmitULEB128(DV.getAddrElement(++i));
2547 } else if (Element == DIBuilder::OpDeref) {
2549 Asm->EmitInt8(dwarf::DW_OP_deref);
2551 llvm_unreachable("unknown Opcode found in complex address");
2555 // else ... ignore constant fp. There is not any good way to
2556 // to represent them here in dwarf.
2557 Asm->OutStreamer.EmitLabel(end);
2562 // Emit visible names into a debug aranges section.
2563 void DwarfDebug::emitDebugARanges() {
2564 // Start the dwarf aranges section.
2565 Asm->OutStreamer.SwitchSection(
2566 Asm->getObjFileLowering().getDwarfARangesSection());
2569 // Emit visible names into a debug ranges section.
2570 void DwarfDebug::emitDebugRanges() {
2571 // Start the dwarf ranges section.
2572 Asm->OutStreamer.SwitchSection(
2573 Asm->getObjFileLowering().getDwarfRangesSection());
2574 unsigned char Size = Asm->getDataLayout().getPointerSize();
2575 for (SmallVectorImpl<const MCSymbol *>::iterator
2576 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2579 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2581 Asm->OutStreamer.EmitIntValue(0, Size);
2585 // Emit visible names into a debug macinfo section.
2586 void DwarfDebug::emitDebugMacInfo() {
2587 if (const MCSection *LineInfo =
2588 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2589 // Start the dwarf macinfo section.
2590 Asm->OutStreamer.SwitchSection(LineInfo);
2594 // Emit inline info using following format.
2596 // 1. length of section
2597 // 2. Dwarf version number
2600 // Entries (one "entry" for each function that was inlined):
2602 // 1. offset into __debug_str section for MIPS linkage name, if exists;
2603 // otherwise offset into __debug_str for regular function name.
2604 // 2. offset into __debug_str section for regular function name.
2605 // 3. an unsigned LEB128 number indicating the number of distinct inlining
2606 // instances for the function.
2608 // The rest of the entry consists of a {die_offset, low_pc} pair for each
2609 // inlined instance; the die_offset points to the inlined_subroutine die in the
2610 // __debug_info section, and the low_pc is the starting address for the
2611 // inlining instance.
2612 void DwarfDebug::emitDebugInlineInfo() {
2613 if (!Asm->MAI->doesDwarfUseInlineInfoSection())
2619 Asm->OutStreamer.SwitchSection(
2620 Asm->getObjFileLowering().getDwarfDebugInlineSection());
2622 Asm->OutStreamer.AddComment("Length of Debug Inlined Information Entry");
2623 Asm->EmitLabelDifference(Asm->GetTempSymbol("debug_inlined_end", 1),
2624 Asm->GetTempSymbol("debug_inlined_begin", 1), 4);
2626 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_begin", 1));
2628 Asm->OutStreamer.AddComment("Dwarf Version");
2629 Asm->EmitInt16(DwarfVersion);
2630 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2631 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2633 for (SmallVectorImpl<const MDNode *>::iterator I = InlinedSPNodes.begin(),
2634 E = InlinedSPNodes.end(); I != E; ++I) {
2636 const MDNode *Node = *I;
2637 InlineInfoMap::iterator II = InlineInfo.find(Node);
2638 SmallVectorImpl<InlineInfoLabels> &Labels = II->second;
2639 DISubprogram SP(Node);
2640 StringRef LName = SP.getLinkageName();
2641 StringRef Name = SP.getName();
2643 Asm->OutStreamer.AddComment("MIPS linkage name");
2645 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2646 DwarfStrSectionSym);
2648 Asm->EmitSectionOffset(
2649 InfoHolder.getStringPoolEntry(Function::getRealLinkageName(LName)),
2650 DwarfStrSectionSym);
2652 Asm->OutStreamer.AddComment("Function name");
2653 Asm->EmitSectionOffset(InfoHolder.getStringPoolEntry(Name),
2654 DwarfStrSectionSym);
2655 Asm->EmitULEB128(Labels.size(), "Inline count");
2657 for (SmallVectorImpl<InlineInfoLabels>::iterator LI = Labels.begin(),
2658 LE = Labels.end(); LI != LE; ++LI) {
2659 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2660 Asm->EmitInt32(LI->second->getOffset());
2662 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("low_pc");
2663 Asm->OutStreamer.EmitSymbolValue(LI->first,
2664 Asm->getDataLayout().getPointerSize());
2668 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_inlined_end", 1));
2671 // DWARF5 Experimental Separate Dwarf emitters.
2673 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2674 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2675 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2676 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2677 CompileUnit *DwarfDebug::constructSkeletonCU(const MDNode *N) {
2678 DICompileUnit DIUnit(N);
2679 CompilationDir = DIUnit.getDirectory();
2681 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2682 CompileUnit *NewCU = new CompileUnit(GlobalCUIndexCount++,
2683 DIUnit.getLanguage(), Die, N, Asm,
2684 this, &SkeletonHolder);
2686 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2687 DIUnit.getSplitDebugFilename());
2689 // This should be a unique identifier when we want to build .dwp files.
2690 NewCU->addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8, 0);
2692 // Relocate to the beginning of the addr_base section, else 0 for the
2693 // beginning of the one for this compile unit.
2694 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2695 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2696 DwarfAddrSectionSym);
2698 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2699 dwarf::DW_FORM_sec_offset, 0);
2701 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2702 // into an entity. We're using 0, or a NULL label for this.
2703 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2705 // DW_AT_stmt_list is a offset of line number information for this
2706 // compile unit in debug_line section.
2707 // FIXME: Should handle multiple compile units.
2708 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2709 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2710 DwarfLineSectionSym);
2712 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2714 if (!CompilationDir.empty())
2715 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2717 SkeletonHolder.addUnit(NewCU);
2718 SkeletonCUs.push_back(NewCU);
2723 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2724 assert(useSplitDwarf() && "No split dwarf debug info?");
2725 emitAbbrevs(Section, &SkeletonAbbrevs);
2728 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2729 // compile units that would normally be in debug_info.
2730 void DwarfDebug::emitDebugInfoDWO() {
2731 assert(useSplitDwarf() && "No split dwarf debug info?");
2732 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2733 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2734 DwarfAbbrevDWOSectionSym);
2737 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2738 // abbreviations for the .debug_info.dwo section.
2739 void DwarfDebug::emitDebugAbbrevDWO() {
2740 assert(useSplitDwarf() && "No split dwarf?");
2741 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2745 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2746 // string section and is identical in format to traditional .debug_str
2748 void DwarfDebug::emitDebugStrDWO() {
2749 assert(useSplitDwarf() && "No split dwarf?");
2750 const MCSection *OffSec = Asm->getObjFileLowering()
2751 .getDwarfStrOffDWOSection();
2752 const MCSymbol *StrSym = DwarfStrSectionSym;
2753 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),