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/Dwarf.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/MD5.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/Timer.h"
44 #include "llvm/Support/ValueHandle.h"
45 #include "llvm/Target/TargetFrameLowering.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Target/TargetOptions.h"
49 #include "llvm/Target/TargetRegisterInfo.h"
53 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
54 cl::desc("Disable debug info printing"));
56 static cl::opt<bool> UnknownLocations(
57 "use-unknown-locations", cl::Hidden,
58 cl::desc("Make an absence of debug location information explicit."),
62 GenerateODRHash("generate-odr-hash", cl::Hidden,
63 cl::desc("Add an ODR hash to external type DIEs."),
67 GenerateCUHash("generate-cu-hash", cl::Hidden,
68 cl::desc("Add the CU hash as the dwo_id."),
79 static cl::opt<DefaultOnOff>
80 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
81 cl::desc("Output prototype dwarf accelerator tables."),
82 cl::values(clEnumVal(Default, "Default for platform"),
83 clEnumVal(Enable, "Enabled"),
84 clEnumVal(Disable, "Disabled"), clEnumValEnd),
87 static cl::opt<DefaultOnOff>
88 SplitDwarf("split-dwarf", cl::Hidden,
89 cl::desc("Output prototype dwarf split debug info."),
90 cl::values(clEnumVal(Default, "Default for platform"),
91 clEnumVal(Enable, "Enabled"),
92 clEnumVal(Disable, "Disabled"), clEnumValEnd),
95 static cl::opt<DefaultOnOff>
96 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
97 cl::desc("Generate DWARF pubnames and pubtypes sections"),
98 cl::values(clEnumVal(Default, "Default for platform"),
99 clEnumVal(Enable, "Enabled"),
100 clEnumVal(Disable, "Disabled"), clEnumValEnd),
103 static const char *const DWARFGroupName = "DWARF Emission";
104 static const char *const DbgTimerName = "DWARF Debug Writer";
106 //===----------------------------------------------------------------------===//
108 // Configuration values for initial hash set sizes (log2).
110 static const unsigned InitAbbreviationsSetSize = 9; // log2(512)
114 DIType DbgVariable::getType() const {
115 DIType Ty = Var.getType();
116 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
117 // addresses instead.
118 if (Var.isBlockByrefVariable()) {
119 /* Byref variables, in Blocks, are declared by the programmer as
120 "SomeType VarName;", but the compiler creates a
121 __Block_byref_x_VarName struct, and gives the variable VarName
122 either the struct, or a pointer to the struct, as its type. This
123 is necessary for various behind-the-scenes things the compiler
124 needs to do with by-reference variables in blocks.
126 However, as far as the original *programmer* is concerned, the
127 variable should still have type 'SomeType', as originally declared.
129 The following function dives into the __Block_byref_x_VarName
130 struct to find the original type of the variable. This will be
131 passed back to the code generating the type for the Debug
132 Information Entry for the variable 'VarName'. 'VarName' will then
133 have the original type 'SomeType' in its debug information.
135 The original type 'SomeType' will be the type of the field named
136 'VarName' inside the __Block_byref_x_VarName struct.
138 NOTE: In order for this to not completely fail on the debugger
139 side, the Debug Information Entry for the variable VarName needs to
140 have a DW_AT_location that tells the debugger how to unwind through
141 the pointers and __Block_byref_x_VarName struct to find the actual
142 value of the variable. The function addBlockByrefType does this. */
144 uint16_t tag = Ty.getTag();
146 if (tag == dwarf::DW_TAG_pointer_type)
147 subType = DIDerivedType(Ty).getTypeDerivedFrom();
149 DIArray Elements = DICompositeType(subType).getTypeArray();
150 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
151 DIDerivedType DT = DIDerivedType(Elements.getElement(i));
152 if (getName() == DT.getName())
153 return (DT.getTypeDerivedFrom());
159 } // end llvm namespace
161 /// Return Dwarf Version by checking module flags.
162 static unsigned getDwarfVersionFromModule(const Module *M) {
163 Value *Val = M->getModuleFlag("Dwarf Version");
164 // If we don't have a value in the module go ahead and use the default in
165 // dwarf::DWARF_VERSION.
166 // FIXME: Apple ld has a problem parsing compilation units that specify a
167 // dwarf version of greater than 3.
169 return Triple(M->getTargetTriple()).isOSDarwin() ? 3 : dwarf::DWARF_VERSION;
170 return cast<ConstantInt>(Val)->getZExtValue();
173 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
174 : Asm(A), MMI(Asm->MMI), FirstCU(0),
175 AbbreviationsSet(InitAbbreviationsSetSize),
176 SourceIdMap(DIEValueAllocator),
177 PrevLabel(NULL), GlobalCUIndexCount(0),
178 InfoHolder(A, &AbbreviationsSet, &Abbreviations, "info_string",
180 SkeletonAbbrevSet(InitAbbreviationsSetSize),
181 SkeletonHolder(A, &SkeletonAbbrevSet, &SkeletonAbbrevs, "skel_string",
184 DwarfInfoSectionSym = DwarfAbbrevSectionSym = 0;
185 DwarfStrSectionSym = TextSectionSym = 0;
186 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
187 DwarfAddrSectionSym = 0;
188 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
189 FunctionBeginSym = FunctionEndSym = 0;
191 // Turn on accelerator tables and older gdb compatibility
192 // for Darwin by default, pubnames by default for non-Darwin,
193 // and handle split dwarf.
194 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
196 if (DwarfAccelTables == Default)
197 HasDwarfAccelTables = IsDarwin;
199 HasDwarfAccelTables = DwarfAccelTables == Enable;
201 if (SplitDwarf == Default)
202 HasSplitDwarf = false;
204 HasSplitDwarf = SplitDwarf == Enable;
206 if (DwarfPubSections == Default)
207 HasDwarfPubSections = !IsDarwin;
209 HasDwarfPubSections = DwarfPubSections == Enable;
211 DwarfVersion = getDwarfVersionFromModule(MMI->getModule());
214 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
218 DwarfDebug::~DwarfDebug() {
221 // Switch to the specified MCSection and emit an assembler
222 // temporary label to it if SymbolStem is specified.
223 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
224 const char *SymbolStem = 0) {
225 Asm->OutStreamer.SwitchSection(Section);
226 if (!SymbolStem) return 0;
228 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
229 Asm->OutStreamer.EmitLabel(TmpSym);
233 MCSymbol *DwarfUnits::getStringPoolSym() {
234 return Asm->GetTempSymbol(StringPref);
237 MCSymbol *DwarfUnits::getStringPoolEntry(StringRef Str) {
238 std::pair<MCSymbol*, unsigned> &Entry =
239 StringPool.GetOrCreateValue(Str).getValue();
240 if (Entry.first) return Entry.first;
242 Entry.second = NextStringPoolNumber++;
243 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
246 unsigned DwarfUnits::getStringPoolIndex(StringRef Str) {
247 std::pair<MCSymbol*, unsigned> &Entry =
248 StringPool.GetOrCreateValue(Str).getValue();
249 if (Entry.first) return Entry.second;
251 Entry.second = NextStringPoolNumber++;
252 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
256 unsigned DwarfUnits::getAddrPoolIndex(const MCSymbol *Sym) {
257 return getAddrPoolIndex(MCSymbolRefExpr::Create(Sym, Asm->OutContext));
260 unsigned DwarfUnits::getAddrPoolIndex(const MCExpr *Sym) {
261 std::pair<DenseMap<const MCExpr *, unsigned>::iterator, bool> P =
262 AddressPool.insert(std::make_pair(Sym, NextAddrPoolNumber));
264 ++NextAddrPoolNumber;
265 return P.first->second;
268 // Define a unique number for the abbreviation.
270 void DwarfUnits::assignAbbrevNumber(DIEAbbrev &Abbrev) {
271 // Check the set for priors.
272 DIEAbbrev *InSet = AbbreviationsSet->GetOrInsertNode(&Abbrev);
274 // If it's newly added.
275 if (InSet == &Abbrev) {
276 // Add to abbreviation list.
277 Abbreviations->push_back(&Abbrev);
279 // Assign the vector position + 1 as its number.
280 Abbrev.setNumber(Abbreviations->size());
282 // Assign existing abbreviation number.
283 Abbrev.setNumber(InSet->getNumber());
287 static bool isObjCClass(StringRef Name) {
288 return Name.startswith("+") || Name.startswith("-");
291 static bool hasObjCCategory(StringRef Name) {
292 if (!isObjCClass(Name)) return false;
294 return Name.find(") ") != StringRef::npos;
297 static void getObjCClassCategory(StringRef In, StringRef &Class,
298 StringRef &Category) {
299 if (!hasObjCCategory(In)) {
300 Class = In.slice(In.find('[') + 1, In.find(' '));
305 Class = In.slice(In.find('[') + 1, In.find('('));
306 Category = In.slice(In.find('[') + 1, In.find(' '));
310 static StringRef getObjCMethodName(StringRef In) {
311 return In.slice(In.find(' ') + 1, In.find(']'));
314 // Add the various names to the Dwarf accelerator table names.
315 static void addSubprogramNames(CompileUnit *TheCU, DISubprogram SP,
317 if (!SP.isDefinition()) return;
319 TheCU->addAccelName(SP.getName(), Die);
321 // If the linkage name is different than the name, go ahead and output
322 // that as well into the name table.
323 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
324 TheCU->addAccelName(SP.getLinkageName(), Die);
326 // If this is an Objective-C selector name add it to the ObjC accelerator
328 if (isObjCClass(SP.getName())) {
329 StringRef Class, Category;
330 getObjCClassCategory(SP.getName(), Class, Category);
331 TheCU->addAccelObjC(Class, Die);
333 TheCU->addAccelObjC(Category, Die);
334 // Also add the base method name to the name table.
335 TheCU->addAccelName(getObjCMethodName(SP.getName()), Die);
339 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
340 // and DW_AT_high_pc attributes. If there are global variables in this
341 // scope then create and insert DIEs for these variables.
342 DIE *DwarfDebug::updateSubprogramScopeDIE(CompileUnit *SPCU,
343 const MDNode *SPNode) {
344 DIE *SPDie = SPCU->getDIE(SPNode);
346 assert(SPDie && "Unable to find subprogram DIE!");
347 DISubprogram SP(SPNode);
349 // If we're updating an abstract DIE, then we will be adding the children and
350 // object pointer later on. But what we don't want to do is process the
351 // concrete DIE twice.
352 DIE *AbsSPDIE = AbstractSPDies.lookup(SPNode);
354 bool InSameCU = (AbsSPDIE->getCompileUnit() == SPCU->getCUDie());
355 // Pick up abstract subprogram DIE.
356 SPDie = new DIE(dwarf::DW_TAG_subprogram);
357 // If AbsSPDIE belongs to a different CU, use DW_FORM_ref_addr instead of
359 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin,
360 InSameCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr,
364 DISubprogram SPDecl = SP.getFunctionDeclaration();
365 if (!SPDecl.isSubprogram()) {
366 // There is not any need to generate specification DIE for a function
367 // defined at compile unit level. If a function is defined inside another
368 // function then gdb prefers the definition at top level and but does not
369 // expect specification DIE in parent function. So avoid creating
370 // specification DIE for a function defined inside a function.
371 if (SP.isDefinition() && !SP.getContext().isCompileUnit() &&
372 !SP.getContext().isFile() &&
373 !isSubprogramContext(SP.getContext())) {
374 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
377 DICompositeType SPTy = SP.getType();
378 DIArray Args = SPTy.getTypeArray();
379 uint16_t SPTag = SPTy.getTag();
380 if (SPTag == dwarf::DW_TAG_subroutine_type)
381 for (unsigned i = 1, N = Args.getNumElements(); i < N; ++i) {
382 DIE *Arg = new DIE(dwarf::DW_TAG_formal_parameter);
383 DIType ATy = DIType(Args.getElement(i));
384 SPCU->addType(Arg, ATy);
385 if (ATy.isArtificial())
386 SPCU->addFlag(Arg, dwarf::DW_AT_artificial);
387 if (ATy.isObjectPointer())
388 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_object_pointer,
389 dwarf::DW_FORM_ref4, Arg);
390 SPDie->addChild(Arg);
392 DIE *SPDeclDie = SPDie;
393 SPDie = new DIE(dwarf::DW_TAG_subprogram);
394 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification,
395 dwarf::DW_FORM_ref4, SPDeclDie);
401 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_low_pc,
402 Asm->GetTempSymbol("func_begin",
403 Asm->getFunctionNumber()));
404 SPCU->addLabelAddress(SPDie, dwarf::DW_AT_high_pc,
405 Asm->GetTempSymbol("func_end",
406 Asm->getFunctionNumber()));
407 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
408 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
409 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
411 // Add name to the name table, we do this here because we're guaranteed
412 // to have concrete versions of our DW_TAG_subprogram nodes.
413 addSubprogramNames(SPCU, SP, SPDie);
418 // Construct new DW_TAG_lexical_block for this scope and attach
419 // DW_AT_low_pc/DW_AT_high_pc labels.
420 DIE *DwarfDebug::constructLexicalScopeDIE(CompileUnit *TheCU,
421 LexicalScope *Scope) {
422 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
423 if (Scope->isAbstractScope())
426 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
430 // If we have multiple ranges, emit them into the range section.
431 if (Ranges.size() > 1) {
432 // .debug_range section has not been laid out yet. Emit offset in
433 // .debug_range as a uint, size 4, for now. emitDIE will handle
434 // DW_AT_ranges appropriately.
435 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
436 DebugRangeSymbols.size()
437 * Asm->getDataLayout().getPointerSize());
438 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
439 RE = Ranges.end(); RI != RE; ++RI) {
440 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
441 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
444 // Terminate the range list.
445 DebugRangeSymbols.push_back(NULL);
446 DebugRangeSymbols.push_back(NULL);
450 // Construct the address range for this DIE.
451 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
452 MCSymbol *Start = getLabelBeforeInsn(RI->first);
453 MCSymbol *End = getLabelAfterInsn(RI->second);
455 if (End == 0) return 0;
457 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
458 assert(End->isDefined() && "Invalid end label for an inlined scope!");
460 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, Start);
461 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, End);
466 // This scope represents inlined body of a function. Construct DIE to
467 // represent this concrete inlined copy of the function.
468 DIE *DwarfDebug::constructInlinedScopeDIE(CompileUnit *TheCU,
469 LexicalScope *Scope) {
470 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
471 assert(Ranges.empty() == false &&
472 "LexicalScope does not have instruction markers!");
474 if (!Scope->getScopeNode())
476 DIScope DS(Scope->getScopeNode());
477 DISubprogram InlinedSP = getDISubprogram(DS);
478 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
480 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
484 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
485 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin,
486 dwarf::DW_FORM_ref4, OriginDIE);
488 if (Ranges.size() > 1) {
489 // .debug_range section has not been laid out yet. Emit offset in
490 // .debug_range as a uint, size 4, for now. emitDIE will handle
491 // DW_AT_ranges appropriately.
492 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_ranges, dwarf::DW_FORM_data4,
493 DebugRangeSymbols.size()
494 * Asm->getDataLayout().getPointerSize());
495 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
496 RE = Ranges.end(); RI != RE; ++RI) {
497 DebugRangeSymbols.push_back(getLabelBeforeInsn(RI->first));
498 DebugRangeSymbols.push_back(getLabelAfterInsn(RI->second));
500 DebugRangeSymbols.push_back(NULL);
501 DebugRangeSymbols.push_back(NULL);
503 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
504 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
505 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
507 if (StartLabel == 0 || EndLabel == 0)
508 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
510 assert(StartLabel->isDefined() &&
511 "Invalid starting label for an inlined scope!");
512 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
514 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_low_pc, StartLabel);
515 TheCU->addLabelAddress(ScopeDIE, dwarf::DW_AT_high_pc, EndLabel);
518 InlinedSubprogramDIEs.insert(OriginDIE);
520 // Add the call site information to the DIE.
521 DILocation DL(Scope->getInlinedAt());
522 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_file, 0,
523 getOrCreateSourceID(DL.getFilename(), DL.getDirectory(),
524 TheCU->getUniqueID()));
525 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, 0, DL.getLineNumber());
527 // Add name to the name table, we do this here because we're guaranteed
528 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
529 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
534 // Construct a DIE for this scope.
535 DIE *DwarfDebug::constructScopeDIE(CompileUnit *TheCU, LexicalScope *Scope) {
536 if (!Scope || !Scope->getScopeNode())
539 DIScope DS(Scope->getScopeNode());
540 // Early return to avoid creating dangling variable|scope DIEs.
541 if (!Scope->getInlinedAt() && DS.isSubprogram() && Scope->isAbstractScope() &&
545 SmallVector<DIE *, 8> Children;
546 DIE *ObjectPointer = NULL;
548 // Collect arguments for current function.
549 if (LScopes.isCurrentFunctionScope(Scope))
550 for (unsigned i = 0, N = CurrentFnArguments.size(); i < N; ++i)
551 if (DbgVariable *ArgDV = CurrentFnArguments[i])
553 TheCU->constructVariableDIE(ArgDV, Scope->isAbstractScope())) {
554 Children.push_back(Arg);
555 if (ArgDV->isObjectPointer()) ObjectPointer = Arg;
558 // Collect lexical scope children first.
559 const SmallVectorImpl<DbgVariable *> &Variables =ScopeVariables.lookup(Scope);
560 for (unsigned i = 0, N = Variables.size(); i < N; ++i)
562 TheCU->constructVariableDIE(Variables[i], Scope->isAbstractScope())) {
563 Children.push_back(Variable);
564 if (Variables[i]->isObjectPointer()) ObjectPointer = Variable;
566 const SmallVectorImpl<LexicalScope *> &Scopes = Scope->getChildren();
567 for (unsigned j = 0, M = Scopes.size(); j < M; ++j)
568 if (DIE *Nested = constructScopeDIE(TheCU, Scopes[j]))
569 Children.push_back(Nested);
570 DIE *ScopeDIE = NULL;
571 if (Scope->getInlinedAt())
572 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
573 else if (DS.isSubprogram()) {
574 ProcessedSPNodes.insert(DS);
575 if (Scope->isAbstractScope()) {
576 ScopeDIE = TheCU->getDIE(DS);
577 // Note down abstract DIE.
579 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
582 ScopeDIE = updateSubprogramScopeDIE(TheCU, DS);
585 // There is no need to emit empty lexical block DIE.
586 std::pair<ImportedEntityMap::const_iterator,
587 ImportedEntityMap::const_iterator> Range = std::equal_range(
588 ScopesWithImportedEntities.begin(), ScopesWithImportedEntities.end(),
589 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode*)0),
591 if (Children.empty() && Range.first == Range.second)
593 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
594 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
596 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
600 std::for_each(Children.begin(), Children.end(), deleter<DIE>);
605 for (SmallVectorImpl<DIE *>::iterator I = Children.begin(),
606 E = Children.end(); I != E; ++I)
607 ScopeDIE->addChild(*I);
609 if (DS.isSubprogram() && ObjectPointer != NULL)
610 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer,
611 dwarf::DW_FORM_ref4, ObjectPointer);
613 if (DS.isSubprogram())
614 TheCU->addPubTypes(DISubprogram(DS));
619 // Look up the source id with the given directory and source file names.
620 // If none currently exists, create a new id and insert it in the
621 // SourceIds map. This can update DirectoryNames and SourceFileNames maps
623 unsigned DwarfDebug::getOrCreateSourceID(StringRef FileName,
624 StringRef DirName, unsigned CUID) {
625 // If we use .loc in assembly, we can't separate .file entries according to
626 // compile units. Thus all files will belong to the default compile unit.
627 if (Asm->TM.hasMCUseLoc() &&
628 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
631 // If FE did not provide a file name, then assume stdin.
632 if (FileName.empty())
633 return getOrCreateSourceID("<stdin>", StringRef(), CUID);
635 // TODO: this might not belong here. See if we can factor this better.
636 if (DirName == CompilationDir)
639 // FileIDCUMap stores the current ID for the given compile unit.
640 unsigned SrcId = FileIDCUMap[CUID] + 1;
642 // We look up the CUID/file/dir by concatenating them with a zero byte.
643 SmallString<128> NamePair;
644 NamePair += utostr(CUID);
647 NamePair += '\0'; // Zero bytes are not allowed in paths.
648 NamePair += FileName;
650 StringMapEntry<unsigned> &Ent = SourceIdMap.GetOrCreateValue(NamePair, SrcId);
651 if (Ent.getValue() != SrcId)
652 return Ent.getValue();
654 FileIDCUMap[CUID] = SrcId;
655 // Print out a .file directive to specify files for .loc directives.
656 Asm->OutStreamer.EmitDwarfFileDirective(SrcId, DirName, FileName, CUID);
661 // Create new CompileUnit for the given metadata node with tag
662 // DW_TAG_compile_unit.
663 CompileUnit *DwarfDebug::constructCompileUnit(const MDNode *N) {
664 DICompileUnit DIUnit(N);
665 StringRef FN = DIUnit.getFilename();
666 CompilationDir = DIUnit.getDirectory();
668 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
670 new CompileUnit(GlobalCUIndexCount++, Die, N, Asm, this, &InfoHolder);
672 FileIDCUMap[NewCU->getUniqueID()] = 0;
673 // Call this to emit a .file directive if it wasn't emitted for the source
674 // file this CU comes from yet.
675 getOrCreateSourceID(FN, CompilationDir, NewCU->getUniqueID());
677 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
678 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
679 DIUnit.getLanguage());
680 NewCU->addString(Die, dwarf::DW_AT_name, FN);
682 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
683 // into an entity. We're using 0 (or a NULL label) for this. For
684 // split dwarf it's in the skeleton CU so omit it here.
685 if (!useSplitDwarf())
686 NewCU->addLabelAddress(Die, dwarf::DW_AT_low_pc, NULL);
688 // Define start line table label for each Compile Unit.
689 MCSymbol *LineTableStartSym = Asm->GetTempSymbol("line_table_start",
690 NewCU->getUniqueID());
691 Asm->OutStreamer.getContext().setMCLineTableSymbol(LineTableStartSym,
692 NewCU->getUniqueID());
694 // Use a single line table if we are using .loc and generating assembly.
696 (Asm->TM.hasMCUseLoc() &&
697 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer) ||
698 (NewCU->getUniqueID() == 0);
700 // DW_AT_stmt_list is a offset of line number information for this
701 // compile unit in debug_line section. For split dwarf this is
702 // left in the skeleton CU and so not included.
703 // The line table entries are not always emitted in assembly, so it
704 // is not okay to use line_table_start here.
705 if (!useSplitDwarf()) {
706 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
707 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
709 Asm->GetTempSymbol("section_line") : LineTableStartSym);
710 else if (UseTheFirstCU)
711 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4, 0);
713 NewCU->addDelta(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_data4,
714 LineTableStartSym, DwarfLineSectionSym);
717 // If we're using split dwarf the compilation dir is going to be in the
718 // skeleton CU and so we don't need to duplicate it here.
719 if (!useSplitDwarf() && !CompilationDir.empty())
720 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
721 if (DIUnit.isOptimized())
722 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
724 StringRef Flags = DIUnit.getFlags();
726 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
728 if (unsigned RVer = DIUnit.getRunTimeVersion())
729 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
730 dwarf::DW_FORM_data1, RVer);
735 InfoHolder.addUnit(NewCU);
737 CUMap.insert(std::make_pair(N, NewCU));
741 // Construct subprogram DIE.
742 void DwarfDebug::constructSubprogramDIE(CompileUnit *TheCU,
744 CompileUnit *&CURef = SPMap[N];
750 if (!SP.isDefinition())
751 // This is a method declaration which will be handled while constructing
755 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
758 TheCU->insertDIE(N, SubprogramDie);
760 // Add to context owner.
761 TheCU->addToContextOwner(SubprogramDie, SP.getContext());
763 // Expose as global, if requested.
764 if (HasDwarfPubSections)
765 TheCU->addGlobalName(SP.getName(), SubprogramDie);
768 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
770 DIImportedEntity Module(N);
771 if (!Module.Verify())
773 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
774 constructImportedEntityDIE(TheCU, Module, D);
777 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU, const MDNode *N,
779 DIImportedEntity Module(N);
780 if (!Module.Verify())
782 return constructImportedEntityDIE(TheCU, Module, Context);
785 void DwarfDebug::constructImportedEntityDIE(CompileUnit *TheCU,
786 const DIImportedEntity &Module,
788 assert(Module.Verify() &&
789 "Use one of the MDNode * overloads to handle invalid metadata");
790 assert(Context && "Should always have a context for an imported_module");
791 DIE *IMDie = new DIE(Module.getTag());
792 TheCU->insertDIE(Module, IMDie);
794 DIDescriptor Entity = Module.getEntity();
795 if (Entity.isNameSpace())
796 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
797 else if (Entity.isSubprogram())
798 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
799 else if (Entity.isType())
800 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
802 EntityDie = TheCU->getDIE(Entity);
803 unsigned FileID = getOrCreateSourceID(Module.getContext().getFilename(),
804 Module.getContext().getDirectory(),
805 TheCU->getUniqueID());
806 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_file, 0, FileID);
807 TheCU->addUInt(IMDie, dwarf::DW_AT_decl_line, 0, Module.getLineNumber());
808 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, dwarf::DW_FORM_ref4,
810 StringRef Name = Module.getName();
812 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
813 Context->addChild(IMDie);
816 // Emit all Dwarf sections that should come prior to the content. Create
817 // global DIEs and emit initial debug info sections. This is invoked by
818 // the target AsmPrinter.
819 void DwarfDebug::beginModule() {
820 if (DisableDebugInfoPrinting)
823 const Module *M = MMI->getModule();
825 // If module has named metadata anchors then use them, otherwise scan the
826 // module using debug info finder to collect debug info.
827 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
831 // Emit initial sections so we can reference labels later.
834 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
835 DICompileUnit CUNode(CU_Nodes->getOperand(i));
836 CompileUnit *CU = constructCompileUnit(CUNode);
837 DIArray ImportedEntities = CUNode.getImportedEntities();
838 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
839 ScopesWithImportedEntities.push_back(std::make_pair(
840 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
841 ImportedEntities.getElement(i)));
842 std::sort(ScopesWithImportedEntities.begin(),
843 ScopesWithImportedEntities.end(), less_first());
844 DIArray GVs = CUNode.getGlobalVariables();
845 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
846 CU->createGlobalVariableDIE(GVs.getElement(i));
847 DIArray SPs = CUNode.getSubprograms();
848 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
849 constructSubprogramDIE(CU, SPs.getElement(i));
850 DIArray EnumTypes = CUNode.getEnumTypes();
851 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
852 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
853 DIArray RetainedTypes = CUNode.getRetainedTypes();
854 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
855 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
856 // Emit imported_modules last so that the relevant context is already
858 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
859 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
862 // Tell MMI that we have debug info.
863 MMI->setDebugInfoAvailability(true);
865 // Prime section data.
866 SectionMap.insert(Asm->getObjFileLowering().getTextSection());
869 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
870 void DwarfDebug::computeInlinedDIEs() {
871 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
872 for (SmallPtrSet<DIE *, 4>::iterator AI = InlinedSubprogramDIEs.begin(),
873 AE = InlinedSubprogramDIEs.end(); AI != AE; ++AI) {
875 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
877 for (DenseMap<const MDNode *, DIE *>::iterator AI = AbstractSPDies.begin(),
878 AE = AbstractSPDies.end(); AI != AE; ++AI) {
879 DIE *ISP = AI->second;
880 if (InlinedSubprogramDIEs.count(ISP))
882 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, 0, dwarf::DW_INL_inlined);
886 // Collect info for variables that were optimized out.
887 void DwarfDebug::collectDeadVariables() {
888 const Module *M = MMI->getModule();
889 DenseMap<const MDNode *, LexicalScope *> DeadFnScopeMap;
891 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
892 for (unsigned i = 0, e = CU_Nodes->getNumOperands(); i != e; ++i) {
893 DICompileUnit TheCU(CU_Nodes->getOperand(i));
894 DIArray Subprograms = TheCU.getSubprograms();
895 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
896 DISubprogram SP(Subprograms.getElement(i));
897 if (ProcessedSPNodes.count(SP) != 0) continue;
898 if (!SP.isSubprogram()) continue;
899 if (!SP.isDefinition()) continue;
900 DIArray Variables = SP.getVariables();
901 if (Variables.getNumElements() == 0) continue;
903 LexicalScope *Scope =
904 new LexicalScope(NULL, DIDescriptor(SP), NULL, false);
905 DeadFnScopeMap[SP] = Scope;
907 // Construct subprogram DIE and add variables DIEs.
908 CompileUnit *SPCU = CUMap.lookup(TheCU);
909 assert(SPCU && "Unable to find Compile Unit!");
910 constructSubprogramDIE(SPCU, SP);
911 DIE *ScopeDIE = SPCU->getDIE(SP);
912 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
913 DIVariable DV(Variables.getElement(vi));
914 if (!DV.isVariable()) continue;
915 DbgVariable NewVar(DV, NULL);
916 if (DIE *VariableDIE =
917 SPCU->constructVariableDIE(&NewVar, Scope->isAbstractScope()))
918 ScopeDIE->addChild(VariableDIE);
923 DeleteContainerSeconds(DeadFnScopeMap);
926 // Type Signature [7.27] and ODR Hash code.
928 /// \brief Grabs the string in whichever attribute is passed in and returns
929 /// a reference to it. Returns "" if the attribute doesn't exist.
930 static StringRef getDIEStringAttr(DIE *Die, unsigned Attr) {
931 DIEValue *V = Die->findAttribute(Attr);
933 if (DIEString *S = dyn_cast_or_null<DIEString>(V))
934 return S->getString();
936 return StringRef("");
939 /// Return true if the current DIE is contained within an anonymous namespace.
940 static bool isContainedInAnonNamespace(DIE *Die) {
941 DIE *Parent = Die->getParent();
944 if (Parent->getTag() == dwarf::DW_TAG_namespace &&
945 getDIEStringAttr(Parent, dwarf::DW_AT_name) == "")
947 Parent = Parent->getParent();
953 /// Test if the current CU language is C++ and that we have
954 /// a named type that is not contained in an anonymous namespace.
955 static bool shouldAddODRHash(CompileUnit *CU, DIE *Die) {
956 return CU->getLanguage() == dwarf::DW_LANG_C_plus_plus &&
957 getDIEStringAttr(Die, dwarf::DW_AT_name) != "" &&
958 !isContainedInAnonNamespace(Die);
961 void DwarfDebug::finalizeModuleInfo() {
962 // Collect info for variables that were optimized out.
963 collectDeadVariables();
965 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
966 computeInlinedDIEs();
968 // Split out type units and conditionally add an ODR tag to the split
970 // FIXME: Do type splitting.
971 for (unsigned i = 0, e = TypeUnits.size(); i != e; ++i) {
972 DIE *Die = TypeUnits[i];
974 // If we've requested ODR hashes and it's applicable for an ODR hash then
975 // add the ODR signature now.
976 // FIXME: This should be added onto the type unit, not the type, but this
977 // works as an intermediate stage.
978 if (GenerateODRHash && shouldAddODRHash(CUMap.begin()->second, Die))
979 CUMap.begin()->second->addUInt(Die, dwarf::DW_AT_GNU_odr_signature,
980 dwarf::DW_FORM_data8,
981 Hash.computeDIEODRSignature(Die));
984 // Handle anything that needs to be done on a per-cu basis.
985 for (DenseMap<const MDNode *, CompileUnit *>::iterator CUI = CUMap.begin(),
988 CompileUnit *TheCU = CUI->second;
989 // Emit DW_AT_containing_type attribute to connect types with their
990 // vtable holding type.
991 TheCU->constructContainingTypeDIEs();
993 // If we're splitting the dwarf out now that we've got the entire
994 // CU then construct a skeleton CU based upon it.
995 if (useSplitDwarf()) {
997 if (GenerateCUHash) {
999 ID = CUHash.computeCUSignature(TheCU->getCUDie());
1001 // This should be a unique identifier when we want to build .dwp files.
1002 TheCU->addUInt(TheCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1003 dwarf::DW_FORM_data8, ID);
1004 // Now construct the skeleton CU associated.
1005 CompileUnit *SkCU = constructSkeletonCU(TheCU);
1006 // This should be a unique identifier when we want to build .dwp files.
1007 SkCU->addUInt(SkCU->getCUDie(), dwarf::DW_AT_GNU_dwo_id,
1008 dwarf::DW_FORM_data8, ID);
1012 // Compute DIE offsets and sizes.
1013 InfoHolder.computeSizeAndOffsets();
1014 if (useSplitDwarf())
1015 SkeletonHolder.computeSizeAndOffsets();
1018 void DwarfDebug::endSections() {
1019 // Standard sections final addresses.
1020 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getTextSection());
1021 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("text_end"));
1022 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering().getDataSection());
1023 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("data_end"));
1025 // End text sections.
1026 for (unsigned I = 0, E = SectionMap.size(); I != E; ++I) {
1027 Asm->OutStreamer.SwitchSection(SectionMap[I]);
1028 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("section_end", I+1));
1032 // Emit all Dwarf sections that should come after the content.
1033 void DwarfDebug::endModule() {
1035 if (!FirstCU) return;
1037 // End any existing sections.
1038 // TODO: Does this need to happen?
1041 // Finalize the debug info for the module.
1042 finalizeModuleInfo();
1044 if (!useSplitDwarf()) {
1045 // Emit all the DIEs into a debug info section.
1048 // Corresponding abbreviations into a abbrev section.
1049 emitAbbreviations();
1051 // Emit info into a debug loc section.
1054 // Emit info into a debug aranges section.
1057 // Emit info into a debug ranges section.
1060 // Emit info into a debug macinfo section.
1064 // TODO: Fill this in for separated debug sections and separate
1065 // out information into new sections.
1067 // Emit the debug info section and compile units.
1071 // Corresponding abbreviations into a abbrev section.
1072 emitAbbreviations();
1073 emitDebugAbbrevDWO();
1075 // Emit info into a debug loc section.
1078 // Emit info into a debug aranges section.
1081 // Emit info into a debug ranges section.
1084 // Emit info into a debug macinfo section.
1087 // Emit DWO addresses.
1088 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1092 // Emit info into the dwarf accelerator table sections.
1093 if (useDwarfAccelTables()) {
1096 emitAccelNamespaces();
1100 // Emit the pubnames and pubtypes sections if requested.
1101 if (HasDwarfPubSections) {
1102 emitDebugPubnames();
1103 emitDebugPubTypes();
1106 // Finally emit string information into a string table.
1108 if (useSplitDwarf())
1113 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
1114 E = CUMap.end(); I != E; ++I)
1117 for (SmallVectorImpl<CompileUnit *>::iterator I = SkeletonCUs.begin(),
1118 E = SkeletonCUs.end(); I != E; ++I)
1121 // Reset these for the next Module if we have one.
1125 // Find abstract variable, if any, associated with Var.
1126 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1127 DebugLoc ScopeLoc) {
1128 LLVMContext &Ctx = DV->getContext();
1129 // More then one inlined variable corresponds to one abstract variable.
1130 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1131 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1133 return AbsDbgVariable;
1135 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1139 AbsDbgVariable = new DbgVariable(Var, NULL);
1140 addScopeVariable(Scope, AbsDbgVariable);
1141 AbstractVariables[Var] = AbsDbgVariable;
1142 return AbsDbgVariable;
1145 // If Var is a current function argument then add it to CurrentFnArguments list.
1146 bool DwarfDebug::addCurrentFnArgument(const MachineFunction *MF,
1147 DbgVariable *Var, LexicalScope *Scope) {
1148 if (!LScopes.isCurrentFunctionScope(Scope))
1150 DIVariable DV = Var->getVariable();
1151 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1153 unsigned ArgNo = DV.getArgNumber();
1157 size_t Size = CurrentFnArguments.size();
1159 CurrentFnArguments.resize(MF->getFunction()->arg_size());
1160 // llvm::Function argument size is not good indicator of how many
1161 // arguments does the function have at source level.
1163 CurrentFnArguments.resize(ArgNo * 2);
1164 CurrentFnArguments[ArgNo - 1] = Var;
1168 // Collect variable information from side table maintained by MMI.
1170 DwarfDebug::collectVariableInfoFromMMITable(const MachineFunction *MF,
1171 SmallPtrSet<const MDNode *, 16> &Processed) {
1172 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
1173 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
1174 VE = VMap.end(); VI != VE; ++VI) {
1175 const MDNode *Var = VI->first;
1177 Processed.insert(Var);
1179 const std::pair<unsigned, DebugLoc> &VP = VI->second;
1181 LexicalScope *Scope = LScopes.findLexicalScope(VP.second);
1183 // If variable scope is not found then skip this variable.
1187 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VP.second);
1188 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable);
1189 RegVar->setFrameIndex(VP.first);
1190 if (!addCurrentFnArgument(MF, RegVar, Scope))
1191 addScopeVariable(Scope, RegVar);
1193 AbsDbgVariable->setFrameIndex(VP.first);
1197 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1199 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1200 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1201 return MI->getNumOperands() == 3 &&
1202 MI->getOperand(0).isReg() && MI->getOperand(0).getReg() &&
1203 (MI->getOperand(1).isImm() ||
1204 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1207 // Get .debug_loc entry for the instruction range starting at MI.
1208 static DotDebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1209 const MCSymbol *FLabel,
1210 const MCSymbol *SLabel,
1211 const MachineInstr *MI) {
1212 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1214 assert(MI->getNumOperands() == 3);
1215 if (MI->getOperand(0).isReg()) {
1216 MachineLocation MLoc;
1217 // If the second operand is an immediate, this is a
1218 // register-indirect address.
1219 if (!MI->getOperand(1).isImm())
1220 MLoc.set(MI->getOperand(0).getReg());
1222 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1223 return DotDebugLocEntry(FLabel, SLabel, MLoc, Var);
1225 if (MI->getOperand(0).isImm())
1226 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1227 if (MI->getOperand(0).isFPImm())
1228 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1229 if (MI->getOperand(0).isCImm())
1230 return DotDebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1232 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1235 // Find variables for each lexical scope.
1237 DwarfDebug::collectVariableInfo(const MachineFunction *MF,
1238 SmallPtrSet<const MDNode *, 16> &Processed) {
1240 // Grab the variable info that was squirreled away in the MMI side-table.
1241 collectVariableInfoFromMMITable(MF, Processed);
1243 for (SmallVectorImpl<const MDNode*>::const_iterator
1244 UVI = UserVariables.begin(), UVE = UserVariables.end(); UVI != UVE;
1246 const MDNode *Var = *UVI;
1247 if (Processed.count(Var))
1250 // History contains relevant DBG_VALUE instructions for Var and instructions
1252 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1253 if (History.empty())
1255 const MachineInstr *MInsn = History.front();
1258 LexicalScope *Scope = NULL;
1259 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1260 DISubprogram(DV.getContext()).describes(MF->getFunction()))
1261 Scope = LScopes.getCurrentFunctionScope();
1262 else if (MDNode *IA = DV.getInlinedAt())
1263 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1265 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1266 // If variable scope is not found then skip this variable.
1270 Processed.insert(DV);
1271 assert(MInsn->isDebugValue() && "History must begin with debug value");
1272 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1273 DbgVariable *RegVar = new DbgVariable(DV, AbsVar);
1274 if (!addCurrentFnArgument(MF, RegVar, Scope))
1275 addScopeVariable(Scope, RegVar);
1277 AbsVar->setMInsn(MInsn);
1279 // Simplify ranges that are fully coalesced.
1280 if (History.size() <= 1 || (History.size() == 2 &&
1281 MInsn->isIdenticalTo(History.back()))) {
1282 RegVar->setMInsn(MInsn);
1286 // Handle multiple DBG_VALUE instructions describing one variable.
1287 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1289 for (SmallVectorImpl<const MachineInstr*>::const_iterator
1290 HI = History.begin(), HE = History.end(); HI != HE; ++HI) {
1291 const MachineInstr *Begin = *HI;
1292 assert(Begin->isDebugValue() && "Invalid History entry");
1294 // Check if DBG_VALUE is truncating a range.
1295 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg()
1296 && !Begin->getOperand(0).getReg())
1299 // Compute the range for a register location.
1300 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1301 const MCSymbol *SLabel = 0;
1304 // If Begin is the last instruction in History then its value is valid
1305 // until the end of the function.
1306 SLabel = FunctionEndSym;
1308 const MachineInstr *End = HI[1];
1309 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1310 << "\t" << *Begin << "\t" << *End << "\n");
1311 if (End->isDebugValue())
1312 SLabel = getLabelBeforeInsn(End);
1314 // End is a normal instruction clobbering the range.
1315 SLabel = getLabelAfterInsn(End);
1316 assert(SLabel && "Forgot label after clobber instruction");
1321 // The value is valid until the next DBG_VALUE or clobber.
1322 DotDebugLocEntries.push_back(getDebugLocEntry(Asm, FLabel, SLabel,
1325 DotDebugLocEntries.push_back(DotDebugLocEntry());
1328 // Collect info for variables that were optimized out.
1329 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1330 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1331 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1332 DIVariable DV(Variables.getElement(i));
1333 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1335 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1336 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1340 // Return Label preceding the instruction.
1341 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1342 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1343 assert(Label && "Didn't insert label before instruction");
1347 // Return Label immediately following the instruction.
1348 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1349 return LabelsAfterInsn.lookup(MI);
1352 // Process beginning of an instruction.
1353 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1354 // Check if source location changes, but ignore DBG_VALUE locations.
1355 if (!MI->isDebugValue()) {
1356 DebugLoc DL = MI->getDebugLoc();
1357 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1360 if (DL == PrologEndLoc) {
1361 Flags |= DWARF2_FLAG_PROLOGUE_END;
1362 PrologEndLoc = DebugLoc();
1364 if (PrologEndLoc.isUnknown())
1365 Flags |= DWARF2_FLAG_IS_STMT;
1367 if (!DL.isUnknown()) {
1368 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1369 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1371 recordSourceLine(0, 0, 0, 0);
1375 // Insert labels where requested.
1376 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1377 LabelsBeforeInsn.find(MI);
1380 if (I == LabelsBeforeInsn.end())
1383 // Label already assigned.
1388 PrevLabel = MMI->getContext().CreateTempSymbol();
1389 Asm->OutStreamer.EmitLabel(PrevLabel);
1391 I->second = PrevLabel;
1394 // Process end of an instruction.
1395 void DwarfDebug::endInstruction(const MachineInstr *MI) {
1396 // Don't create a new label after DBG_VALUE instructions.
1397 // They don't generate code.
1398 if (!MI->isDebugValue())
1401 DenseMap<const MachineInstr*, MCSymbol*>::iterator I =
1402 LabelsAfterInsn.find(MI);
1405 if (I == LabelsAfterInsn.end())
1408 // Label already assigned.
1412 // We need a label after this instruction.
1414 PrevLabel = MMI->getContext().CreateTempSymbol();
1415 Asm->OutStreamer.EmitLabel(PrevLabel);
1417 I->second = PrevLabel;
1420 // Each LexicalScope has first instruction and last instruction to mark
1421 // beginning and end of a scope respectively. Create an inverse map that list
1422 // scopes starts (and ends) with an instruction. One instruction may start (or
1423 // end) multiple scopes. Ignore scopes that are not reachable.
1424 void DwarfDebug::identifyScopeMarkers() {
1425 SmallVector<LexicalScope *, 4> WorkList;
1426 WorkList.push_back(LScopes.getCurrentFunctionScope());
1427 while (!WorkList.empty()) {
1428 LexicalScope *S = WorkList.pop_back_val();
1430 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1431 if (!Children.empty())
1432 for (SmallVectorImpl<LexicalScope *>::const_iterator SI = Children.begin(),
1433 SE = Children.end(); SI != SE; ++SI)
1434 WorkList.push_back(*SI);
1436 if (S->isAbstractScope())
1439 const SmallVectorImpl<InsnRange> &Ranges = S->getRanges();
1442 for (SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin(),
1443 RE = Ranges.end(); RI != RE; ++RI) {
1444 assert(RI->first && "InsnRange does not have first instruction!");
1445 assert(RI->second && "InsnRange does not have second instruction!");
1446 requestLabelBeforeInsn(RI->first);
1447 requestLabelAfterInsn(RI->second);
1452 // Get MDNode for DebugLoc's scope.
1453 static MDNode *getScopeNode(DebugLoc DL, const LLVMContext &Ctx) {
1454 if (MDNode *InlinedAt = DL.getInlinedAt(Ctx))
1455 return getScopeNode(DebugLoc::getFromDILocation(InlinedAt), Ctx);
1456 return DL.getScope(Ctx);
1459 // Walk up the scope chain of given debug loc and find line number info
1460 // for the function.
1461 static DebugLoc getFnDebugLoc(DebugLoc DL, const LLVMContext &Ctx) {
1462 const MDNode *Scope = getScopeNode(DL, Ctx);
1463 DISubprogram SP = getDISubprogram(Scope);
1464 if (SP.isSubprogram()) {
1465 // Check for number of operands since the compatibility is
1467 if (SP->getNumOperands() > 19)
1468 return DebugLoc::get(SP.getScopeLineNumber(), 0, SP);
1470 return DebugLoc::get(SP.getLineNumber(), 0, SP);
1476 // Gather pre-function debug information. Assumes being called immediately
1477 // after the function entry point has been emitted.
1478 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1479 if (!MMI->hasDebugInfo()) return;
1480 LScopes.initialize(*MF);
1481 if (LScopes.empty()) return;
1482 identifyScopeMarkers();
1484 // Set DwarfCompileUnitID in MCContext to the Compile Unit this function
1486 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1487 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1488 assert(TheCU && "Unable to find compile unit!");
1489 if (Asm->TM.hasMCUseLoc() &&
1490 Asm->OutStreamer.getKind() == MCStreamer::SK_AsmStreamer)
1491 // Use a single line table if we are using .loc and generating assembly.
1492 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1494 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1496 FunctionBeginSym = Asm->GetTempSymbol("func_begin",
1497 Asm->getFunctionNumber());
1498 // Assumes in correct section after the entry point.
1499 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1501 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1503 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1504 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1505 std::vector<const MDNode*> LiveUserVar(TRI->getNumRegs());
1507 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end();
1509 bool AtBlockEntry = true;
1510 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1512 const MachineInstr *MI = II;
1514 if (MI->isDebugValue()) {
1515 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1517 // Keep track of user variables.
1519 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1521 // Variable is in a register, we need to check for clobbers.
1522 if (isDbgValueInDefinedReg(MI))
1523 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1525 // Check the history of this variable.
1526 SmallVectorImpl<const MachineInstr*> &History = DbgValues[Var];
1527 if (History.empty()) {
1528 UserVariables.push_back(Var);
1529 // The first mention of a function argument gets the FunctionBeginSym
1530 // label, so arguments are visible when breaking at function entry.
1532 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1533 DISubprogram(getDISubprogram(DV.getContext()))
1534 .describes(MF->getFunction()))
1535 LabelsBeforeInsn[MI] = FunctionBeginSym;
1537 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1538 const MachineInstr *Prev = History.back();
1539 if (Prev->isDebugValue()) {
1540 // Coalesce identical entries at the end of History.
1541 if (History.size() >= 2 &&
1542 Prev->isIdenticalTo(History[History.size() - 2])) {
1543 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1545 << "\t" << *History[History.size() - 2] << "\n");
1549 // Terminate old register assignments that don't reach MI;
1550 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1551 if (PrevMBB != I && (!AtBlockEntry || llvm::next(PrevMBB) != I) &&
1552 isDbgValueInDefinedReg(Prev)) {
1553 // Previous register assignment needs to terminate at the end of
1555 MachineBasicBlock::const_iterator LastMI =
1556 PrevMBB->getLastNonDebugInstr();
1557 if (LastMI == PrevMBB->end()) {
1558 // Drop DBG_VALUE for empty range.
1559 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1560 << "\t" << *Prev << "\n");
1562 } else if (llvm::next(PrevMBB) != PrevMBB->getParent()->end())
1563 // Terminate after LastMI.
1564 History.push_back(LastMI);
1568 History.push_back(MI);
1570 // Not a DBG_VALUE instruction.
1572 AtBlockEntry = false;
1574 // First known non-DBG_VALUE and non-frame setup location marks
1575 // the beginning of the function body.
1576 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1577 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1578 PrologEndLoc = MI->getDebugLoc();
1580 // Check if the instruction clobbers any registers with debug vars.
1581 for (MachineInstr::const_mop_iterator MOI = MI->operands_begin(),
1582 MOE = MI->operands_end(); MOI != MOE; ++MOI) {
1583 if (!MOI->isReg() || !MOI->isDef() || !MOI->getReg())
1585 for (MCRegAliasIterator AI(MOI->getReg(), TRI, true);
1586 AI.isValid(); ++AI) {
1588 const MDNode *Var = LiveUserVar[Reg];
1591 // Reg is now clobbered.
1592 LiveUserVar[Reg] = 0;
1594 // Was MD last defined by a DBG_VALUE referring to Reg?
1595 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1596 if (HistI == DbgValues.end())
1598 SmallVectorImpl<const MachineInstr*> &History = HistI->second;
1599 if (History.empty())
1601 const MachineInstr *Prev = History.back();
1602 // Sanity-check: Register assignments are terminated at the end of
1604 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1606 // Is the variable still in Reg?
1607 if (!isDbgValueInDefinedReg(Prev) ||
1608 Prev->getOperand(0).getReg() != Reg)
1610 // Var is clobbered. Make sure the next instruction gets a label.
1611 History.push_back(MI);
1618 for (DbgValueHistoryMap::iterator I = DbgValues.begin(), E = DbgValues.end();
1620 SmallVectorImpl<const MachineInstr*> &History = I->second;
1621 if (History.empty())
1624 // Make sure the final register assignments are terminated.
1625 const MachineInstr *Prev = History.back();
1626 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1627 const MachineBasicBlock *PrevMBB = Prev->getParent();
1628 MachineBasicBlock::const_iterator LastMI =
1629 PrevMBB->getLastNonDebugInstr();
1630 if (LastMI == PrevMBB->end())
1631 // Drop DBG_VALUE for empty range.
1633 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1634 // Terminate after LastMI.
1635 History.push_back(LastMI);
1638 // Request labels for the full history.
1639 for (unsigned i = 0, e = History.size(); i != e; ++i) {
1640 const MachineInstr *MI = History[i];
1641 if (MI->isDebugValue())
1642 requestLabelBeforeInsn(MI);
1644 requestLabelAfterInsn(MI);
1648 PrevInstLoc = DebugLoc();
1649 PrevLabel = FunctionBeginSym;
1651 // Record beginning of function.
1652 if (!PrologEndLoc.isUnknown()) {
1653 DebugLoc FnStartDL = getFnDebugLoc(PrologEndLoc,
1654 MF->getFunction()->getContext());
1655 recordSourceLine(FnStartDL.getLine(), FnStartDL.getCol(),
1656 FnStartDL.getScope(MF->getFunction()->getContext()),
1657 // We'd like to list the prologue as "not statements" but GDB behaves
1658 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1659 DWARF2_FLAG_IS_STMT);
1663 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1664 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1665 DIVariable DV = Var->getVariable();
1666 // Variables with positive arg numbers are parameters.
1667 if (unsigned ArgNum = DV.getArgNumber()) {
1668 // Keep all parameters in order at the start of the variable list to ensure
1669 // function types are correct (no out-of-order parameters)
1671 // This could be improved by only doing it for optimized builds (unoptimized
1672 // builds have the right order to begin with), searching from the back (this
1673 // would catch the unoptimized case quickly), or doing a binary search
1674 // rather than linear search.
1675 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1676 while (I != Vars.end()) {
1677 unsigned CurNum = (*I)->getVariable().getArgNumber();
1678 // A local (non-parameter) variable has been found, insert immediately
1682 // A later indexed parameter has been found, insert immediately before it.
1683 if (CurNum > ArgNum)
1687 Vars.insert(I, Var);
1691 Vars.push_back(Var);
1694 // Gather and emit post-function debug information.
1695 void DwarfDebug::endFunction(const MachineFunction *MF) {
1696 if (!MMI->hasDebugInfo() || LScopes.empty()) return;
1698 // Define end label for subprogram.
1699 FunctionEndSym = Asm->GetTempSymbol("func_end",
1700 Asm->getFunctionNumber());
1701 // Assumes in correct section after the entry point.
1702 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1703 // Set DwarfCompileUnitID in MCContext to default value.
1704 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1706 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1707 collectVariableInfo(MF, ProcessedVars);
1709 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1710 CompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1711 assert(TheCU && "Unable to find compile unit!");
1713 // Construct abstract scopes.
1714 ArrayRef<LexicalScope *> AList = LScopes.getAbstractScopesList();
1715 for (unsigned i = 0, e = AList.size(); i != e; ++i) {
1716 LexicalScope *AScope = AList[i];
1717 DISubprogram SP(AScope->getScopeNode());
1718 if (SP.isSubprogram()) {
1719 // Collect info for variables that were optimized out.
1720 DIArray Variables = SP.getVariables();
1721 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1722 DIVariable DV(Variables.getElement(i));
1723 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1725 // Check that DbgVariable for DV wasn't created earlier, when
1726 // findAbstractVariable() was called for inlined instance of DV.
1727 LLVMContext &Ctx = DV->getContext();
1728 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1729 if (AbstractVariables.lookup(CleanDV))
1731 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1732 addScopeVariable(Scope, new DbgVariable(DV, NULL));
1735 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1736 constructScopeDIE(TheCU, AScope);
1739 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1741 if (!MF->getTarget().Options.DisableFramePointerElim(*MF))
1742 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1745 for (ScopeVariablesMap::iterator
1746 I = ScopeVariables.begin(), E = ScopeVariables.end(); I != E; ++I)
1747 DeleteContainerPointers(I->second);
1748 ScopeVariables.clear();
1749 DeleteContainerPointers(CurrentFnArguments);
1750 UserVariables.clear();
1752 AbstractVariables.clear();
1753 LabelsBeforeInsn.clear();
1754 LabelsAfterInsn.clear();
1758 // Register a source line with debug info. Returns the unique label that was
1759 // emitted and which provides correspondence to the source line list.
1760 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1766 DIDescriptor Scope(S);
1768 if (Scope.isCompileUnit()) {
1769 DICompileUnit CU(S);
1770 Fn = CU.getFilename();
1771 Dir = CU.getDirectory();
1772 } else if (Scope.isFile()) {
1774 Fn = F.getFilename();
1775 Dir = F.getDirectory();
1776 } else if (Scope.isSubprogram()) {
1778 Fn = SP.getFilename();
1779 Dir = SP.getDirectory();
1780 } else if (Scope.isLexicalBlockFile()) {
1781 DILexicalBlockFile DBF(S);
1782 Fn = DBF.getFilename();
1783 Dir = DBF.getDirectory();
1784 } else if (Scope.isLexicalBlock()) {
1785 DILexicalBlock DB(S);
1786 Fn = DB.getFilename();
1787 Dir = DB.getDirectory();
1789 llvm_unreachable("Unexpected scope info");
1791 Src = getOrCreateSourceID(Fn, Dir,
1792 Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1794 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0, 0, Fn);
1797 //===----------------------------------------------------------------------===//
1799 //===----------------------------------------------------------------------===//
1801 // Compute the size and offset of a DIE.
1803 DwarfUnits::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1804 // Get the children.
1805 const std::vector<DIE *> &Children = Die->getChildren();
1807 // Record the abbreviation.
1808 assignAbbrevNumber(Die->getAbbrev());
1810 // Get the abbreviation for this DIE.
1811 unsigned AbbrevNumber = Die->getAbbrevNumber();
1812 const DIEAbbrev *Abbrev = Abbreviations->at(AbbrevNumber - 1);
1815 Die->setOffset(Offset);
1817 // Start the size with the size of abbreviation code.
1818 Offset += MCAsmInfo::getULEB128Size(AbbrevNumber);
1820 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1821 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1823 // Size the DIE attribute values.
1824 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1825 // Size attribute value.
1826 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1828 // Size the DIE children if any.
1829 if (!Children.empty()) {
1830 assert(Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes &&
1831 "Children flag not set");
1833 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1834 Offset = computeSizeAndOffset(Children[j], Offset);
1836 // End of children marker.
1837 Offset += sizeof(int8_t);
1840 Die->setSize(Offset - Die->getOffset());
1844 // Compute the size and offset of all the DIEs.
1845 void DwarfUnits::computeSizeAndOffsets() {
1846 // Offset from the beginning of debug info section.
1847 unsigned SecOffset = 0;
1848 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
1849 E = CUs.end(); I != E; ++I) {
1850 (*I)->setDebugInfoOffset(SecOffset);
1852 sizeof(int32_t) + // Length of Compilation Unit Info
1853 sizeof(int16_t) + // DWARF version number
1854 sizeof(int32_t) + // Offset Into Abbrev. Section
1855 sizeof(int8_t); // Pointer Size (in bytes)
1857 unsigned EndOffset = computeSizeAndOffset((*I)->getCUDie(), Offset);
1858 SecOffset += EndOffset;
1862 // Emit initial Dwarf sections with a label at the start of each one.
1863 void DwarfDebug::emitSectionLabels() {
1864 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1866 // Dwarf sections base addresses.
1867 DwarfInfoSectionSym =
1868 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1869 DwarfAbbrevSectionSym =
1870 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1871 if (useSplitDwarf())
1872 DwarfAbbrevDWOSectionSym =
1873 emitSectionSym(Asm, TLOF.getDwarfAbbrevDWOSection(),
1874 "section_abbrev_dwo");
1875 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1877 if (const MCSection *MacroInfo = TLOF.getDwarfMacroInfoSection())
1878 emitSectionSym(Asm, MacroInfo);
1880 DwarfLineSectionSym =
1881 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1882 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1883 if (HasDwarfPubSections) {
1884 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1885 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1887 DwarfStrSectionSym =
1888 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1889 if (useSplitDwarf()) {
1890 DwarfStrDWOSectionSym =
1891 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1892 DwarfAddrSectionSym =
1893 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1895 DwarfDebugRangeSectionSym = emitSectionSym(Asm, TLOF.getDwarfRangesSection(),
1898 DwarfDebugLocSectionSym = emitSectionSym(Asm, TLOF.getDwarfLocSection(),
1899 "section_debug_loc");
1901 TextSectionSym = emitSectionSym(Asm, TLOF.getTextSection(), "text_begin");
1902 emitSectionSym(Asm, TLOF.getDataSection());
1905 // Recursively emits a debug information entry.
1906 void DwarfDebug::emitDIE(DIE *Die, std::vector<DIEAbbrev *> *Abbrevs) {
1907 // Get the abbreviation for this DIE.
1908 unsigned AbbrevNumber = Die->getAbbrevNumber();
1909 const DIEAbbrev *Abbrev = Abbrevs->at(AbbrevNumber - 1);
1911 // Emit the code (index) for the abbreviation.
1912 if (Asm->isVerbose())
1913 Asm->OutStreamer.AddComment("Abbrev [" + Twine(AbbrevNumber) + "] 0x" +
1914 Twine::utohexstr(Die->getOffset()) + ":0x" +
1915 Twine::utohexstr(Die->getSize()) + " " +
1916 dwarf::TagString(Abbrev->getTag()));
1917 Asm->EmitULEB128(AbbrevNumber);
1919 const SmallVectorImpl<DIEValue*> &Values = Die->getValues();
1920 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev->getData();
1922 // Emit the DIE attribute values.
1923 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1924 unsigned Attr = AbbrevData[i].getAttribute();
1925 unsigned Form = AbbrevData[i].getForm();
1926 assert(Form && "Too many attributes for DIE (check abbreviation)");
1928 if (Asm->isVerbose())
1929 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1932 case dwarf::DW_AT_abstract_origin: {
1933 DIEEntry *E = cast<DIEEntry>(Values[i]);
1934 DIE *Origin = E->getEntry();
1935 unsigned Addr = Origin->getOffset();
1936 if (Form == dwarf::DW_FORM_ref_addr) {
1937 // For DW_FORM_ref_addr, output the offset from beginning of debug info
1938 // section. Origin->getOffset() returns the offset from start of the
1940 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1941 Addr += Holder.getCUOffset(Origin->getCompileUnit());
1943 Asm->OutStreamer.EmitIntValue(Addr,
1944 Form == dwarf::DW_FORM_ref_addr ? DIEEntry::getRefAddrSize(Asm) : 4);
1947 case dwarf::DW_AT_ranges: {
1948 // DW_AT_range Value encodes offset in debug_range section.
1949 DIEInteger *V = cast<DIEInteger>(Values[i]);
1951 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) {
1952 Asm->EmitLabelPlusOffset(DwarfDebugRangeSectionSym,
1956 Asm->EmitLabelOffsetDifference(DwarfDebugRangeSectionSym,
1958 DwarfDebugRangeSectionSym,
1963 case dwarf::DW_AT_location: {
1964 if (DIELabel *L = dyn_cast<DIELabel>(Values[i])) {
1965 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
1966 Asm->EmitLabelReference(L->getValue(), 4);
1968 Asm->EmitLabelDifference(L->getValue(), DwarfDebugLocSectionSym, 4);
1970 Values[i]->EmitValue(Asm, Form);
1974 case dwarf::DW_AT_accessibility: {
1975 if (Asm->isVerbose()) {
1976 DIEInteger *V = cast<DIEInteger>(Values[i]);
1977 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(V->getValue()));
1979 Values[i]->EmitValue(Asm, Form);
1983 // Emit an attribute using the defined form.
1984 Values[i]->EmitValue(Asm, Form);
1989 // Emit the DIE children if any.
1990 if (Abbrev->getChildrenFlag() == dwarf::DW_CHILDREN_yes) {
1991 const std::vector<DIE *> &Children = Die->getChildren();
1993 for (unsigned j = 0, M = Children.size(); j < M; ++j)
1994 emitDIE(Children[j], Abbrevs);
1996 if (Asm->isVerbose())
1997 Asm->OutStreamer.AddComment("End Of Children Mark");
2002 // Emit the various dwarf units to the unit section USection with
2003 // the abbreviations going into ASection.
2004 void DwarfUnits::emitUnits(DwarfDebug *DD,
2005 const MCSection *USection,
2006 const MCSection *ASection,
2007 const MCSymbol *ASectionSym) {
2008 Asm->OutStreamer.SwitchSection(USection);
2009 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(),
2010 E = CUs.end(); I != E; ++I) {
2011 CompileUnit *TheCU = *I;
2012 DIE *Die = TheCU->getCUDie();
2014 // Emit the compile units header.
2016 .EmitLabel(Asm->GetTempSymbol(USection->getLabelBeginName(),
2017 TheCU->getUniqueID()));
2019 // Emit size of content not including length itself
2020 unsigned ContentSize = Die->getSize() +
2021 sizeof(int16_t) + // DWARF version number
2022 sizeof(int32_t) + // Offset Into Abbrev. Section
2023 sizeof(int8_t); // Pointer Size (in bytes)
2025 Asm->OutStreamer.AddComment("Length of Compilation Unit Info");
2026 Asm->EmitInt32(ContentSize);
2027 Asm->OutStreamer.AddComment("DWARF version number");
2028 Asm->EmitInt16(DD->getDwarfVersion());
2029 Asm->OutStreamer.AddComment("Offset Into Abbrev. Section");
2030 Asm->EmitSectionOffset(Asm->GetTempSymbol(ASection->getLabelBeginName()),
2032 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2033 Asm->EmitInt8(Asm->getDataLayout().getPointerSize());
2035 DD->emitDIE(Die, Abbreviations);
2036 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol(USection->getLabelEndName(),
2037 TheCU->getUniqueID()));
2041 /// For a given compile unit DIE, returns offset from beginning of debug info.
2042 unsigned DwarfUnits::getCUOffset(DIE *Die) {
2043 assert(Die->getTag() == dwarf::DW_TAG_compile_unit &&
2044 "Input DIE should be compile unit in getCUOffset.");
2045 for (SmallVectorImpl<CompileUnit *>::iterator I = CUs.begin(), E = CUs.end();
2047 CompileUnit *TheCU = *I;
2048 if (TheCU->getCUDie() == Die)
2049 return TheCU->getDebugInfoOffset();
2051 llvm_unreachable("The compile unit DIE should belong to CUs in DwarfUnits.");
2054 // Emit the debug info section.
2055 void DwarfDebug::emitDebugInfo() {
2056 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2058 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoSection(),
2059 Asm->getObjFileLowering().getDwarfAbbrevSection(),
2060 DwarfAbbrevSectionSym);
2063 // Emit the abbreviation section.
2064 void DwarfDebug::emitAbbreviations() {
2065 if (!useSplitDwarf())
2066 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection(),
2069 emitSkeletonAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2072 void DwarfDebug::emitAbbrevs(const MCSection *Section,
2073 std::vector<DIEAbbrev *> *Abbrevs) {
2074 // Check to see if it is worth the effort.
2075 if (!Abbrevs->empty()) {
2076 // Start the debug abbrev section.
2077 Asm->OutStreamer.SwitchSection(Section);
2079 MCSymbol *Begin = Asm->GetTempSymbol(Section->getLabelBeginName());
2080 Asm->OutStreamer.EmitLabel(Begin);
2082 // For each abbrevation.
2083 for (unsigned i = 0, N = Abbrevs->size(); i < N; ++i) {
2084 // Get abbreviation data
2085 const DIEAbbrev *Abbrev = Abbrevs->at(i);
2087 // Emit the abbrevations code (base 1 index.)
2088 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2090 // Emit the abbreviations data.
2094 // Mark end of abbreviations.
2095 Asm->EmitULEB128(0, "EOM(3)");
2097 MCSymbol *End = Asm->GetTempSymbol(Section->getLabelEndName());
2098 Asm->OutStreamer.EmitLabel(End);
2102 // Emit the last address of the section and the end of the line matrix.
2103 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2104 // Define last address of section.
2105 Asm->OutStreamer.AddComment("Extended Op");
2108 Asm->OutStreamer.AddComment("Op size");
2109 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2110 Asm->OutStreamer.AddComment("DW_LNE_set_address");
2111 Asm->EmitInt8(dwarf::DW_LNE_set_address);
2113 Asm->OutStreamer.AddComment("Section end label");
2115 Asm->OutStreamer.EmitSymbolValue(Asm->GetTempSymbol("section_end",SectionEnd),
2116 Asm->getDataLayout().getPointerSize());
2118 // Mark end of matrix.
2119 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2125 // Emit visible names into a hashed accelerator table section.
2126 void DwarfDebug::emitAccelNames() {
2127 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2128 dwarf::DW_FORM_data4));
2129 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2130 E = CUMap.end(); I != E; ++I) {
2131 CompileUnit *TheCU = I->second;
2132 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNames();
2133 for (StringMap<std::vector<DIE*> >::const_iterator
2134 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2135 StringRef Name = GI->getKey();
2136 const std::vector<DIE *> &Entities = GI->second;
2137 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2138 DE = Entities.end(); DI != DE; ++DI)
2139 AT.AddName(Name, (*DI));
2143 AT.FinalizeTable(Asm, "Names");
2144 Asm->OutStreamer.SwitchSection(
2145 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2146 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2147 Asm->OutStreamer.EmitLabel(SectionBegin);
2149 // Emit the full data.
2150 AT.Emit(Asm, SectionBegin, &InfoHolder);
2153 // Emit objective C classes and categories into a hashed accelerator table
2155 void DwarfDebug::emitAccelObjC() {
2156 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2157 dwarf::DW_FORM_data4));
2158 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2159 E = CUMap.end(); I != E; ++I) {
2160 CompileUnit *TheCU = I->second;
2161 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelObjC();
2162 for (StringMap<std::vector<DIE*> >::const_iterator
2163 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2164 StringRef Name = GI->getKey();
2165 const std::vector<DIE *> &Entities = GI->second;
2166 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2167 DE = Entities.end(); DI != DE; ++DI)
2168 AT.AddName(Name, (*DI));
2172 AT.FinalizeTable(Asm, "ObjC");
2173 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2174 .getDwarfAccelObjCSection());
2175 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2176 Asm->OutStreamer.EmitLabel(SectionBegin);
2178 // Emit the full data.
2179 AT.Emit(Asm, SectionBegin, &InfoHolder);
2182 // Emit namespace dies into a hashed accelerator table.
2183 void DwarfDebug::emitAccelNamespaces() {
2184 DwarfAccelTable AT(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2185 dwarf::DW_FORM_data4));
2186 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2187 E = CUMap.end(); I != E; ++I) {
2188 CompileUnit *TheCU = I->second;
2189 const StringMap<std::vector<DIE*> > &Names = TheCU->getAccelNamespace();
2190 for (StringMap<std::vector<DIE*> >::const_iterator
2191 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2192 StringRef Name = GI->getKey();
2193 const std::vector<DIE *> &Entities = GI->second;
2194 for (std::vector<DIE *>::const_iterator DI = Entities.begin(),
2195 DE = Entities.end(); DI != DE; ++DI)
2196 AT.AddName(Name, (*DI));
2200 AT.FinalizeTable(Asm, "namespac");
2201 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2202 .getDwarfAccelNamespaceSection());
2203 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2204 Asm->OutStreamer.EmitLabel(SectionBegin);
2206 // Emit the full data.
2207 AT.Emit(Asm, SectionBegin, &InfoHolder);
2210 // Emit type dies into a hashed accelerator table.
2211 void DwarfDebug::emitAccelTypes() {
2212 std::vector<DwarfAccelTable::Atom> Atoms;
2213 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeDIEOffset,
2214 dwarf::DW_FORM_data4));
2215 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTag,
2216 dwarf::DW_FORM_data2));
2217 Atoms.push_back(DwarfAccelTable::Atom(DwarfAccelTable::eAtomTypeTypeFlags,
2218 dwarf::DW_FORM_data1));
2219 DwarfAccelTable AT(Atoms);
2220 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2221 E = CUMap.end(); I != E; ++I) {
2222 CompileUnit *TheCU = I->second;
2223 const StringMap<std::vector<std::pair<DIE*, unsigned > > > &Names
2224 = TheCU->getAccelTypes();
2225 for (StringMap<std::vector<std::pair<DIE*, unsigned> > >::const_iterator
2226 GI = Names.begin(), GE = Names.end(); GI != GE; ++GI) {
2227 StringRef Name = GI->getKey();
2228 const std::vector<std::pair<DIE *, unsigned> > &Entities = GI->second;
2229 for (std::vector<std::pair<DIE *, unsigned> >::const_iterator DI
2230 = Entities.begin(), DE = Entities.end(); DI !=DE; ++DI)
2231 AT.AddName(Name, (*DI).first, (*DI).second);
2235 AT.FinalizeTable(Asm, "types");
2236 Asm->OutStreamer.SwitchSection(Asm->getObjFileLowering()
2237 .getDwarfAccelTypesSection());
2238 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2239 Asm->OutStreamer.EmitLabel(SectionBegin);
2241 // Emit the full data.
2242 AT.Emit(Asm, SectionBegin, &InfoHolder);
2245 /// emitDebugPubnames - Emit visible names into a debug pubnames section.
2247 void DwarfDebug::emitDebugPubnames() {
2248 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2250 typedef DenseMap<const MDNode*, CompileUnit*> CUMapType;
2251 for (CUMapType::iterator I = CUMap.begin(), E = CUMap.end(); I != E; ++I) {
2252 CompileUnit *TheCU = I->second;
2253 unsigned ID = TheCU->getUniqueID();
2255 if (TheCU->getGlobalNames().empty())
2258 // Start the dwarf pubnames section.
2260 .SwitchSection(Asm->getObjFileLowering().getDwarfPubNamesSection());
2262 Asm->OutStreamer.AddComment("Length of Public Names Info");
2263 Asm->EmitLabelDifference(Asm->GetTempSymbol("pubnames_end", ID),
2264 Asm->GetTempSymbol("pubnames_begin", ID), 4);
2266 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_begin", ID));
2268 Asm->OutStreamer.AddComment("DWARF Version");
2269 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2271 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2272 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2273 DwarfInfoSectionSym);
2275 Asm->OutStreamer.AddComment("Compilation Unit Length");
2276 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(), ID),
2277 Asm->GetTempSymbol(ISec->getLabelBeginName(), ID),
2280 const StringMap<DIE*> &Globals = TheCU->getGlobalNames();
2281 for (StringMap<DIE*>::const_iterator
2282 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2283 const char *Name = GI->getKeyData();
2284 const DIE *Entity = GI->second;
2286 Asm->OutStreamer.AddComment("DIE offset");
2287 Asm->EmitInt32(Entity->getOffset());
2289 if (Asm->isVerbose())
2290 Asm->OutStreamer.AddComment("External Name");
2291 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2294 Asm->OutStreamer.AddComment("End Mark");
2296 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubnames_end", ID));
2300 void DwarfDebug::emitDebugPubTypes() {
2301 for (DenseMap<const MDNode *, CompileUnit *>::iterator I = CUMap.begin(),
2302 E = CUMap.end(); I != E; ++I) {
2303 CompileUnit *TheCU = I->second;
2304 // Start the dwarf pubtypes section.
2305 Asm->OutStreamer.SwitchSection(
2306 Asm->getObjFileLowering().getDwarfPubTypesSection());
2307 Asm->OutStreamer.AddComment("Length of Public Types Info");
2308 Asm->EmitLabelDifference(
2309 Asm->GetTempSymbol("pubtypes_end", TheCU->getUniqueID()),
2310 Asm->GetTempSymbol("pubtypes_begin", TheCU->getUniqueID()), 4);
2312 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_begin",
2313 TheCU->getUniqueID()));
2315 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DWARF Version");
2316 Asm->EmitInt16(dwarf::DW_PUBTYPES_VERSION);
2318 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2319 const MCSection *ISec = Asm->getObjFileLowering().getDwarfInfoSection();
2320 Asm->EmitSectionOffset(Asm->GetTempSymbol(ISec->getLabelBeginName(),
2321 TheCU->getUniqueID()),
2322 DwarfInfoSectionSym);
2324 Asm->OutStreamer.AddComment("Compilation Unit Length");
2325 Asm->EmitLabelDifference(Asm->GetTempSymbol(ISec->getLabelEndName(),
2326 TheCU->getUniqueID()),
2327 Asm->GetTempSymbol(ISec->getLabelBeginName(),
2328 TheCU->getUniqueID()),
2331 const StringMap<DIE*> &Globals = TheCU->getGlobalTypes();
2332 for (StringMap<DIE*>::const_iterator
2333 GI = Globals.begin(), GE = Globals.end(); GI != GE; ++GI) {
2334 const char *Name = GI->getKeyData();
2335 DIE *Entity = GI->second;
2337 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("DIE offset");
2338 Asm->EmitInt32(Entity->getOffset());
2340 if (Asm->isVerbose()) Asm->OutStreamer.AddComment("External Name");
2341 // Emit the name with a terminating null byte.
2342 Asm->OutStreamer.EmitBytes(StringRef(Name, GI->getKeyLength()+1));
2345 Asm->OutStreamer.AddComment("End Mark");
2347 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("pubtypes_end",
2348 TheCU->getUniqueID()));
2352 // Emit strings into a string section.
2353 void DwarfUnits::emitStrings(const MCSection *StrSection,
2354 const MCSection *OffsetSection = NULL,
2355 const MCSymbol *StrSecSym = NULL) {
2357 if (StringPool.empty()) return;
2359 // Start the dwarf str section.
2360 Asm->OutStreamer.SwitchSection(StrSection);
2362 // Get all of the string pool entries and put them in an array by their ID so
2363 // we can sort them.
2364 SmallVector<std::pair<unsigned,
2365 StringMapEntry<std::pair<MCSymbol*, unsigned> >*>, 64> Entries;
2367 for (StringMap<std::pair<MCSymbol*, unsigned> >::iterator
2368 I = StringPool.begin(), E = StringPool.end();
2370 Entries.push_back(std::make_pair(I->second.second, &*I));
2372 array_pod_sort(Entries.begin(), Entries.end());
2374 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2375 // Emit a label for reference from debug information entries.
2376 Asm->OutStreamer.EmitLabel(Entries[i].second->getValue().first);
2378 // Emit the string itself with a terminating null byte.
2379 Asm->OutStreamer.EmitBytes(StringRef(Entries[i].second->getKeyData(),
2380 Entries[i].second->getKeyLength()+1));
2383 // If we've got an offset section go ahead and emit that now as well.
2384 if (OffsetSection) {
2385 Asm->OutStreamer.SwitchSection(OffsetSection);
2386 unsigned offset = 0;
2387 unsigned size = 4; // FIXME: DWARF64 is 8.
2388 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2389 Asm->OutStreamer.EmitIntValue(offset, size);
2390 offset += Entries[i].second->getKeyLength() + 1;
2395 // Emit strings into a string section.
2396 void DwarfUnits::emitAddresses(const MCSection *AddrSection) {
2398 if (AddressPool.empty()) return;
2400 // Start the dwarf addr section.
2401 Asm->OutStreamer.SwitchSection(AddrSection);
2403 // Order the address pool entries by ID
2404 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2406 for (DenseMap<const MCExpr *, unsigned>::iterator I = AddressPool.begin(),
2407 E = AddressPool.end();
2409 Entries[I->second] = I->first;
2411 for (unsigned i = 0, e = Entries.size(); i != e; ++i) {
2412 // Emit an expression for reference from debug information entries.
2413 if (const MCExpr *Expr = Entries[i])
2414 Asm->OutStreamer.EmitValue(Expr, Asm->getDataLayout().getPointerSize());
2416 Asm->OutStreamer.EmitIntValue(0, Asm->getDataLayout().getPointerSize());
2421 // Emit visible names into a debug str section.
2422 void DwarfDebug::emitDebugStr() {
2423 DwarfUnits &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2424 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2427 // Emit locations into the debug loc section.
2428 void DwarfDebug::emitDebugLoc() {
2429 if (DotDebugLocEntries.empty())
2432 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2433 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2435 DotDebugLocEntry &Entry = *I;
2436 if (I + 1 != DotDebugLocEntries.end())
2440 // Start the dwarf loc section.
2441 Asm->OutStreamer.SwitchSection(
2442 Asm->getObjFileLowering().getDwarfLocSection());
2443 unsigned char Size = Asm->getDataLayout().getPointerSize();
2444 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2446 for (SmallVectorImpl<DotDebugLocEntry>::iterator
2447 I = DotDebugLocEntries.begin(), E = DotDebugLocEntries.end();
2448 I != E; ++I, ++index) {
2449 DotDebugLocEntry &Entry = *I;
2450 if (Entry.isMerged()) continue;
2451 if (Entry.isEmpty()) {
2452 Asm->OutStreamer.EmitIntValue(0, Size);
2453 Asm->OutStreamer.EmitIntValue(0, Size);
2454 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2456 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2457 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2458 DIVariable DV(Entry.getVariable());
2459 Asm->OutStreamer.AddComment("Loc expr size");
2460 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2461 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2462 Asm->EmitLabelDifference(end, begin, 2);
2463 Asm->OutStreamer.EmitLabel(begin);
2464 if (Entry.isInt()) {
2465 DIBasicType BTy(DV.getType());
2467 (BTy.getEncoding() == dwarf::DW_ATE_signed
2468 || BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2469 Asm->OutStreamer.AddComment("DW_OP_consts");
2470 Asm->EmitInt8(dwarf::DW_OP_consts);
2471 Asm->EmitSLEB128(Entry.getInt());
2473 Asm->OutStreamer.AddComment("DW_OP_constu");
2474 Asm->EmitInt8(dwarf::DW_OP_constu);
2475 Asm->EmitULEB128(Entry.getInt());
2477 } else if (Entry.isLocation()) {
2478 MachineLocation Loc = Entry.getLoc();
2479 if (!DV.hasComplexAddress())
2481 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2483 // Complex address entry.
2484 unsigned N = DV.getNumAddrElements();
2486 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2487 if (Loc.getOffset()) {
2489 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2490 Asm->OutStreamer.AddComment("DW_OP_deref");
2491 Asm->EmitInt8(dwarf::DW_OP_deref);
2492 Asm->OutStreamer.AddComment("DW_OP_plus_uconst");
2493 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2494 Asm->EmitSLEB128(DV.getAddrElement(1));
2496 // If first address element is OpPlus then emit
2497 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2498 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2499 Asm->EmitDwarfRegOp(TLoc, DV.isIndirect());
2503 Asm->EmitDwarfRegOp(Loc, DV.isIndirect());
2506 // Emit remaining complex address elements.
2507 for (; i < N; ++i) {
2508 uint64_t Element = DV.getAddrElement(i);
2509 if (Element == DIBuilder::OpPlus) {
2510 Asm->EmitInt8(dwarf::DW_OP_plus_uconst);
2511 Asm->EmitULEB128(DV.getAddrElement(++i));
2512 } else if (Element == DIBuilder::OpDeref) {
2514 Asm->EmitInt8(dwarf::DW_OP_deref);
2516 llvm_unreachable("unknown Opcode found in complex address");
2520 // else ... ignore constant fp. There is not any good way to
2521 // to represent them here in dwarf.
2522 Asm->OutStreamer.EmitLabel(end);
2527 // Emit visible names into a debug aranges section.
2528 void DwarfDebug::emitDebugARanges() {
2529 // Start the dwarf aranges section.
2531 .SwitchSection(Asm->getObjFileLowering().getDwarfARangesSection());
2534 // Emit visible names into a debug ranges section.
2535 void DwarfDebug::emitDebugRanges() {
2536 // Start the dwarf ranges section.
2538 .SwitchSection(Asm->getObjFileLowering().getDwarfRangesSection());
2539 unsigned char Size = Asm->getDataLayout().getPointerSize();
2540 for (SmallVectorImpl<const MCSymbol *>::iterator
2541 I = DebugRangeSymbols.begin(), E = DebugRangeSymbols.end();
2544 Asm->OutStreamer.EmitSymbolValue(const_cast<MCSymbol*>(*I), Size);
2546 Asm->OutStreamer.EmitIntValue(0, Size);
2550 // Emit visible names into a debug macinfo section.
2551 void DwarfDebug::emitDebugMacInfo() {
2552 if (const MCSection *LineInfo =
2553 Asm->getObjFileLowering().getDwarfMacroInfoSection()) {
2554 // Start the dwarf macinfo section.
2555 Asm->OutStreamer.SwitchSection(LineInfo);
2559 // DWARF5 Experimental Separate Dwarf emitters.
2561 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2562 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2563 // DW_AT_ranges_base, DW_AT_addr_base. If DW_AT_ranges is present,
2564 // DW_AT_low_pc and DW_AT_high_pc are not used, and vice versa.
2565 CompileUnit *DwarfDebug::constructSkeletonCU(const CompileUnit *CU) {
2567 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2568 CompileUnit *NewCU = new CompileUnit(CU->getUniqueID(), Die, CU->getNode(),
2569 Asm, this, &SkeletonHolder);
2571 NewCU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2572 DICompileUnit(CU->getNode()).getSplitDebugFilename());
2574 // Relocate to the beginning of the addr_base section, else 0 for the
2575 // beginning of the one for this compile unit.
2576 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2577 NewCU->addLabel(Die, dwarf::DW_AT_GNU_addr_base, dwarf::DW_FORM_sec_offset,
2578 DwarfAddrSectionSym);
2580 NewCU->addUInt(Die, dwarf::DW_AT_GNU_addr_base,
2581 dwarf::DW_FORM_sec_offset, 0);
2583 // 2.17.1 requires that we use DW_AT_low_pc for a single entry point
2584 // into an entity. We're using 0, or a NULL label for this.
2585 NewCU->addUInt(Die, dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
2587 // DW_AT_stmt_list is a offset of line number information for this
2588 // compile unit in debug_line section.
2589 // FIXME: Should handle multiple compile units.
2590 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2591 NewCU->addLabel(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset,
2592 DwarfLineSectionSym);
2594 NewCU->addUInt(Die, dwarf::DW_AT_stmt_list, dwarf::DW_FORM_sec_offset, 0);
2596 if (!CompilationDir.empty())
2597 NewCU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2599 SkeletonHolder.addUnit(NewCU);
2600 SkeletonCUs.push_back(NewCU);
2605 void DwarfDebug::emitSkeletonAbbrevs(const MCSection *Section) {
2606 assert(useSplitDwarf() && "No split dwarf debug info?");
2607 emitAbbrevs(Section, &SkeletonAbbrevs);
2610 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2611 // compile units that would normally be in debug_info.
2612 void DwarfDebug::emitDebugInfoDWO() {
2613 assert(useSplitDwarf() && "No split dwarf debug info?");
2614 InfoHolder.emitUnits(this, Asm->getObjFileLowering().getDwarfInfoDWOSection(),
2615 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2616 DwarfAbbrevDWOSectionSym);
2619 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2620 // abbreviations for the .debug_info.dwo section.
2621 void DwarfDebug::emitDebugAbbrevDWO() {
2622 assert(useSplitDwarf() && "No split dwarf?");
2623 emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2627 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2628 // string section and is identical in format to traditional .debug_str
2630 void DwarfDebug::emitDebugStrDWO() {
2631 assert(useSplitDwarf() && "No split dwarf?");
2632 const MCSection *OffSec = Asm->getObjFileLowering()
2633 .getDwarfStrOffDWOSection();
2634 const MCSymbol *StrSym = DwarfStrSectionSym;
2635 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),