1 //===-- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ---------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "dwarfdebug"
15 #include "ByteStreamer.h"
16 #include "DwarfDebug.h"
17 #include "DIE.h"
18 #include "DIEHash.h"
19 #include "DwarfAccelTable.h"
20 #include "DwarfUnit.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DIBuilder.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DebugInfo.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCSection.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/MC/MCSymbol.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Dwarf.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/LEB128.h"
44 #include "llvm/Support/MD5.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/Timer.h"
47 #include "llvm/Target/TargetFrameLowering.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Target/TargetMachine.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include "llvm/Target/TargetRegisterInfo.h"
52 using namespace llvm;
54 static cl::opt<bool>
55 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
56 cl::desc("Disable debug info printing"));
58 static cl::opt<bool> UnknownLocations(
59 "use-unknown-locations", cl::Hidden,
60 cl::desc("Make an absence of debug location information explicit."),
61 cl::init(false));
63 static cl::opt<bool>
64 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
65 cl::desc("Generate GNU-style pubnames and pubtypes"),
66 cl::init(false));
68 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
69 cl::Hidden,
70 cl::desc("Generate dwarf aranges"),
71 cl::init(false));
73 namespace {
74 enum DefaultOnOff { Default, Enable, Disable };
75 }
77 static cl::opt<DefaultOnOff>
78 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
79 cl::desc("Output prototype dwarf accelerator tables."),
80 cl::values(clEnumVal(Default, "Default for platform"),
81 clEnumVal(Enable, "Enabled"),
82 clEnumVal(Disable, "Disabled"), clEnumValEnd),
83 cl::init(Default));
85 static cl::opt<DefaultOnOff>
86 SplitDwarf("split-dwarf", cl::Hidden,
87 cl::desc("Output DWARF5 split debug info."),
88 cl::values(clEnumVal(Default, "Default for platform"),
89 clEnumVal(Enable, "Enabled"),
90 clEnumVal(Disable, "Disabled"), clEnumValEnd),
91 cl::init(Default));
93 static cl::opt<DefaultOnOff>
94 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
95 cl::desc("Generate DWARF pubnames and pubtypes sections"),
96 cl::values(clEnumVal(Default, "Default for platform"),
97 clEnumVal(Enable, "Enabled"),
98 clEnumVal(Disable, "Disabled"), clEnumValEnd),
99 cl::init(Default));
101 static cl::opt<unsigned>
102 DwarfVersionNumber("dwarf-version", cl::Hidden,
103 cl::desc("Generate DWARF for dwarf version."), cl::init(0));
105 static const char *const DWARFGroupName = "DWARF Emission";
106 static const char *const DbgTimerName = "DWARF Debug Writer";
108 //===----------------------------------------------------------------------===//
110 namespace llvm {
112 /// resolve - Look in the DwarfDebug map for the MDNode that
113 /// corresponds to the reference.
114 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
115 return DD->resolve(Ref);
116 }
118 DIType DbgVariable::getType() const {
119 DIType Ty = Var.getType();
120 // FIXME: isBlockByrefVariable should be reformulated in terms of complex
121 // addresses instead.
122 if (Var.isBlockByrefVariable()) {
123 /* Byref variables, in Blocks, are declared by the programmer as
124 "SomeType VarName;", but the compiler creates a
125 __Block_byref_x_VarName struct, and gives the variable VarName
126 either the struct, or a pointer to the struct, as its type. This
127 is necessary for various behind-the-scenes things the compiler
128 needs to do with by-reference variables in blocks.
130 However, as far as the original *programmer* is concerned, the
131 variable should still have type 'SomeType', as originally declared.
133 The following function dives into the __Block_byref_x_VarName
134 struct to find the original type of the variable. This will be
135 passed back to the code generating the type for the Debug
136 Information Entry for the variable 'VarName'. 'VarName' will then
137 have the original type 'SomeType' in its debug information.
139 The original type 'SomeType' will be the type of the field named
140 'VarName' inside the __Block_byref_x_VarName struct.
142 NOTE: In order for this to not completely fail on the debugger
143 side, the Debug Information Entry for the variable VarName needs to
144 have a DW_AT_location that tells the debugger how to unwind through
145 the pointers and __Block_byref_x_VarName struct to find the actual
146 value of the variable. The function addBlockByrefType does this. */
147 DIType subType = Ty;
148 uint16_t tag = Ty.getTag();
150 if (tag == dwarf::DW_TAG_pointer_type)
151 subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
153 DIArray Elements = DICompositeType(subType).getTypeArray();
154 for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
155 DIDerivedType DT(Elements.getElement(i));
156 if (getName() == DT.getName())
157 return (resolve(DT.getTypeDerivedFrom()));
158 }
159 }
160 return Ty;
161 }
163 } // end llvm namespace
165 /// Return Dwarf Version by checking module flags.
166 static unsigned getDwarfVersionFromModule(const Module *M) {
167 Value *Val = M->getModuleFlag("Dwarf Version");
168 if (!Val)
169 return dwarf::DWARF_VERSION;
170 return cast<ConstantInt>(Val)->getZExtValue();
171 }
173 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
174 : Asm(A), MMI(Asm->MMI), FirstCU(0), PrevLabel(NULL), GlobalRangeCount(0),
175 InfoHolder(A, "info_string", DIEValueAllocator), HasCURanges(false),
176 UsedNonDefaultText(false),
177 SkeletonHolder(A, "skel_string", DIEValueAllocator) {
179 DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = 0;
180 DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = DwarfLineSectionSym = 0;
181 DwarfAddrSectionSym = 0;
182 DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = 0;
183 FunctionBeginSym = FunctionEndSym = 0;
184 CurFn = 0;
185 CurMI = 0;
187 // Turn on accelerator tables for Darwin by default, pubnames by
188 // default for non-Darwin, and handle split dwarf.
189 bool IsDarwin = Triple(A->getTargetTriple()).isOSDarwin();
191 if (DwarfAccelTables == Default)
192 HasDwarfAccelTables = IsDarwin;
193 else
194 HasDwarfAccelTables = DwarfAccelTables == Enable;
196 if (SplitDwarf == Default)
197 HasSplitDwarf = false;
198 else
199 HasSplitDwarf = SplitDwarf == Enable;
201 if (DwarfPubSections == Default)
202 HasDwarfPubSections = !IsDarwin;
203 else
204 HasDwarfPubSections = DwarfPubSections == Enable;
206 DwarfVersion = DwarfVersionNumber
207 ? DwarfVersionNumber
208 : getDwarfVersionFromModule(MMI->getModule());
210 {
211 NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
212 beginModule();
213 }
214 }
216 // Switch to the specified MCSection and emit an assembler
217 // temporary label to it if SymbolStem is specified.
218 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
219 const char *SymbolStem = 0) {
220 Asm->OutStreamer.SwitchSection(Section);
221 if (!SymbolStem)
222 return 0;
224 MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
225 Asm->OutStreamer.EmitLabel(TmpSym);
226 return TmpSym;
227 }
229 DwarfFile::~DwarfFile() {
230 for (DwarfUnit *DU : CUs)
231 delete DU;
232 }
234 MCSymbol *DwarfFile::getStringPoolSym() {
235 return Asm->GetTempSymbol(StringPref);
236 }
238 MCSymbol *DwarfFile::getStringPoolEntry(StringRef Str) {
239 std::pair<MCSymbol *, unsigned> &Entry =
240 StringPool.GetOrCreateValue(Str).getValue();
241 if (Entry.first)
242 return Entry.first;
244 Entry.second = NextStringPoolNumber++;
245 return Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
246 }
248 unsigned DwarfFile::getStringPoolIndex(StringRef Str) {
249 std::pair<MCSymbol *, unsigned> &Entry =
250 StringPool.GetOrCreateValue(Str).getValue();
251 if (Entry.first)
252 return Entry.second;
254 Entry.second = NextStringPoolNumber++;
255 Entry.first = Asm->GetTempSymbol(StringPref, Entry.second);
256 return Entry.second;
257 }
259 unsigned DwarfFile::getAddrPoolIndex(const MCSymbol *Sym, bool TLS) {
260 std::pair<AddrPool::iterator, bool> P = AddressPool.insert(
261 std::make_pair(Sym, AddressPoolEntry(NextAddrPoolNumber, TLS)));
262 if (P.second)
263 ++NextAddrPoolNumber;
264 return P.first->second.Number;
265 }
267 // Define a unique number for the abbreviation.
268 //
269 void DwarfFile::assignAbbrevNumber(DIEAbbrev &Abbrev) {
270 // Check the set for priors.
271 DIEAbbrev *InSet = AbbreviationsSet.GetOrInsertNode(&Abbrev);
273 // If it's newly added.
274 if (InSet == &Abbrev) {
275 // Add to abbreviation list.
276 Abbreviations.push_back(&Abbrev);
278 // Assign the vector position + 1 as its number.
279 Abbrev.setNumber(Abbreviations.size());
280 } else {
281 // Assign existing abbreviation number.
282 Abbrev.setNumber(InSet->getNumber());
283 }
284 }
286 static bool isObjCClass(StringRef Name) {
287 return Name.startswith("+") || Name.startswith("-");
288 }
290 static bool hasObjCCategory(StringRef Name) {
291 if (!isObjCClass(Name))
292 return false;
294 return Name.find(") ") != StringRef::npos;
295 }
297 static void getObjCClassCategory(StringRef In, StringRef &Class,
298 StringRef &Category) {
299 if (!hasObjCCategory(In)) {
300 Class = In.slice(In.find('[') + 1, In.find(' '));
301 Category = "";
302 return;
303 }
305 Class = In.slice(In.find('[') + 1, In.find('('));
306 Category = In.slice(In.find('[') + 1, In.find(' '));
307 return;
308 }
310 static StringRef getObjCMethodName(StringRef In) {
311 return In.slice(In.find(' ') + 1, In.find(']'));
312 }
314 // Helper for sorting sections into a stable output order.
315 static bool SectionSort(const MCSection *A, const MCSection *B) {
316 std::string LA = (A ? A->getLabelBeginName() : "");
317 std::string LB = (B ? B->getLabelBeginName() : "");
318 return LA < LB;
319 }
321 // Add the various names to the Dwarf accelerator table names.
322 // TODO: Determine whether or not we should add names for programs
323 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
324 // is only slightly different than the lookup of non-standard ObjC names.
325 static void addSubprogramNames(DwarfUnit *TheU, DISubprogram SP, DIE *Die) {
326 if (!SP.isDefinition())
327 return;
328 TheU->addAccelName(SP.getName(), Die);
330 // If the linkage name is different than the name, go ahead and output
331 // that as well into the name table.
332 if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
333 TheU->addAccelName(SP.getLinkageName(), Die);
335 // If this is an Objective-C selector name add it to the ObjC accelerator
336 // too.
337 if (isObjCClass(SP.getName())) {
338 StringRef Class, Category;
339 getObjCClassCategory(SP.getName(), Class, Category);
340 TheU->addAccelObjC(Class, Die);
341 if (Category != "")
342 TheU->addAccelObjC(Category, Die);
343 // Also add the base method name to the name table.
344 TheU->addAccelName(getObjCMethodName(SP.getName()), Die);
345 }
346 }
348 /// isSubprogramContext - Return true if Context is either a subprogram
349 /// or another context nested inside a subprogram.
350 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
351 if (!Context)
352 return false;
353 DIDescriptor D(Context);
354 if (D.isSubprogram())
355 return true;
356 if (D.isType())
357 return isSubprogramContext(resolve(DIType(Context).getContext()));
358 return false;
359 }
361 // Find DIE for the given subprogram and attach appropriate DW_AT_low_pc
362 // and DW_AT_high_pc attributes. If there are global variables in this
363 // scope then create and insert DIEs for these variables.
364 DIE *DwarfDebug::updateSubprogramScopeDIE(DwarfCompileUnit *SPCU,
365 DISubprogram SP) {
366 SP = SPCU->getOdrUniqueSubprogram(resolve(SP.getContext()), SP);
367 DIE *SPDie = SPCU->getDIE(SP);
369 assert(SPDie && "Unable to find subprogram DIE!");
371 // If we're updating an abstract DIE, then we will be adding the children and
372 // object pointer later on. But what we don't want to do is process the
373 // concrete DIE twice.
374 if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
375 // Pick up abstract subprogram DIE.
376 SPDie =
377 SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram, *SPCU->getUnitDie());
378 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_abstract_origin, AbsSPDIE);
379 } else {
380 DISubprogram SPDecl = SP.getFunctionDeclaration();
381 if (!SPDecl.isSubprogram()) {
382 // There is not any need to generate specification DIE for a function
383 // defined at compile unit level. If a function is defined inside another
384 // function then gdb prefers the definition at top level and but does not
385 // expect specification DIE in parent function. So avoid creating
386 // specification DIE for a function defined inside a function.
387 DIScope SPContext = resolve(SP.getContext());
388 if (SP.isDefinition() && !SPContext.isCompileUnit() &&
389 !SPContext.isFile() && !isSubprogramContext(SPContext)) {
390 SPCU->addFlag(SPDie, dwarf::DW_AT_declaration);
392 // Add arguments.
393 DICompositeType SPTy = SP.getType();
394 DIArray Args = SPTy.getTypeArray();
395 uint16_t SPTag = SPTy.getTag();
396 if (SPTag == dwarf::DW_TAG_subroutine_type)
397 SPCU->constructSubprogramArguments(*SPDie, Args);
398 DIE *SPDeclDie = SPDie;
399 SPDie = SPCU->createAndAddDIE(dwarf::DW_TAG_subprogram,
400 *SPCU->getUnitDie());
401 SPCU->addDIEEntry(SPDie, dwarf::DW_AT_specification, SPDeclDie);
402 }
403 }
404 }
406 attachLowHighPC(SPCU, SPDie, FunctionBeginSym, FunctionEndSym);
408 const TargetRegisterInfo *RI = Asm->TM.getRegisterInfo();
409 MachineLocation Location(RI->getFrameRegister(*Asm->MF));
410 SPCU->addAddress(SPDie, dwarf::DW_AT_frame_base, Location);
412 // Add name to the name table, we do this here because we're guaranteed
413 // to have concrete versions of our DW_TAG_subprogram nodes.
414 addSubprogramNames(SPCU, SP, SPDie);
416 return SPDie;
417 }
419 /// Check whether we should create a DIE for the given Scope, return true
420 /// if we don't create a DIE (the corresponding DIE is null).
421 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
422 if (Scope->isAbstractScope())
423 return false;
425 // We don't create a DIE if there is no Range.
426 const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
427 if (Ranges.empty())
428 return true;
430 if (Ranges.size() > 1)
431 return false;
433 // We don't create a DIE if we have a single Range and the end label
434 // is null.
435 SmallVectorImpl<InsnRange>::const_iterator RI = Ranges.begin();
436 MCSymbol *End = getLabelAfterInsn(RI->second);
437 return !End;
438 }
440 static void addSectionLabel(AsmPrinter *Asm, DwarfUnit *U, DIE *D,
441 dwarf::Attribute A, const MCSymbol *L,
442 const MCSymbol *Sec) {
443 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
444 U->addSectionLabel(D, A, L);
445 else
446 U->addSectionDelta(D, A, L, Sec);
447 }
449 void DwarfDebug::addScopeRangeList(DwarfCompileUnit *TheCU, DIE *ScopeDIE,
450 const SmallVectorImpl<InsnRange> &Range) {
451 // Emit offset in .debug_range as a relocatable label. emitDIE will handle
452 // emitting it appropriately.
453 MCSymbol *RangeSym = Asm->GetTempSymbol("debug_ranges", GlobalRangeCount++);
454 addSectionLabel(Asm, TheCU, ScopeDIE, dwarf::DW_AT_ranges, RangeSym,
455 DwarfDebugRangeSectionSym);
457 RangeSpanList List(RangeSym);
458 for (const InsnRange &R : Range) {
459 RangeSpan Span(getLabelBeforeInsn(R.first), getLabelAfterInsn(R.second));
460 List.addRange(std::move(Span));
461 }
463 // Add the range list to the set of ranges to be emitted.
464 TheCU->addRangeList(std::move(List));
465 }
467 // Construct new DW_TAG_lexical_block for this scope and attach
468 // DW_AT_low_pc/DW_AT_high_pc labels.
469 DIE *DwarfDebug::constructLexicalScopeDIE(DwarfCompileUnit *TheCU,
470 LexicalScope *Scope) {
471 if (isLexicalScopeDIENull(Scope))
472 return 0;
474 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_lexical_block);
475 if (Scope->isAbstractScope())
476 return ScopeDIE;
478 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
480 // If we have multiple ranges, emit them into the range section.
481 if (ScopeRanges.size() > 1) {
482 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
483 return ScopeDIE;
484 }
486 // Construct the address range for this DIE.
487 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
488 MCSymbol *Start = getLabelBeforeInsn(RI->first);
489 MCSymbol *End = getLabelAfterInsn(RI->second);
490 assert(End && "End label should not be null!");
492 assert(Start->isDefined() && "Invalid starting label for an inlined scope!");
493 assert(End->isDefined() && "Invalid end label for an inlined scope!");
495 attachLowHighPC(TheCU, ScopeDIE, Start, End);
497 return ScopeDIE;
498 }
500 // This scope represents inlined body of a function. Construct DIE to
501 // represent this concrete inlined copy of the function.
502 DIE *DwarfDebug::constructInlinedScopeDIE(DwarfCompileUnit *TheCU,
503 LexicalScope *Scope) {
504 const SmallVectorImpl<InsnRange> &ScopeRanges = Scope->getRanges();
505 assert(!ScopeRanges.empty() &&
506 "LexicalScope does not have instruction markers!");
508 if (!Scope->getScopeNode())
509 return NULL;
510 DIScope DS(Scope->getScopeNode());
511 DISubprogram InlinedSP = getDISubprogram(DS);
512 DIE *OriginDIE = TheCU->getDIE(InlinedSP);
513 if (!OriginDIE) {
514 DEBUG(dbgs() << "Unable to find original DIE for an inlined subprogram.");
515 return NULL;
516 }
518 DIE *ScopeDIE = new DIE(dwarf::DW_TAG_inlined_subroutine);
519 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_abstract_origin, OriginDIE);
521 // If we have multiple ranges, emit them into the range section.
522 if (ScopeRanges.size() > 1)
523 addScopeRangeList(TheCU, ScopeDIE, ScopeRanges);
524 else {
525 SmallVectorImpl<InsnRange>::const_iterator RI = ScopeRanges.begin();
526 MCSymbol *StartLabel = getLabelBeforeInsn(RI->first);
527 MCSymbol *EndLabel = getLabelAfterInsn(RI->second);
529 if (StartLabel == 0 || EndLabel == 0)
530 llvm_unreachable("Unexpected Start and End labels for an inlined scope!");
532 assert(StartLabel->isDefined() &&
533 "Invalid starting label for an inlined scope!");
534 assert(EndLabel->isDefined() && "Invalid end label for an inlined scope!");
536 attachLowHighPC(TheCU, ScopeDIE, StartLabel, EndLabel);
537 }
539 InlinedSubprogramDIEs.insert(OriginDIE);
541 // Add the call site information to the DIE.
542 DILocation DL(Scope->getInlinedAt());
543 TheCU->addUInt(
544 ScopeDIE, dwarf::DW_AT_call_file, None,
545 TheCU->getOrCreateSourceID(DL.getFilename(), DL.getDirectory()));
546 TheCU->addUInt(ScopeDIE, dwarf::DW_AT_call_line, None, DL.getLineNumber());
548 // Add name to the name table, we do this here because we're guaranteed
549 // to have concrete versions of our DW_TAG_inlined_subprogram nodes.
550 addSubprogramNames(TheCU, InlinedSP, ScopeDIE);
552 return ScopeDIE;
553 }
555 DIE *DwarfDebug::createScopeChildrenDIE(DwarfCompileUnit *TheCU,
556 LexicalScope *Scope,
557 SmallVectorImpl<DIE *> &Children) {
558 DIE *ObjectPointer = NULL;
560 // Collect arguments for current function.
561 if (LScopes.isCurrentFunctionScope(Scope)) {
562 for (DbgVariable *ArgDV : CurrentFnArguments)
563 if (ArgDV)
564 if (DIE *Arg =
565 TheCU->constructVariableDIE(*ArgDV, Scope->isAbstractScope())) {
566 Children.push_back(Arg);
567 if (ArgDV->isObjectPointer())
568 ObjectPointer = Arg;
569 }
571 // If this is a variadic function, add an unspecified parameter.
572 DISubprogram SP(Scope->getScopeNode());
573 DIArray FnArgs = SP.getType().getTypeArray();
574 if (FnArgs.getElement(FnArgs.getNumElements() - 1)
575 .isUnspecifiedParameter()) {
576 DIE *Ellipsis = new DIE(dwarf::DW_TAG_unspecified_parameters);
577 Children.push_back(Ellipsis);
578 }
579 }
581 // Collect lexical scope children first.
582 for (DbgVariable *DV : ScopeVariables.lookup(Scope))
583 if (DIE *Variable = TheCU->constructVariableDIE(*DV,
584 Scope->isAbstractScope())) {
585 Children.push_back(Variable);
586 if (DV->isObjectPointer())
587 ObjectPointer = Variable;
588 }
589 for (LexicalScope *LS : Scope->getChildren())
590 if (DIE *Nested = constructScopeDIE(TheCU, LS))
591 Children.push_back(Nested);
592 return ObjectPointer;
593 }
595 // Construct a DIE for this scope.
596 DIE *DwarfDebug::constructScopeDIE(DwarfCompileUnit *TheCU,
597 LexicalScope *Scope) {
598 if (!Scope || !Scope->getScopeNode())
599 return NULL;
601 DIScope DS(Scope->getScopeNode());
603 SmallVector<DIE *, 8> Children;
604 DIE *ObjectPointer = NULL;
605 bool ChildrenCreated = false;
607 // We try to create the scope DIE first, then the children DIEs. This will
608 // avoid creating un-used children then removing them later when we find out
609 // the scope DIE is null.
610 DIE *ScopeDIE = NULL;
611 if (Scope->getInlinedAt())
612 ScopeDIE = constructInlinedScopeDIE(TheCU, Scope);
613 else if (DS.isSubprogram()) {
614 ProcessedSPNodes.insert(DS);
615 if (Scope->isAbstractScope()) {
616 ScopeDIE = TheCU->getDIE(DS);
617 // Note down abstract DIE.
618 if (ScopeDIE)
619 AbstractSPDies.insert(std::make_pair(DS, ScopeDIE));
620 } else
621 ScopeDIE = updateSubprogramScopeDIE(TheCU, DISubprogram(DS));
622 } else {
623 // Early exit when we know the scope DIE is going to be null.
624 if (isLexicalScopeDIENull(Scope))
625 return NULL;
627 // We create children here when we know the scope DIE is not going to be
628 // null and the children will be added to the scope DIE.
629 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
630 ChildrenCreated = true;
632 // There is no need to emit empty lexical block DIE.
633 std::pair<ImportedEntityMap::const_iterator,
634 ImportedEntityMap::const_iterator> Range =
635 std::equal_range(
636 ScopesWithImportedEntities.begin(),
637 ScopesWithImportedEntities.end(),
638 std::pair<const MDNode *, const MDNode *>(DS, (const MDNode *)0),
639 less_first());
640 if (Children.empty() && Range.first == Range.second)
641 return NULL;
642 ScopeDIE = constructLexicalScopeDIE(TheCU, Scope);
643 assert(ScopeDIE && "Scope DIE should not be null.");
644 for (ImportedEntityMap::const_iterator i = Range.first; i != Range.second;
645 ++i)
646 constructImportedEntityDIE(TheCU, i->second, ScopeDIE);
647 }
649 if (!ScopeDIE) {
650 assert(Children.empty() &&
651 "We create children only when the scope DIE is not null.");
652 return NULL;
653 }
654 if (!ChildrenCreated)
655 // We create children when the scope DIE is not null.
656 ObjectPointer = createScopeChildrenDIE(TheCU, Scope, Children);
658 // Add children
659 for (DIE *I : Children)
660 ScopeDIE->addChild(I);
662 if (DS.isSubprogram() && ObjectPointer != NULL)
663 TheCU->addDIEEntry(ScopeDIE, dwarf::DW_AT_object_pointer, ObjectPointer);
665 return ScopeDIE;
666 }
668 void DwarfDebug::addGnuPubAttributes(DwarfUnit *U, DIE *D) const {
669 if (!GenerateGnuPubSections)
670 return;
672 U->addFlag(D, dwarf::DW_AT_GNU_pubnames);
673 }
675 // Create new DwarfCompileUnit for the given metadata node with tag
676 // DW_TAG_compile_unit.
677 DwarfCompileUnit *DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit,
678 bool Singular) {
679 StringRef FN = DIUnit.getFilename();
680 CompilationDir = DIUnit.getDirectory();
682 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
683 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
684 InfoHolder.getUnits().size(), Die, DIUnit, Asm, this, &InfoHolder);
685 InfoHolder.addUnit(NewCU);
686 if (!Asm->OutStreamer.hasRawTextSupport() || Singular)
687 Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
688 NewCU->getUniqueID(), CompilationDir);
690 NewCU->addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
691 NewCU->addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
692 DIUnit.getLanguage());
693 NewCU->addString(Die, dwarf::DW_AT_name, FN);
695 if (!useSplitDwarf()) {
696 NewCU->initStmtList(DwarfLineSectionSym);
698 // If we're using split dwarf the compilation dir is going to be in the
699 // skeleton CU and so we don't need to duplicate it here.
700 if (!CompilationDir.empty())
701 NewCU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
703 addGnuPubAttributes(NewCU, Die);
704 }
706 if (DIUnit.isOptimized())
707 NewCU->addFlag(Die, dwarf::DW_AT_APPLE_optimized);
709 StringRef Flags = DIUnit.getFlags();
710 if (!Flags.empty())
711 NewCU->addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
713 if (unsigned RVer = DIUnit.getRunTimeVersion())
714 NewCU->addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
715 dwarf::DW_FORM_data1, RVer);
717 if (!FirstCU)
718 FirstCU = NewCU;
720 if (useSplitDwarf()) {
721 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
722 DwarfInfoDWOSectionSym);
723 NewCU->setSkeleton(constructSkeletonCU(NewCU));
724 } else
725 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
726 DwarfInfoSectionSym);
728 CUMap.insert(std::make_pair(DIUnit, NewCU));
729 CUDieMap.insert(std::make_pair(Die, NewCU));
730 return NewCU;
731 }
733 // Construct subprogram DIE.
734 void DwarfDebug::constructSubprogramDIE(DwarfCompileUnit *TheCU,
735 const MDNode *N) {
736 // FIXME: We should only call this routine once, however, during LTO if a
737 // program is defined in multiple CUs we could end up calling it out of
738 // beginModule as we walk the CUs.
740 DwarfCompileUnit *&CURef = SPMap[N];
741 if (CURef)
742 return;
743 CURef = TheCU;
745 DISubprogram SP(N);
746 if (!SP.isDefinition())
747 // This is a method declaration which will be handled while constructing
748 // class type.
749 return;
751 DIE *SubprogramDie = TheCU->getOrCreateSubprogramDIE(SP);
753 // Expose as a global name.
754 TheCU->addGlobalName(SP.getName(), SubprogramDie, resolve(SP.getContext()));
755 }
757 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
758 const MDNode *N) {
759 DIImportedEntity Module(N);
760 assert(Module.Verify());
761 if (DIE *D = TheCU->getOrCreateContextDIE(Module.getContext()))
762 constructImportedEntityDIE(TheCU, Module, D);
763 }
765 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
766 const MDNode *N, DIE *Context) {
767 DIImportedEntity Module(N);
768 assert(Module.Verify());
769 return constructImportedEntityDIE(TheCU, Module, Context);
770 }
772 void DwarfDebug::constructImportedEntityDIE(DwarfCompileUnit *TheCU,
773 const DIImportedEntity &Module,
774 DIE *Context) {
775 assert(Module.Verify() &&
776 "Use one of the MDNode * overloads to handle invalid metadata");
777 assert(Context && "Should always have a context for an imported_module");
778 DIE *IMDie = new DIE(Module.getTag());
779 TheCU->insertDIE(Module, IMDie);
780 DIE *EntityDie;
781 DIDescriptor Entity = Module.getEntity();
782 if (Entity.isNameSpace())
783 EntityDie = TheCU->getOrCreateNameSpace(DINameSpace(Entity));
784 else if (Entity.isSubprogram())
785 EntityDie = TheCU->getOrCreateSubprogramDIE(DISubprogram(Entity));
786 else if (Entity.isType())
787 EntityDie = TheCU->getOrCreateTypeDIE(DIType(Entity));
788 else
789 EntityDie = TheCU->getDIE(Entity);
790 TheCU->addSourceLine(IMDie, Module.getLineNumber(),
791 Module.getContext().getFilename(),
792 Module.getContext().getDirectory());
793 TheCU->addDIEEntry(IMDie, dwarf::DW_AT_import, EntityDie);
794 StringRef Name = Module.getName();
795 if (!Name.empty())
796 TheCU->addString(IMDie, dwarf::DW_AT_name, Name);
797 Context->addChild(IMDie);
798 }
800 // Emit all Dwarf sections that should come prior to the content. Create
801 // global DIEs and emit initial debug info sections. This is invoked by
802 // the target AsmPrinter.
803 void DwarfDebug::beginModule() {
804 if (DisableDebugInfoPrinting)
805 return;
807 const Module *M = MMI->getModule();
809 // If module has named metadata anchors then use them, otherwise scan the
810 // module using debug info finder to collect debug info.
811 NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
812 if (!CU_Nodes)
813 return;
814 TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
816 // Emit initial sections so we can reference labels later.
817 emitSectionLabels();
819 auto Operands = CU_Nodes->operands();
821 bool SingleCU = std::next(Operands.begin()) == Operands.end();
823 for (MDNode *N : Operands) {
824 DICompileUnit CUNode(N);
825 DwarfCompileUnit *CU = constructDwarfCompileUnit(CUNode, SingleCU);
826 DIArray ImportedEntities = CUNode.getImportedEntities();
827 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
828 ScopesWithImportedEntities.push_back(std::make_pair(
829 DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
830 ImportedEntities.getElement(i)));
831 std::sort(ScopesWithImportedEntities.begin(),
832 ScopesWithImportedEntities.end(), less_first());
833 DIArray GVs = CUNode.getGlobalVariables();
834 for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
835 CU->createGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
836 DIArray SPs = CUNode.getSubprograms();
837 for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
838 constructSubprogramDIE(CU, SPs.getElement(i));
839 DIArray EnumTypes = CUNode.getEnumTypes();
840 for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i)
841 CU->getOrCreateTypeDIE(EnumTypes.getElement(i));
842 DIArray RetainedTypes = CUNode.getRetainedTypes();
843 for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i)
844 CU->getOrCreateTypeDIE(RetainedTypes.getElement(i));
845 // Emit imported_modules last so that the relevant context is already
846 // available.
847 for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
848 constructImportedEntityDIE(CU, ImportedEntities.getElement(i));
849 }
851 // Tell MMI that we have debug info.
852 MMI->setDebugInfoAvailability(true);
854 // Prime section data.
855 SectionMap[Asm->getObjFileLowering().getTextSection()];
856 }
858 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
859 void DwarfDebug::computeInlinedDIEs() {
860 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
861 for (DIE *ISP : InlinedSubprogramDIEs)
862 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
864 for (const auto &AI : AbstractSPDies) {
865 DIE *ISP = AI.second;
866 if (InlinedSubprogramDIEs.count(ISP))
867 continue;
868 FirstCU->addUInt(ISP, dwarf::DW_AT_inline, None, dwarf::DW_INL_inlined);
869 }
870 }
872 // Collect info for variables that were optimized out.
873 void DwarfDebug::collectDeadVariables() {
874 const Module *M = MMI->getModule();
876 if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
877 for (MDNode *N : CU_Nodes->operands()) {
878 DICompileUnit TheCU(N);
879 DIArray Subprograms = TheCU.getSubprograms();
880 for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
881 DISubprogram SP(Subprograms.getElement(i));
882 if (ProcessedSPNodes.count(SP) != 0)
883 continue;
884 if (!SP.isSubprogram())
885 continue;
886 if (!SP.isDefinition())
887 continue;
888 DIArray Variables = SP.getVariables();
889 if (Variables.getNumElements() == 0)
890 continue;
892 // Construct subprogram DIE and add variables DIEs.
893 DwarfCompileUnit *SPCU =
894 static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
895 assert(SPCU && "Unable to find Compile Unit!");
896 // FIXME: See the comment in constructSubprogramDIE about duplicate
897 // subprogram DIEs.
898 constructSubprogramDIE(SPCU, SP);
899 DIE *SPDIE = SPCU->getDIE(SP);
900 for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
901 DIVariable DV(Variables.getElement(vi));
902 if (!DV.isVariable())
903 continue;
904 DbgVariable NewVar(DV, NULL, this);
905 if (DIE *VariableDIE = SPCU->constructVariableDIE(NewVar, false))
906 SPDIE->addChild(VariableDIE);
907 }
908 }
909 }
910 }
911 }
913 void DwarfDebug::finalizeModuleInfo() {
914 // Collect info for variables that were optimized out.
915 collectDeadVariables();
917 // Attach DW_AT_inline attribute with inlined subprogram DIEs.
918 computeInlinedDIEs();
920 // Handle anything that needs to be done on a per-unit basis after
921 // all other generation.
922 for (DwarfUnit *TheU : getUnits()) {
923 // Emit DW_AT_containing_type attribute to connect types with their
924 // vtable holding type.
925 TheU->constructContainingTypeDIEs();
927 // Add CU specific attributes if we need to add any.
928 if (TheU->getUnitDie()->getTag() == dwarf::DW_TAG_compile_unit) {
929 // If we're splitting the dwarf out now that we've got the entire
930 // CU then add the dwo id to it.
931 DwarfCompileUnit *SkCU =
932 static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
933 if (useSplitDwarf()) {
934 // Emit a unique identifier for this CU.
935 uint64_t ID = DIEHash(Asm).computeCUSignature(*TheU->getUnitDie());
936 TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
937 dwarf::DW_FORM_data8, ID);
938 SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
939 dwarf::DW_FORM_data8, ID);
940 }
942 // If we have code split among multiple sections or we've requested
943 // it then emit a DW_AT_ranges attribute on the unit that will remain
944 // in the .o file, otherwise add a DW_AT_low_pc.
945 // FIXME: Also add a high pc if we can.
946 // FIXME: We should use ranges if we have multiple compile units or
947 // allow reordering of code ala .subsections_via_symbols in mach-o.
948 DwarfCompileUnit *U = SkCU ? SkCU : static_cast<DwarfCompileUnit *>(TheU);
949 if (useCURanges() && TheU->getRanges().size()) {
950 addSectionLabel(Asm, U, U->getUnitDie(), dwarf::DW_AT_ranges,
951 Asm->GetTempSymbol("cu_ranges", U->getUniqueID()),
952 DwarfDebugRangeSectionSym);
954 // A DW_AT_low_pc attribute may also be specified in combination with
955 // DW_AT_ranges to specify the default base address for use in location
956 // lists (see Section 2.6.2) and range lists (see Section 2.17.3).
957 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
958 0);
959 } else
960 U->addUInt(U->getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
961 0);
962 }
963 }
965 // Compute DIE offsets and sizes.
966 InfoHolder.computeSizeAndOffsets();
967 if (useSplitDwarf())
968 SkeletonHolder.computeSizeAndOffsets();
969 }
971 void DwarfDebug::endSections() {
972 // Filter labels by section.
973 for (const SymbolCU &SCU : ArangeLabels) {
974 if (SCU.Sym->isInSection()) {
975 // Make a note of this symbol and it's section.
976 const MCSection *Section = &SCU.Sym->getSection();
977 if (!Section->getKind().isMetadata())
978 SectionMap[Section].push_back(SCU);
979 } else {
980 // Some symbols (e.g. common/bss on mach-o) can have no section but still
981 // appear in the output. This sucks as we rely on sections to build
982 // arange spans. We can do it without, but it's icky.
983 SectionMap[NULL].push_back(SCU);
984 }
985 }
987 // Build a list of sections used.
988 std::vector<const MCSection *> Sections;
989 for (const auto &it : SectionMap) {
990 const MCSection *Section = it.first;
991 Sections.push_back(Section);
992 }
994 // Sort the sections into order.
995 // This is only done to ensure consistent output order across different runs.
996 std::sort(Sections.begin(), Sections.end(), SectionSort);
998 // Add terminating symbols for each section.
999 for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
1000 const MCSection *Section = Sections[ID];
1001 MCSymbol *Sym = NULL;
1003 if (Section) {
1004 // We can't call MCSection::getLabelEndName, as it's only safe to do so
1005 // if we know the section name up-front. For user-created sections, the
1006 // resulting label may not be valid to use as a label. (section names can
1007 // use a greater set of characters on some systems)
1008 Sym = Asm->GetTempSymbol("debug_end", ID);
1009 Asm->OutStreamer.SwitchSection(Section);
1010 Asm->OutStreamer.EmitLabel(Sym);
1011 }
1013 // Insert a final terminator.
1014 SectionMap[Section].push_back(SymbolCU(NULL, Sym));
1015 }
1017 // For now only turn on CU ranges if we have -ffunction-sections enabled,
1018 // we've emitted a function into a unique section, or we're using LTO. If
1019 // we're using LTO then we can't know that any particular function in the
1020 // module is correlated to a particular CU and so we need to be conservative.
1021 // At this point all sections should be finalized except for dwarf sections.
1022 HasCURanges = UsedNonDefaultText || (CUMap.size() > 1) ||
1023 TargetMachine::getFunctionSections();
1024 }
1026 // Emit all Dwarf sections that should come after the content.
1027 void DwarfDebug::endModule() {
1028 assert(CurFn == 0);
1029 assert(CurMI == 0);
1031 if (!FirstCU)
1032 return;
1034 // End any existing sections.
1035 // TODO: Does this need to happen?
1036 endSections();
1038 // Finalize the debug info for the module.
1039 finalizeModuleInfo();
1041 emitDebugStr();
1043 // Emit all the DIEs into a debug info section.
1044 emitDebugInfo();
1046 // Corresponding abbreviations into a abbrev section.
1047 emitAbbreviations();
1049 // Emit info into a debug loc section.
1050 emitDebugLoc();
1052 // Emit info into a debug aranges section.
1053 if (GenerateARangeSection)
1054 emitDebugARanges();
1056 // Emit info into a debug ranges section.
1057 emitDebugRanges();
1059 if (useSplitDwarf()) {
1060 emitDebugStrDWO();
1061 emitDebugInfoDWO();
1062 emitDebugAbbrevDWO();
1063 emitDebugLineDWO();
1064 // Emit DWO addresses.
1065 InfoHolder.emitAddresses(Asm->getObjFileLowering().getDwarfAddrSection());
1066 }
1068 // Emit info into the dwarf accelerator table sections.
1069 if (useDwarfAccelTables()) {
1070 emitAccelNames();
1071 emitAccelObjC();
1072 emitAccelNamespaces();
1073 emitAccelTypes();
1074 }
1076 // Emit the pubnames and pubtypes sections if requested.
1077 if (HasDwarfPubSections) {
1078 emitDebugPubNames(GenerateGnuPubSections);
1079 emitDebugPubTypes(GenerateGnuPubSections);
1080 }
1082 // clean up.
1083 SPMap.clear();
1085 // Reset these for the next Module if we have one.
1086 FirstCU = NULL;
1087 }
1089 // Find abstract variable, if any, associated with Var.
1090 DbgVariable *DwarfDebug::findAbstractVariable(DIVariable &DV,
1091 DebugLoc ScopeLoc) {
1092 LLVMContext &Ctx = DV->getContext();
1093 // More then one inlined variable corresponds to one abstract variable.
1094 DIVariable Var = cleanseInlinedVariable(DV, Ctx);
1095 DbgVariable *AbsDbgVariable = AbstractVariables.lookup(Var);
1096 if (AbsDbgVariable)
1097 return AbsDbgVariable;
1099 LexicalScope *Scope = LScopes.findAbstractScope(ScopeLoc.getScope(Ctx));
1100 if (!Scope)
1101 return NULL;
1103 AbsDbgVariable = new DbgVariable(Var, NULL, this);
1104 addScopeVariable(Scope, AbsDbgVariable);
1105 AbstractVariables[Var] = AbsDbgVariable;
1106 return AbsDbgVariable;
1107 }
1109 // If Var is a current function argument then add it to CurrentFnArguments list.
1110 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1111 if (!LScopes.isCurrentFunctionScope(Scope))
1112 return false;
1113 DIVariable DV = Var->getVariable();
1114 if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1115 return false;
1116 unsigned ArgNo = DV.getArgNumber();
1117 if (ArgNo == 0)
1118 return false;
1120 size_t Size = CurrentFnArguments.size();
1121 if (Size == 0)
1122 CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1123 // llvm::Function argument size is not good indicator of how many
1124 // arguments does the function have at source level.
1125 if (ArgNo > Size)
1126 CurrentFnArguments.resize(ArgNo * 2);
1127 CurrentFnArguments[ArgNo - 1] = Var;
1128 return true;
1129 }
1131 // Collect variable information from side table maintained by MMI.
1132 void DwarfDebug::collectVariableInfoFromMMITable(
1133 SmallPtrSet<const MDNode *, 16> &Processed) {
1134 for (const auto &VI : MMI->getVariableDbgInfo()) {
1135 if (!VI.Var)
1136 continue;
1137 Processed.insert(VI.Var);
1138 DIVariable DV(VI.Var);
1139 LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1141 // If variable scope is not found then skip this variable.
1142 if (Scope == 0)
1143 continue;
1145 DbgVariable *AbsDbgVariable = findAbstractVariable(DV, VI.Loc);
1146 DbgVariable *RegVar = new DbgVariable(DV, AbsDbgVariable, this);
1147 RegVar->setFrameIndex(VI.Slot);
1148 if (!addCurrentFnArgument(RegVar, Scope))
1149 addScopeVariable(Scope, RegVar);
1150 if (AbsDbgVariable)
1151 AbsDbgVariable->setFrameIndex(VI.Slot);
1152 }
1153 }
1155 // Return true if debug value, encoded by DBG_VALUE instruction, is in a
1156 // defined reg.
1157 static bool isDbgValueInDefinedReg(const MachineInstr *MI) {
1158 assert(MI->isDebugValue() && "Invalid DBG_VALUE machine instruction!");
1159 return MI->getNumOperands() == 3 && MI->getOperand(0).isReg() &&
1160 MI->getOperand(0).getReg() &&
1161 (MI->getOperand(1).isImm() ||
1162 (MI->getOperand(1).isReg() && MI->getOperand(1).getReg() == 0U));
1163 }
1165 // Get .debug_loc entry for the instruction range starting at MI.
1166 static DebugLocEntry getDebugLocEntry(AsmPrinter *Asm,
1167 const MCSymbol *FLabel,
1168 const MCSymbol *SLabel,
1169 const MachineInstr *MI) {
1170 const MDNode *Var = MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1172 assert(MI->getNumOperands() == 3);
1173 if (MI->getOperand(0).isReg()) {
1174 MachineLocation MLoc;
1175 // If the second operand is an immediate, this is a
1176 // register-indirect address.
1177 if (!MI->getOperand(1).isImm())
1178 MLoc.set(MI->getOperand(0).getReg());
1179 else
1180 MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1181 return DebugLocEntry(FLabel, SLabel, MLoc, Var);
1182 }
1183 if (MI->getOperand(0).isImm())
1184 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getImm());
1185 if (MI->getOperand(0).isFPImm())
1186 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getFPImm());
1187 if (MI->getOperand(0).isCImm())
1188 return DebugLocEntry(FLabel, SLabel, MI->getOperand(0).getCImm());
1190 llvm_unreachable("Unexpected 3 operand DBG_VALUE instruction!");
1191 }
1193 // Find variables for each lexical scope.
1194 void
1195 DwarfDebug::collectVariableInfo(SmallPtrSet<const MDNode *, 16> &Processed) {
1197 // Grab the variable info that was squirreled away in the MMI side-table.
1198 collectVariableInfoFromMMITable(Processed);
1200 for (const MDNode *Var : UserVariables) {
1201 if (Processed.count(Var))
1202 continue;
1204 // History contains relevant DBG_VALUE instructions for Var and instructions
1205 // clobbering it.
1206 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1207 if (History.empty())
1208 continue;
1209 const MachineInstr *MInsn = History.front();
1211 DIVariable DV(Var);
1212 LexicalScope *Scope = NULL;
1213 if (DV.getTag() == dwarf::DW_TAG_arg_variable &&
1214 DISubprogram(DV.getContext()).describes(CurFn->getFunction()))
1215 Scope = LScopes.getCurrentFunctionScope();
1216 else if (MDNode *IA = DV.getInlinedAt())
1217 Scope = LScopes.findInlinedScope(DebugLoc::getFromDILocation(IA));
1218 else
1219 Scope = LScopes.findLexicalScope(cast<MDNode>(DV->getOperand(1)));
1220 // If variable scope is not found then skip this variable.
1221 if (!Scope)
1222 continue;
1224 Processed.insert(DV);
1225 assert(MInsn->isDebugValue() && "History must begin with debug value");
1226 DbgVariable *AbsVar = findAbstractVariable(DV, MInsn->getDebugLoc());
1227 DbgVariable *RegVar = new DbgVariable(DV, AbsVar, this);
1228 if (!addCurrentFnArgument(RegVar, Scope))
1229 addScopeVariable(Scope, RegVar);
1230 if (AbsVar)
1231 AbsVar->setMInsn(MInsn);
1233 // Simplify ranges that are fully coalesced.
1234 if (History.size() <= 1 ||
1235 (History.size() == 2 && MInsn->isIdenticalTo(History.back()))) {
1236 RegVar->setMInsn(MInsn);
1237 continue;
1238 }
1240 // Handle multiple DBG_VALUE instructions describing one variable.
1241 RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1243 for (SmallVectorImpl<const MachineInstr *>::const_iterator
1244 HI = History.begin(),
1245 HE = History.end();
1246 HI != HE; ++HI) {
1247 const MachineInstr *Begin = *HI;
1248 assert(Begin->isDebugValue() && "Invalid History entry");
1250 // Check if DBG_VALUE is truncating a range.
1251 if (Begin->getNumOperands() > 1 && Begin->getOperand(0).isReg() &&
1252 !Begin->getOperand(0).getReg())
1253 continue;
1255 // Compute the range for a register location.
1256 const MCSymbol *FLabel = getLabelBeforeInsn(Begin);
1257 const MCSymbol *SLabel = 0;
1259 if (HI + 1 == HE)
1260 // If Begin is the last instruction in History then its value is valid
1261 // until the end of the function.
1262 SLabel = FunctionEndSym;
1263 else {
1264 const MachineInstr *End = HI[1];
1265 DEBUG(dbgs() << "DotDebugLoc Pair:\n"
1266 << "\t" << *Begin << "\t" << *End << "\n");
1267 if (End->isDebugValue())
1268 SLabel = getLabelBeforeInsn(End);
1269 else {
1270 // End is a normal instruction clobbering the range.
1271 SLabel = getLabelAfterInsn(End);
1272 assert(SLabel && "Forgot label after clobber instruction");
1273 ++HI;
1274 }
1275 }
1277 // The value is valid until the next DBG_VALUE or clobber.
1278 DotDebugLocEntries.push_back(
1279 getDebugLocEntry(Asm, FLabel, SLabel, Begin));
1280 }
1281 DotDebugLocEntries.push_back(DebugLocEntry());
1282 }
1284 // Collect info for variables that were optimized out.
1285 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1286 DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1287 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1288 DIVariable DV(Variables.getElement(i));
1289 if (!DV || !DV.isVariable() || !Processed.insert(DV))
1290 continue;
1291 if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext()))
1292 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1293 }
1294 }
1296 // Return Label preceding the instruction.
1297 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1298 MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1299 assert(Label && "Didn't insert label before instruction");
1300 return Label;
1301 }
1303 // Return Label immediately following the instruction.
1304 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1305 return LabelsAfterInsn.lookup(MI);
1306 }
1308 // Process beginning of an instruction.
1309 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1310 assert(CurMI == 0);
1311 CurMI = MI;
1312 // Check if source location changes, but ignore DBG_VALUE locations.
1313 if (!MI->isDebugValue()) {
1314 DebugLoc DL = MI->getDebugLoc();
1315 if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1316 unsigned Flags = 0;
1317 PrevInstLoc = DL;
1318 if (DL == PrologEndLoc) {
1319 Flags |= DWARF2_FLAG_PROLOGUE_END;
1320 PrologEndLoc = DebugLoc();
1321 }
1322 if (PrologEndLoc.isUnknown())
1323 Flags |= DWARF2_FLAG_IS_STMT;
1325 if (!DL.isUnknown()) {
1326 const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1327 recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1328 } else
1329 recordSourceLine(0, 0, 0, 0);
1330 }
1331 }
1333 // Insert labels where requested.
1334 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1335 LabelsBeforeInsn.find(MI);
1337 // No label needed.
1338 if (I == LabelsBeforeInsn.end())
1339 return;
1341 // Label already assigned.
1342 if (I->second)
1343 return;
1345 if (!PrevLabel) {
1346 PrevLabel = MMI->getContext().CreateTempSymbol();
1347 Asm->OutStreamer.EmitLabel(PrevLabel);
1348 }
1349 I->second = PrevLabel;
1350 }
1352 // Process end of an instruction.
1353 void DwarfDebug::endInstruction() {
1354 assert(CurMI != 0);
1355 // Don't create a new label after DBG_VALUE instructions.
1356 // They don't generate code.
1357 if (!CurMI->isDebugValue())
1358 PrevLabel = 0;
1360 DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1361 LabelsAfterInsn.find(CurMI);
1362 CurMI = 0;
1364 // No label needed.
1365 if (I == LabelsAfterInsn.end())
1366 return;
1368 // Label already assigned.
1369 if (I->second)
1370 return;
1372 // We need a label after this instruction.
1373 if (!PrevLabel) {
1374 PrevLabel = MMI->getContext().CreateTempSymbol();
1375 Asm->OutStreamer.EmitLabel(PrevLabel);
1376 }
1377 I->second = PrevLabel;
1378 }
1380 // Each LexicalScope has first instruction and last instruction to mark
1381 // beginning and end of a scope respectively. Create an inverse map that list
1382 // scopes starts (and ends) with an instruction. One instruction may start (or
1383 // end) multiple scopes. Ignore scopes that are not reachable.
1384 void DwarfDebug::identifyScopeMarkers() {
1385 SmallVector<LexicalScope *, 4> WorkList;
1386 WorkList.push_back(LScopes.getCurrentFunctionScope());
1387 while (!WorkList.empty()) {
1388 LexicalScope *S = WorkList.pop_back_val();
1390 const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1391 if (!Children.empty())
1392 WorkList.append(Children.begin(), Children.end());
1394 if (S->isAbstractScope())
1395 continue;
1397 for (const InsnRange &R : S->getRanges()) {
1398 assert(R.first && "InsnRange does not have first instruction!");
1399 assert(R.second && "InsnRange does not have second instruction!");
1400 requestLabelBeforeInsn(R.first);
1401 requestLabelAfterInsn(R.second);
1402 }
1403 }
1404 }
1406 // Gather pre-function debug information. Assumes being called immediately
1407 // after the function entry point has been emitted.
1408 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1409 CurFn = MF;
1411 // If there's no debug info for the function we're not going to do anything.
1412 if (!MMI->hasDebugInfo())
1413 return;
1415 // Grab the lexical scopes for the function, if we don't have any of those
1416 // then we're not going to be able to do anything.
1417 LScopes.initialize(*MF);
1418 if (LScopes.empty()) {
1419 // If we don't have a lexical scope for this function then there will
1420 // be a hole in the range information. Keep note of this.
1421 UsedNonDefaultText = true;
1422 return;
1423 }
1425 assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1427 // Make sure that each lexical scope will have a begin/end label.
1428 identifyScopeMarkers();
1430 // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1431 // belongs to so that we add to the correct per-cu line table in the
1432 // non-asm case.
1433 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1434 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1435 assert(TheCU && "Unable to find compile unit!");
1436 if (Asm->OutStreamer.hasRawTextSupport())
1437 // Use a single line table if we are generating assembly.
1438 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1439 else
1440 Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1442 // Check the current section against the standard text section. If different
1443 // keep track so that we will know when we're emitting functions into multiple
1444 // sections.
1445 if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1446 UsedNonDefaultText = true;
1448 // Emit a label for the function so that we have a beginning address.
1449 FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1450 // Assumes in correct section after the entry point.
1451 Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1453 const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1454 // LiveUserVar - Map physreg numbers to the MDNode they contain.
1455 std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1457 for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1458 ++I) {
1459 bool AtBlockEntry = true;
1460 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1461 II != IE; ++II) {
1462 const MachineInstr *MI = II;
1464 if (MI->isDebugValue()) {
1465 assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1467 // Keep track of user variables.
1468 const MDNode *Var =
1469 MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1471 // Variable is in a register, we need to check for clobbers.
1472 if (isDbgValueInDefinedReg(MI))
1473 LiveUserVar[MI->getOperand(0).getReg()] = Var;
1475 // Check the history of this variable.
1476 SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1477 if (History.empty()) {
1478 UserVariables.push_back(Var);
1479 // The first mention of a function argument gets the FunctionBeginSym
1480 // label, so arguments are visible when breaking at function entry.
1481 DIVariable DV(Var);
1482 if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1483 getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1484 LabelsBeforeInsn[MI] = FunctionBeginSym;
1485 } else {
1486 // We have seen this variable before. Try to coalesce DBG_VALUEs.
1487 const MachineInstr *Prev = History.back();
1488 if (Prev->isDebugValue()) {
1489 // Coalesce identical entries at the end of History.
1490 if (History.size() >= 2 &&
1491 Prev->isIdenticalTo(History[History.size() - 2])) {
1492 DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1493 << "\t" << *Prev << "\t"
1494 << *History[History.size() - 2] << "\n");
1495 History.pop_back();
1496 }
1498 // Terminate old register assignments that don't reach MI;
1499 MachineFunction::const_iterator PrevMBB = Prev->getParent();
1500 if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1501 isDbgValueInDefinedReg(Prev)) {
1502 // Previous register assignment needs to terminate at the end of
1503 // its basic block.
1504 MachineBasicBlock::const_iterator LastMI =
1505 PrevMBB->getLastNonDebugInstr();
1506 if (LastMI == PrevMBB->end()) {
1507 // Drop DBG_VALUE for empty range.
1508 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1509 << "\t" << *Prev << "\n");
1510 History.pop_back();
1511 } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1512 // Terminate after LastMI.
1513 History.push_back(LastMI);
1514 }
1515 }
1516 }
1517 History.push_back(MI);
1518 } else {
1519 // Not a DBG_VALUE instruction.
1520 if (!MI->isPosition())
1521 AtBlockEntry = false;
1523 // First known non-DBG_VALUE and non-frame setup location marks
1524 // the beginning of the function body.
1525 if (!MI->getFlag(MachineInstr::FrameSetup) &&
1526 (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1527 PrologEndLoc = MI->getDebugLoc();
1529 // Check if the instruction clobbers any registers with debug vars.
1530 for (const MachineOperand &MO : MI->operands()) {
1531 if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1532 continue;
1533 for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1534 ++AI) {
1535 unsigned Reg = *AI;
1536 const MDNode *Var = LiveUserVar[Reg];
1537 if (!Var)
1538 continue;
1539 // Reg is now clobbered.
1540 LiveUserVar[Reg] = 0;
1542 // Was MD last defined by a DBG_VALUE referring to Reg?
1543 DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1544 if (HistI == DbgValues.end())
1545 continue;
1546 SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1547 if (History.empty())
1548 continue;
1549 const MachineInstr *Prev = History.back();
1550 // Sanity-check: Register assignments are terminated at the end of
1551 // their block.
1552 if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1553 continue;
1554 // Is the variable still in Reg?
1555 if (!isDbgValueInDefinedReg(Prev) ||
1556 Prev->getOperand(0).getReg() != Reg)
1557 continue;
1558 // Var is clobbered. Make sure the next instruction gets a label.
1559 History.push_back(MI);
1560 }
1561 }
1562 }
1563 }
1564 }
1566 for (auto &I : DbgValues) {
1567 SmallVectorImpl<const MachineInstr *> &History = I.second;
1568 if (History.empty())
1569 continue;
1571 // Make sure the final register assignments are terminated.
1572 const MachineInstr *Prev = History.back();
1573 if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1574 const MachineBasicBlock *PrevMBB = Prev->getParent();
1575 MachineBasicBlock::const_iterator LastMI =
1576 PrevMBB->getLastNonDebugInstr();
1577 if (LastMI == PrevMBB->end())
1578 // Drop DBG_VALUE for empty range.
1579 History.pop_back();
1580 else if (PrevMBB != &PrevMBB->getParent()->back()) {
1581 // Terminate after LastMI.
1582 History.push_back(LastMI);
1583 }
1584 }
1585 // Request labels for the full history.
1586 for (const MachineInstr *MI : History) {
1587 if (MI->isDebugValue())
1588 requestLabelBeforeInsn(MI);
1589 else
1590 requestLabelAfterInsn(MI);
1591 }
1592 }
1594 PrevInstLoc = DebugLoc();
1595 PrevLabel = FunctionBeginSym;
1597 // Record beginning of function.
1598 if (!PrologEndLoc.isUnknown()) {
1599 DebugLoc FnStartDL =
1600 PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1601 recordSourceLine(
1602 FnStartDL.getLine(), FnStartDL.getCol(),
1603 FnStartDL.getScope(MF->getFunction()->getContext()),
1604 // We'd like to list the prologue as "not statements" but GDB behaves
1605 // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1606 DWARF2_FLAG_IS_STMT);
1607 }
1608 }
1610 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1611 SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1612 DIVariable DV = Var->getVariable();
1613 // Variables with positive arg numbers are parameters.
1614 if (unsigned ArgNum = DV.getArgNumber()) {
1615 // Keep all parameters in order at the start of the variable list to ensure
1616 // function types are correct (no out-of-order parameters)
1617 //
1618 // This could be improved by only doing it for optimized builds (unoptimized
1619 // builds have the right order to begin with), searching from the back (this
1620 // would catch the unoptimized case quickly), or doing a binary search
1621 // rather than linear search.
1622 SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1623 while (I != Vars.end()) {
1624 unsigned CurNum = (*I)->getVariable().getArgNumber();
1625 // A local (non-parameter) variable has been found, insert immediately
1626 // before it.
1627 if (CurNum == 0)
1628 break;
1629 // A later indexed parameter has been found, insert immediately before it.
1630 if (CurNum > ArgNum)
1631 break;
1632 ++I;
1633 }
1634 Vars.insert(I, Var);
1635 return;
1636 }
1638 Vars.push_back(Var);
1639 }
1641 // Gather and emit post-function debug information.
1642 void DwarfDebug::endFunction(const MachineFunction *MF) {
1643 // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1644 // though the beginFunction may not be called at all.
1645 // We should handle both cases.
1646 if (CurFn == 0)
1647 CurFn = MF;
1648 else
1649 assert(CurFn == MF);
1650 assert(CurFn != 0);
1652 if (!MMI->hasDebugInfo() || LScopes.empty()) {
1653 CurFn = 0;
1654 return;
1655 }
1657 // Define end label for subprogram.
1658 FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1659 // Assumes in correct section after the entry point.
1660 Asm->OutStreamer.EmitLabel(FunctionEndSym);
1662 // Set DwarfDwarfCompileUnitID in MCContext to default value.
1663 Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1665 SmallPtrSet<const MDNode *, 16> ProcessedVars;
1666 collectVariableInfo(ProcessedVars);
1668 LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1669 DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1670 assert(TheCU && "Unable to find compile unit!");
1672 // Construct abstract scopes.
1673 for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1674 DISubprogram SP(AScope->getScopeNode());
1675 if (SP.isSubprogram()) {
1676 // Collect info for variables that were optimized out.
1677 DIArray Variables = SP.getVariables();
1678 for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1679 DIVariable DV(Variables.getElement(i));
1680 if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1681 continue;
1682 // Check that DbgVariable for DV wasn't created earlier, when
1683 // findAbstractVariable() was called for inlined instance of DV.
1684 LLVMContext &Ctx = DV->getContext();
1685 DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1686 if (AbstractVariables.lookup(CleanDV))
1687 continue;
1688 if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1689 addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1690 }
1691 }
1692 if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1693 constructScopeDIE(TheCU, AScope);
1694 }
1696 DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1697 if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1698 TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1700 // Add the range of this function to the list of ranges for the CU.
1701 RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1702 TheCU->addRange(std::move(Span));
1704 // Clear debug info
1705 for (auto &I : ScopeVariables)
1706 DeleteContainerPointers(I.second);
1707 ScopeVariables.clear();
1708 DeleteContainerPointers(CurrentFnArguments);
1709 UserVariables.clear();
1710 DbgValues.clear();
1711 AbstractVariables.clear();
1712 LabelsBeforeInsn.clear();
1713 LabelsAfterInsn.clear();
1714 PrevLabel = NULL;
1715 CurFn = 0;
1716 }
1718 // Register a source line with debug info. Returns the unique label that was
1719 // emitted and which provides correspondence to the source line list.
1720 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1721 unsigned Flags) {
1722 StringRef Fn;
1723 StringRef Dir;
1724 unsigned Src = 1;
1725 unsigned Discriminator = 0;
1726 if (S) {
1727 DIDescriptor Scope(S);
1729 if (Scope.isCompileUnit()) {
1730 DICompileUnit CU(S);
1731 Fn = CU.getFilename();
1732 Dir = CU.getDirectory();
1733 } else if (Scope.isFile()) {
1734 DIFile F(S);
1735 Fn = F.getFilename();
1736 Dir = F.getDirectory();
1737 } else if (Scope.isSubprogram()) {
1738 DISubprogram SP(S);
1739 Fn = SP.getFilename();
1740 Dir = SP.getDirectory();
1741 } else if (Scope.isLexicalBlockFile()) {
1742 DILexicalBlockFile DBF(S);
1743 Fn = DBF.getFilename();
1744 Dir = DBF.getDirectory();
1745 } else if (Scope.isLexicalBlock()) {
1746 DILexicalBlock DB(S);
1747 Fn = DB.getFilename();
1748 Dir = DB.getDirectory();
1749 Discriminator = DB.getDiscriminator();
1750 } else
1751 llvm_unreachable("Unexpected scope info");
1753 unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1754 Src = static_cast<DwarfCompileUnit *>(InfoHolder.getUnits()[CUID])
1755 ->getOrCreateSourceID(Fn, Dir);
1756 }
1757 Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1758 Discriminator, Fn);
1759 }
1761 //===----------------------------------------------------------------------===//
1762 // Emit Methods
1763 //===----------------------------------------------------------------------===//
1765 // Compute the size and offset of a DIE. The offset is relative to start of the
1766 // CU. It returns the offset after laying out the DIE.
1767 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1768 // Record the abbreviation.
1769 assignAbbrevNumber(Die->getAbbrev());
1771 // Get the abbreviation for this DIE.
1772 const DIEAbbrev &Abbrev = Die->getAbbrev();
1774 // Set DIE offset
1775 Die->setOffset(Offset);
1777 // Start the size with the size of abbreviation code.
1778 Offset += getULEB128Size(Die->getAbbrevNumber());
1780 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1781 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1783 // Size the DIE attribute values.
1784 for (unsigned i = 0, N = Values.size(); i < N; ++i)
1785 // Size attribute value.
1786 Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1788 // Get the children.
1789 const std::vector<DIE *> &Children = Die->getChildren();
1791 // Size the DIE children if any.
1792 if (!Children.empty()) {
1793 assert(Abbrev.hasChildren() && "Children flag not set");
1795 for (DIE *Child : Children)
1796 Offset = computeSizeAndOffset(Child, Offset);
1798 // End of children marker.
1799 Offset += sizeof(int8_t);
1800 }
1802 Die->setSize(Offset - Die->getOffset());
1803 return Offset;
1804 }
1806 // Compute the size and offset for each DIE.
1807 void DwarfFile::computeSizeAndOffsets() {
1808 // Offset from the first CU in the debug info section is 0 initially.
1809 unsigned SecOffset = 0;
1811 // Iterate over each compile unit and set the size and offsets for each
1812 // DIE within each compile unit. All offsets are CU relative.
1813 for (DwarfUnit *TheU : CUs) {
1814 TheU->setDebugInfoOffset(SecOffset);
1816 // CU-relative offset is reset to 0 here.
1817 unsigned Offset = sizeof(int32_t) + // Length of Unit Info
1818 TheU->getHeaderSize(); // Unit-specific headers
1820 // EndOffset here is CU-relative, after laying out
1821 // all of the CU DIE.
1822 unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1823 SecOffset += EndOffset;
1824 }
1825 }
1827 // Emit initial Dwarf sections with a label at the start of each one.
1828 void DwarfDebug::emitSectionLabels() {
1829 const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1831 // Dwarf sections base addresses.
1832 DwarfInfoSectionSym =
1833 emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1834 if (useSplitDwarf())
1835 DwarfInfoDWOSectionSym =
1836 emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1837 DwarfAbbrevSectionSym =
1838 emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1839 if (useSplitDwarf())
1840 DwarfAbbrevDWOSectionSym = emitSectionSym(
1841 Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1842 if (GenerateARangeSection)
1843 emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1845 DwarfLineSectionSym =
1846 emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1847 emitSectionSym(Asm, TLOF.getDwarfLocSection());
1848 if (GenerateGnuPubSections) {
1849 DwarfGnuPubNamesSectionSym =
1850 emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1851 DwarfGnuPubTypesSectionSym =
1852 emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1853 } else if (HasDwarfPubSections) {
1854 emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1855 emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1856 }
1858 DwarfStrSectionSym =
1859 emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1860 if (useSplitDwarf()) {
1861 DwarfStrDWOSectionSym =
1862 emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1863 DwarfAddrSectionSym =
1864 emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1865 }
1866 DwarfDebugRangeSectionSym =
1867 emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1869 DwarfDebugLocSectionSym =
1870 emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1871 }
1873 // Recursively emits a debug information entry.
1874 void DwarfDebug::emitDIE(DIE *Die) {
1875 // Get the abbreviation for this DIE.
1876 const DIEAbbrev &Abbrev = Die->getAbbrev();
1878 // Emit the code (index) for the abbreviation.
1879 if (Asm->isVerbose())
1880 Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1881 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1882 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1883 dwarf::TagString(Abbrev.getTag()));
1884 Asm->EmitULEB128(Abbrev.getNumber());
1886 const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1887 const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1889 // Emit the DIE attribute values.
1890 for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1891 dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1892 dwarf::Form Form = AbbrevData[i].getForm();
1893 assert(Form && "Too many attributes for DIE (check abbreviation)");
1895 if (Asm->isVerbose()) {
1896 Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1897 if (Attr == dwarf::DW_AT_accessibility)
1898 Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1899 cast<DIEInteger>(Values[i])->getValue()));
1900 }
1902 // Emit an attribute using the defined form.
1903 Values[i]->EmitValue(Asm, Form);
1904 }
1906 // Emit the DIE children if any.
1907 if (Abbrev.hasChildren()) {
1908 const std::vector<DIE *> &Children = Die->getChildren();
1910 for (DIE *Child : Children)
1911 emitDIE(Child);
1913 Asm->OutStreamer.AddComment("End Of Children Mark");
1914 Asm->EmitInt8(0);
1915 }
1916 }
1918 // Emit the various dwarf units to the unit section USection with
1919 // the abbreviations going into ASection.
1920 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1921 const MCSymbol *ASectionSym) {
1922 for (DwarfUnit *TheU : CUs) {
1923 DIE *Die = TheU->getUnitDie();
1924 const MCSection *USection = TheU->getSection();
1925 Asm->OutStreamer.SwitchSection(USection);
1927 // Emit the compile units header.
1928 Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1930 // Emit size of content not including length itself
1931 Asm->OutStreamer.AddComment("Length of Unit");
1932 Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1934 TheU->emitHeader(ASection, ASectionSym);
1936 DD->emitDIE(Die);
1937 Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1938 }
1939 }
1941 // Emit the debug info section.
1942 void DwarfDebug::emitDebugInfo() {
1943 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1945 Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1946 DwarfAbbrevSectionSym);
1947 }
1949 // Emit the abbreviation section.
1950 void DwarfDebug::emitAbbreviations() {
1951 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1953 Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1954 }
1956 void DwarfFile::emitAbbrevs(const MCSection *Section) {
1957 // Check to see if it is worth the effort.
1958 if (!Abbreviations.empty()) {
1959 // Start the debug abbrev section.
1960 Asm->OutStreamer.SwitchSection(Section);
1962 // For each abbrevation.
1963 for (const DIEAbbrev *Abbrev : Abbreviations) {
1964 // Emit the abbrevations code (base 1 index.)
1965 Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
1967 // Emit the abbreviations data.
1968 Abbrev->Emit(Asm);
1969 }
1971 // Mark end of abbreviations.
1972 Asm->EmitULEB128(0, "EOM(3)");
1973 }
1974 }
1976 // Emit the last address of the section and the end of the line matrix.
1977 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1978 // Define last address of section.
1979 Asm->OutStreamer.AddComment("Extended Op");
1980 Asm->EmitInt8(0);
1982 Asm->OutStreamer.AddComment("Op size");
1983 Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1984 Asm->OutStreamer.AddComment("DW_LNE_set_address");
1985 Asm->EmitInt8(dwarf::DW_LNE_set_address);
1987 Asm->OutStreamer.AddComment("Section end label");
1989 Asm->OutStreamer.EmitSymbolValue(
1990 Asm->GetTempSymbol("section_end", SectionEnd),
1991 Asm->getDataLayout().getPointerSize());
1993 // Mark end of matrix.
1994 Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1995 Asm->EmitInt8(0);
1996 Asm->EmitInt8(1);
1997 Asm->EmitInt8(1);
1998 }
2000 // Emit visible names into a hashed accelerator table section.
2001 void DwarfDebug::emitAccelNames() {
2002 DwarfAccelTable AT(
2003 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2004 for (DwarfUnit *TheU : getUnits()) {
2005 for (const auto &GI : TheU->getAccelNames()) {
2006 StringRef Name = GI.getKey();
2007 for (const DIE *D : GI.second)
2008 AT.AddName(Name, D);
2009 }
2010 }
2012 AT.FinalizeTable(Asm, "Names");
2013 Asm->OutStreamer.SwitchSection(
2014 Asm->getObjFileLowering().getDwarfAccelNamesSection());
2015 MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2016 Asm->OutStreamer.EmitLabel(SectionBegin);
2018 // Emit the full data.
2019 AT.Emit(Asm, SectionBegin, &InfoHolder);
2020 }
2022 // Emit objective C classes and categories into a hashed accelerator table
2023 // section.
2024 void DwarfDebug::emitAccelObjC() {
2025 DwarfAccelTable AT(
2026 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2027 for (DwarfUnit *TheU : getUnits()) {
2028 for (const auto &GI : TheU->getAccelObjC()) {
2029 StringRef Name = GI.getKey();
2030 for (const DIE *D : GI.second)
2031 AT.AddName(Name, D);
2032 }
2033 }
2035 AT.FinalizeTable(Asm, "ObjC");
2036 Asm->OutStreamer.SwitchSection(
2037 Asm->getObjFileLowering().getDwarfAccelObjCSection());
2038 MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2039 Asm->OutStreamer.EmitLabel(SectionBegin);
2041 // Emit the full data.
2042 AT.Emit(Asm, SectionBegin, &InfoHolder);
2043 }
2045 // Emit namespace dies into a hashed accelerator table.
2046 void DwarfDebug::emitAccelNamespaces() {
2047 DwarfAccelTable AT(
2048 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2049 for (DwarfUnit *TheU : getUnits()) {
2050 for (const auto &GI : TheU->getAccelNamespace()) {
2051 StringRef Name = GI.getKey();
2052 for (const DIE *D : GI.second)
2053 AT.AddName(Name, D);
2054 }
2055 }
2057 AT.FinalizeTable(Asm, "namespac");
2058 Asm->OutStreamer.SwitchSection(
2059 Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2060 MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2061 Asm->OutStreamer.EmitLabel(SectionBegin);
2063 // Emit the full data.
2064 AT.Emit(Asm, SectionBegin, &InfoHolder);
2065 }
2067 // Emit type dies into a hashed accelerator table.
2068 void DwarfDebug::emitAccelTypes() {
2069 std::vector<DwarfAccelTable::Atom> Atoms;
2070 Atoms.push_back(
2071 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2072 Atoms.push_back(
2073 DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2074 Atoms.push_back(
2075 DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2076 DwarfAccelTable AT(Atoms);
2077 for (DwarfUnit *TheU : getUnits()) {
2078 for (const auto &GI : TheU->getAccelTypes()) {
2079 StringRef Name = GI.getKey();
2080 for (const auto &DI : GI.second)
2081 AT.AddName(Name, DI.first, DI.second);
2082 }
2083 }
2085 AT.FinalizeTable(Asm, "types");
2086 Asm->OutStreamer.SwitchSection(
2087 Asm->getObjFileLowering().getDwarfAccelTypesSection());
2088 MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2089 Asm->OutStreamer.EmitLabel(SectionBegin);
2091 // Emit the full data.
2092 AT.Emit(Asm, SectionBegin, &InfoHolder);
2093 }
2095 // Public name handling.
2096 // The format for the various pubnames:
2097 //
2098 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2099 // for the DIE that is named.
2100 //
2101 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2102 // into the CU and the index value is computed according to the type of value
2103 // for the DIE that is named.
2104 //
2105 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2106 // it's the offset within the debug_info/debug_types dwo section, however, the
2107 // reference in the pubname header doesn't change.
2109 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2110 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2111 const DIE *Die) {
2112 dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2114 // We could have a specification DIE that has our most of our knowledge,
2115 // look for that now.
2116 DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2117 if (SpecVal) {
2118 DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2119 if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2120 Linkage = dwarf::GIEL_EXTERNAL;
2121 } else if (Die->findAttribute(dwarf::DW_AT_external))
2122 Linkage = dwarf::GIEL_EXTERNAL;
2124 switch (Die->getTag()) {
2125 case dwarf::DW_TAG_class_type:
2126 case dwarf::DW_TAG_structure_type:
2127 case dwarf::DW_TAG_union_type:
2128 case dwarf::DW_TAG_enumeration_type:
2129 return dwarf::PubIndexEntryDescriptor(
2130 dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2131 ? dwarf::GIEL_STATIC
2132 : dwarf::GIEL_EXTERNAL);
2133 case dwarf::DW_TAG_typedef:
2134 case dwarf::DW_TAG_base_type:
2135 case dwarf::DW_TAG_subrange_type:
2136 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2137 case dwarf::DW_TAG_namespace:
2138 return dwarf::GIEK_TYPE;
2139 case dwarf::DW_TAG_subprogram:
2140 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2141 case dwarf::DW_TAG_constant:
2142 case dwarf::DW_TAG_variable:
2143 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2144 case dwarf::DW_TAG_enumerator:
2145 return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2146 dwarf::GIEL_STATIC);
2147 default:
2148 return dwarf::GIEK_NONE;
2149 }
2150 }
2152 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2153 ///
2154 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2155 const MCSection *PSec =
2156 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2157 : Asm->getObjFileLowering().getDwarfPubNamesSection();
2159 emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2160 }
2162 void DwarfDebug::emitDebugPubSection(
2163 bool GnuStyle, const MCSection *PSec, StringRef Name,
2164 const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2165 for (const auto &NU : CUMap) {
2166 DwarfCompileUnit *TheU = NU.second;
2168 const auto &Globals = (TheU->*Accessor)();
2170 if (Globals.empty())
2171 continue;
2173 if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2174 TheU = Skeleton;
2175 unsigned ID = TheU->getUniqueID();
2177 // Start the dwarf pubnames section.
2178 Asm->OutStreamer.SwitchSection(PSec);
2180 // Emit the header.
2181 Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2182 MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2183 MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2184 Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2186 Asm->OutStreamer.EmitLabel(BeginLabel);
2188 Asm->OutStreamer.AddComment("DWARF Version");
2189 Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2191 Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2192 Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2194 Asm->OutStreamer.AddComment("Compilation Unit Length");
2195 Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2197 // Emit the pubnames for this compilation unit.
2198 for (const auto &GI : Globals) {
2199 const char *Name = GI.getKeyData();
2200 const DIE *Entity = GI.second;
2202 Asm->OutStreamer.AddComment("DIE offset");
2203 Asm->EmitInt32(Entity->getOffset());
2205 if (GnuStyle) {
2206 dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2207 Asm->OutStreamer.AddComment(
2208 Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2209 dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2210 Asm->EmitInt8(Desc.toBits());
2211 }
2213 Asm->OutStreamer.AddComment("External Name");
2214 Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2215 }
2217 Asm->OutStreamer.AddComment("End Mark");
2218 Asm->EmitInt32(0);
2219 Asm->OutStreamer.EmitLabel(EndLabel);
2220 }
2221 }
2223 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2224 const MCSection *PSec =
2225 GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2226 : Asm->getObjFileLowering().getDwarfPubTypesSection();
2228 emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2229 }
2231 // Emit strings into a string section.
2232 void DwarfFile::emitStrings(const MCSection *StrSection,
2233 const MCSection *OffsetSection = NULL,
2234 const MCSymbol *StrSecSym = NULL) {
2236 if (StringPool.empty())
2237 return;
2239 // Start the dwarf str section.
2240 Asm->OutStreamer.SwitchSection(StrSection);
2242 // Get all of the string pool entries and put them in an array by their ID so
2243 // we can sort them.
2244 SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2246 for (const auto &I : StringPool)
2247 Entries.push_back(std::make_pair(I.second.second, &I));
2249 array_pod_sort(Entries.begin(), Entries.end());
2251 for (const auto &Entry : Entries) {
2252 // Emit a label for reference from debug information entries.
2253 Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2255 // Emit the string itself with a terminating null byte.
2256 Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2257 Entry.second->getKeyLength() + 1));
2258 }
2260 // If we've got an offset section go ahead and emit that now as well.
2261 if (OffsetSection) {
2262 Asm->OutStreamer.SwitchSection(OffsetSection);
2263 unsigned offset = 0;
2264 unsigned size = 4; // FIXME: DWARF64 is 8.
2265 for (const auto &Entry : Entries) {
2266 Asm->OutStreamer.EmitIntValue(offset, size);
2267 offset += Entry.second->getKeyLength() + 1;
2268 }
2269 }
2270 }
2272 // Emit addresses into the section given.
2273 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2275 if (AddressPool.empty())
2276 return;
2278 // Start the dwarf addr section.
2279 Asm->OutStreamer.SwitchSection(AddrSection);
2281 // Order the address pool entries by ID
2282 SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2284 for (const auto &I : AddressPool)
2285 Entries[I.second.Number] =
2286 I.second.TLS
2287 ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2288 : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2290 for (const MCExpr *Entry : Entries)
2291 Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2292 }
2294 // Emit visible names into a debug str section.
2295 void DwarfDebug::emitDebugStr() {
2296 DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2297 Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2298 }
2300 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2301 const DebugLocEntry &Entry) {
2302 DIVariable DV(Entry.getVariable());
2303 if (Entry.isInt()) {
2304 DIBasicType BTy(DV.getType());
2305 if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2306 BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2307 Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2308 Streamer.EmitSLEB128(Entry.getInt());
2309 } else {
2310 Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2311 Streamer.EmitULEB128(Entry.getInt());
2312 }
2313 } else if (Entry.isLocation()) {
2314 MachineLocation Loc = Entry.getLoc();
2315 if (!DV.hasComplexAddress())
2316 // Regular entry.
2317 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2318 else {
2319 // Complex address entry.
2320 unsigned N = DV.getNumAddrElements();
2321 unsigned i = 0;
2322 if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2323 if (Loc.getOffset()) {
2324 i = 2;
2325 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2326 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2327 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2328 Streamer.EmitSLEB128(DV.getAddrElement(1));
2329 } else {
2330 // If first address element is OpPlus then emit
2331 // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2332 MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2333 Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2334 i = 2;
2335 }
2336 } else {
2337 Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2338 }
2340 // Emit remaining complex address elements.
2341 for (; i < N; ++i) {
2342 uint64_t Element = DV.getAddrElement(i);
2343 if (Element == DIBuilder::OpPlus) {
2344 Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2345 Streamer.EmitULEB128(DV.getAddrElement(++i));
2346 } else if (Element == DIBuilder::OpDeref) {
2347 if (!Loc.isReg())
2348 Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2349 } else
2350 llvm_unreachable("unknown Opcode found in complex address");
2351 }
2352 }
2353 }
2354 // else ... ignore constant fp. There is not any good way to
2355 // to represent them here in dwarf.
2356 // FIXME: ^
2357 }
2359 // Emit locations into the debug loc section.
2360 void DwarfDebug::emitDebugLoc() {
2361 if (DotDebugLocEntries.empty())
2362 return;
2364 for (SmallVectorImpl<DebugLocEntry>::iterator
2365 I = DotDebugLocEntries.begin(),
2366 E = DotDebugLocEntries.end();
2367 I != E; ++I) {
2368 DebugLocEntry &Entry = *I;
2369 if (I + 1 != DotDebugLocEntries.end())
2370 Entry.Merge(I + 1);
2371 }
2373 // Start the dwarf loc section.
2374 Asm->OutStreamer.SwitchSection(
2375 Asm->getObjFileLowering().getDwarfLocSection());
2376 unsigned char Size = Asm->getDataLayout().getPointerSize();
2377 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2378 unsigned index = 1;
2379 for (SmallVectorImpl<DebugLocEntry>::const_iterator
2380 I = DotDebugLocEntries.begin(),
2381 E = DotDebugLocEntries.end();
2382 I != E; ++I, ++index) {
2383 const DebugLocEntry &Entry = *I;
2384 if (Entry.isMerged())
2385 continue;
2387 if (Entry.isEmpty()) {
2388 Asm->OutStreamer.EmitIntValue(0, Size);
2389 Asm->OutStreamer.EmitIntValue(0, Size);
2390 Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2391 } else {
2392 // Set up the range.
2393 Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2394 Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2395 Asm->OutStreamer.AddComment("Loc expr size");
2396 MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2397 MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2398 Asm->EmitLabelDifference(end, begin, 2);
2399 Asm->OutStreamer.EmitLabel(begin);
2400 // Emit the entry.
2401 APByteStreamer Streamer(*Asm);
2402 emitDebugLocEntry(Streamer, Entry);
2403 // Close the range.
2404 Asm->OutStreamer.EmitLabel(end);
2405 }
2406 }
2407 }
2409 struct ArangeSpan {
2410 const MCSymbol *Start, *End;
2411 };
2413 // Emit a debug aranges section, containing a CU lookup for any
2414 // address we can tie back to a CU.
2415 void DwarfDebug::emitDebugARanges() {
2416 // Start the dwarf aranges section.
2417 Asm->OutStreamer.SwitchSection(
2418 Asm->getObjFileLowering().getDwarfARangesSection());
2420 typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2422 SpansType Spans;
2424 // Build a list of sections used.
2425 std::vector<const MCSection *> Sections;
2426 for (const auto &it : SectionMap) {
2427 const MCSection *Section = it.first;
2428 Sections.push_back(Section);
2429 }
2431 // Sort the sections into order.
2432 // This is only done to ensure consistent output order across different runs.
2433 std::sort(Sections.begin(), Sections.end(), SectionSort);
2435 // Build a set of address spans, sorted by CU.
2436 for (const MCSection *Section : Sections) {
2437 SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2438 if (List.size() < 2)
2439 continue;
2441 // Sort the symbols by offset within the section.
2442 std::sort(List.begin(), List.end(),
2443 [&](const SymbolCU &A, const SymbolCU &B) {
2444 unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2445 unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2447 // Symbols with no order assigned should be placed at the end.
2448 // (e.g. section end labels)
2449 if (IA == 0)
2450 return false;
2451 if (IB == 0)
2452 return true;
2453 return IA < IB;
2454 });
2456 // If we have no section (e.g. common), just write out
2457 // individual spans for each symbol.
2458 if (Section == NULL) {
2459 for (const SymbolCU &Cur : List) {
2460 ArangeSpan Span;
2461 Span.Start = Cur.Sym;
2462 Span.End = NULL;
2463 if (Cur.CU)
2464 Spans[Cur.CU].push_back(Span);
2465 }
2466 } else {
2467 // Build spans between each label.
2468 const MCSymbol *StartSym = List[0].Sym;
2469 for (size_t n = 1, e = List.size(); n < e; n++) {
2470 const SymbolCU &Prev = List[n - 1];
2471 const SymbolCU &Cur = List[n];
2473 // Try and build the longest span we can within the same CU.
2474 if (Cur.CU != Prev.CU) {
2475 ArangeSpan Span;
2476 Span.Start = StartSym;
2477 Span.End = Cur.Sym;
2478 Spans[Prev.CU].push_back(Span);
2479 StartSym = Cur.Sym;
2480 }
2481 }
2482 }
2483 }
2485 unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2487 // Build a list of CUs used.
2488 std::vector<DwarfCompileUnit *> CUs;
2489 for (const auto &it : Spans) {
2490 DwarfCompileUnit *CU = it.first;
2491 CUs.push_back(CU);
2492 }
2494 // Sort the CU list (again, to ensure consistent output order).
2495 std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2496 return A->getUniqueID() < B->getUniqueID();
2497 });
2499 // Emit an arange table for each CU we used.
2500 for (DwarfCompileUnit *CU : CUs) {
2501 std::vector<ArangeSpan> &List = Spans[CU];
2503 // Emit size of content not including length itself.
2504 unsigned ContentSize =
2505 sizeof(int16_t) + // DWARF ARange version number
2506 sizeof(int32_t) + // Offset of CU in the .debug_info section
2507 sizeof(int8_t) + // Pointer Size (in bytes)
2508 sizeof(int8_t); // Segment Size (in bytes)
2510 unsigned TupleSize = PtrSize * 2;
2512 // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2513 unsigned Padding =
2514 OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2516 ContentSize += Padding;
2517 ContentSize += (List.size() + 1) * TupleSize;
2519 // For each compile unit, write the list of spans it covers.
2520 Asm->OutStreamer.AddComment("Length of ARange Set");
2521 Asm->EmitInt32(ContentSize);
2522 Asm->OutStreamer.AddComment("DWARF Arange version number");
2523 Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2524 Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2525 Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2526 Asm->OutStreamer.AddComment("Address Size (in bytes)");
2527 Asm->EmitInt8(PtrSize);
2528 Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2529 Asm->EmitInt8(0);
2531 Asm->OutStreamer.EmitFill(Padding, 0xff);
2533 for (const ArangeSpan &Span : List) {
2534 Asm->EmitLabelReference(Span.Start, PtrSize);
2536 // Calculate the size as being from the span start to it's end.
2537 if (Span.End) {
2538 Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2539 } else {
2540 // For symbols without an end marker (e.g. common), we
2541 // write a single arange entry containing just that one symbol.
2542 uint64_t Size = SymSize[Span.Start];
2543 if (Size == 0)
2544 Size = 1;
2546 Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2547 }
2548 }
2550 Asm->OutStreamer.AddComment("ARange terminator");
2551 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2552 Asm->OutStreamer.EmitIntValue(0, PtrSize);
2553 }
2554 }
2556 // Emit visible names into a debug ranges section.
2557 void DwarfDebug::emitDebugRanges() {
2558 // Start the dwarf ranges section.
2559 Asm->OutStreamer.SwitchSection(
2560 Asm->getObjFileLowering().getDwarfRangesSection());
2562 // Size for our labels.
2563 unsigned char Size = Asm->getDataLayout().getPointerSize();
2565 // Grab the specific ranges for the compile units in the module.
2566 for (const auto &I : CUMap) {
2567 DwarfCompileUnit *TheCU = I.second;
2569 // Emit a symbol so we can find the beginning of our ranges.
2570 Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2572 // Iterate over the misc ranges for the compile units in the module.
2573 for (const RangeSpanList &List : TheCU->getRangeLists()) {
2574 // Emit our symbol so we can find the beginning of the range.
2575 Asm->OutStreamer.EmitLabel(List.getSym());
2577 for (const RangeSpan &Range : List.getRanges()) {
2578 const MCSymbol *Begin = Range.getStart();
2579 const MCSymbol *End = Range.getEnd();
2580 assert(Begin && "Range without a begin symbol?");
2581 assert(End && "Range without an end symbol?");
2582 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2583 Asm->OutStreamer.EmitSymbolValue(End, Size);
2584 }
2586 // And terminate the list with two 0 values.
2587 Asm->OutStreamer.EmitIntValue(0, Size);
2588 Asm->OutStreamer.EmitIntValue(0, Size);
2589 }
2591 // Now emit a range for the CU itself.
2592 if (useCURanges() && TheCU->getRanges().size()) {
2593 Asm->OutStreamer.EmitLabel(
2594 Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2595 for (const RangeSpan &Range : TheCU->getRanges()) {
2596 const MCSymbol *Begin = Range.getStart();
2597 const MCSymbol *End = Range.getEnd();
2598 assert(Begin && "Range without a begin symbol?");
2599 assert(End && "Range without an end symbol?");
2600 Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2601 Asm->OutStreamer.EmitSymbolValue(End, Size);
2602 }
2603 // And terminate the list with two 0 values.
2604 Asm->OutStreamer.EmitIntValue(0, Size);
2605 Asm->OutStreamer.EmitIntValue(0, Size);
2606 }
2607 }
2608 }
2610 // DWARF5 Experimental Separate Dwarf emitters.
2612 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2613 DwarfUnit *NewU) {
2614 NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2615 U->getCUNode().getSplitDebugFilename());
2617 // Relocate to the beginning of the addr_base section, else 0 for the
2618 // beginning of the one for this compile unit.
2619 if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2620 NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2621 else
2622 NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2624 if (!CompilationDir.empty())
2625 NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2627 addGnuPubAttributes(NewU, Die);
2629 SkeletonHolder.addUnit(NewU);
2630 }
2632 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2633 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2634 // DW_AT_ranges_base, DW_AT_addr_base.
2635 // TODO: Implement DW_AT_ranges_base.
2636 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2638 DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2639 DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2640 CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2641 NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2642 DwarfInfoSectionSym);
2644 NewCU->initStmtList(DwarfLineSectionSym);
2646 initSkeletonUnit(CU, Die, NewCU);
2648 return NewCU;
2649 }
2651 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2652 // DW_AT_addr_base.
2653 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2654 DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2655 *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2657 DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2658 DwarfTypeUnit *NewTU =
2659 new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2660 NewTU->setTypeSignature(TU->getTypeSignature());
2661 NewTU->setType(NULL);
2662 NewTU->initSection(
2663 Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2665 initSkeletonUnit(TU, Die, NewTU);
2666 return NewTU;
2667 }
2669 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2670 // compile units that would normally be in debug_info.
2671 void DwarfDebug::emitDebugInfoDWO() {
2672 assert(useSplitDwarf() && "No split dwarf debug info?");
2673 InfoHolder.emitUnits(this,
2674 Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2675 DwarfAbbrevDWOSectionSym);
2676 }
2678 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2679 // abbreviations for the .debug_info.dwo section.
2680 void DwarfDebug::emitDebugAbbrevDWO() {
2681 assert(useSplitDwarf() && "No split dwarf?");
2682 InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2683 }
2685 void DwarfDebug::emitDebugLineDWO() {
2686 assert(useSplitDwarf() && "No split dwarf?");
2687 Asm->OutStreamer.SwitchSection(
2688 Asm->getObjFileLowering().getDwarfLineDWOSection());
2689 SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2690 }
2692 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2693 // string section and is identical in format to traditional .debug_str
2694 // sections.
2695 void DwarfDebug::emitDebugStrDWO() {
2696 assert(useSplitDwarf() && "No split dwarf?");
2697 const MCSection *OffSec =
2698 Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2699 const MCSymbol *StrSym = DwarfStrSectionSym;
2700 InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2701 OffSec, StrSym);
2702 }
2704 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2705 StringRef Identifier, DIE *RefDie,
2706 DICompositeType CTy) {
2707 // Flag the type unit reference as a declaration so that if it contains
2708 // members (implicit special members, static data member definitions, member
2709 // declarations for definitions in this CU, etc) consumers don't get confused
2710 // and think this is a full definition.
2711 CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2713 const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2714 if (TU) {
2715 CU.addDIETypeSignature(RefDie, *TU);
2716 return;
2717 }
2719 DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2720 DwarfTypeUnit *NewTU = new DwarfTypeUnit(
2721 InfoHolder.getUnits().size(), UnitDie, CU, Asm, this, &InfoHolder,
2722 useSplitDwarf() ? &SplitTypeUnitFileTable : nullptr);
2723 TU = NewTU;
2724 InfoHolder.addUnit(NewTU);
2726 NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2727 CU.getLanguage());
2729 MD5 Hash;
2730 Hash.update(Identifier);
2731 // ... take the least significant 8 bytes and return those. Our MD5
2732 // implementation always returns its results in little endian, swap bytes
2733 // appropriately.
2734 MD5::MD5Result Result;
2735 Hash.final(Result);
2736 uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2737 NewTU->setTypeSignature(Signature);
2738 if (useSplitDwarf())
2739 NewTU->setSkeleton(constructSkeletonTU(NewTU));
2740 else
2741 CU.applyStmtList(*UnitDie);
2743 NewTU->setType(NewTU->createTypeDIE(CTy));
2745 NewTU->initSection(
2746 useSplitDwarf()
2747 ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2748 : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2750 CU.addDIETypeSignature(RefDie, *NewTU);
2751 }
2753 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2754 MCSymbol *Begin, MCSymbol *End) {
2755 Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2756 if (DwarfVersion < 4)
2757 Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2758 else
2759 Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2760 }