Debug Info: Move the complex expression handling (=the remainder) of
[oota-llvm.git] / lib / CodeGen / AsmPrinter / DwarfDebug.cpp
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 //===----------------------------------------------------------------------===//
13
14 #include "DwarfDebug.h"
15
16 #include "ByteStreamer.h"
17 #include "DwarfExpression.h"
18 #include "DwarfCompileUnit.h"
19 #include "DIEHash.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/DIE.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineModuleInfo.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DIBuilder.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/DebugInfo.h"
32 #include "llvm/IR/Instructions.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCSection.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Dwarf.h"
42 #include "llvm/Support/Endian.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/MD5.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/Timer.h"
49 #include "llvm/Target/TargetFrameLowering.h"
50 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #include "llvm/Target/TargetMachine.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Target/TargetSubtargetInfo.h"
55 using namespace llvm;
56
57 #define DEBUG_TYPE "dwarfdebug"
58
59 static cl::opt<bool>
60 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
61                          cl::desc("Disable debug info printing"));
62
63 static cl::opt<bool> UnknownLocations(
64     "use-unknown-locations", cl::Hidden,
65     cl::desc("Make an absence of debug location information explicit."),
66     cl::init(false));
67
68 static cl::opt<bool>
69 GenerateGnuPubSections("generate-gnu-dwarf-pub-sections", cl::Hidden,
70                        cl::desc("Generate GNU-style pubnames and pubtypes"),
71                        cl::init(false));
72
73 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
74                                            cl::Hidden,
75                                            cl::desc("Generate dwarf aranges"),
76                                            cl::init(false));
77
78 namespace {
79 enum DefaultOnOff { Default, Enable, Disable };
80 }
81
82 static cl::opt<DefaultOnOff>
83 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
84                  cl::desc("Output prototype dwarf accelerator tables."),
85                  cl::values(clEnumVal(Default, "Default for platform"),
86                             clEnumVal(Enable, "Enabled"),
87                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
88                  cl::init(Default));
89
90 static cl::opt<DefaultOnOff>
91 SplitDwarf("split-dwarf", cl::Hidden,
92            cl::desc("Output DWARF5 split debug info."),
93            cl::values(clEnumVal(Default, "Default for platform"),
94                       clEnumVal(Enable, "Enabled"),
95                       clEnumVal(Disable, "Disabled"), clEnumValEnd),
96            cl::init(Default));
97
98 static cl::opt<DefaultOnOff>
99 DwarfPubSections("generate-dwarf-pub-sections", cl::Hidden,
100                  cl::desc("Generate DWARF pubnames and pubtypes sections"),
101                  cl::values(clEnumVal(Default, "Default for platform"),
102                             clEnumVal(Enable, "Enabled"),
103                             clEnumVal(Disable, "Disabled"), clEnumValEnd),
104                  cl::init(Default));
105
106 static const char *const DWARFGroupName = "DWARF Emission";
107 static const char *const DbgTimerName = "DWARF Debug Writer";
108
109 //===----------------------------------------------------------------------===//
110
111 /// resolve - Look in the DwarfDebug map for the MDNode that
112 /// corresponds to the reference.
113 template <typename T> T DbgVariable::resolve(DIRef<T> Ref) const {
114   return DD->resolve(Ref);
115 }
116
117 bool DbgVariable::isBlockByrefVariable() const {
118   assert(Var.isVariable() && "Invalid complex DbgVariable!");
119   return Var.isBlockByrefVariable(DD->getTypeIdentifierMap());
120 }
121
122 DIType DbgVariable::getType() const {
123   DIType Ty = Var.getType().resolve(DD->getTypeIdentifierMap());
124   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
125   // addresses instead.
126   if (Var.isBlockByrefVariable(DD->getTypeIdentifierMap())) {
127     /* Byref variables, in Blocks, are declared by the programmer as
128        "SomeType VarName;", but the compiler creates a
129        __Block_byref_x_VarName struct, and gives the variable VarName
130        either the struct, or a pointer to the struct, as its type.  This
131        is necessary for various behind-the-scenes things the compiler
132        needs to do with by-reference variables in blocks.
133
134        However, as far as the original *programmer* is concerned, the
135        variable should still have type 'SomeType', as originally declared.
136
137        The following function dives into the __Block_byref_x_VarName
138        struct to find the original type of the variable.  This will be
139        passed back to the code generating the type for the Debug
140        Information Entry for the variable 'VarName'.  'VarName' will then
141        have the original type 'SomeType' in its debug information.
142
143        The original type 'SomeType' will be the type of the field named
144        'VarName' inside the __Block_byref_x_VarName struct.
145
146        NOTE: In order for this to not completely fail on the debugger
147        side, the Debug Information Entry for the variable VarName needs to
148        have a DW_AT_location that tells the debugger how to unwind through
149        the pointers and __Block_byref_x_VarName struct to find the actual
150        value of the variable.  The function addBlockByrefType does this.  */
151     DIType subType = Ty;
152     uint16_t tag = Ty.getTag();
153
154     if (tag == dwarf::DW_TAG_pointer_type)
155       subType = resolve(DIDerivedType(Ty).getTypeDerivedFrom());
156
157     DIArray Elements = DICompositeType(subType).getElements();
158     for (unsigned i = 0, N = Elements.getNumElements(); i < N; ++i) {
159       DIDerivedType DT(Elements.getElement(i));
160       if (getName() == DT.getName())
161         return (resolve(DT.getTypeDerivedFrom()));
162     }
163   }
164   return Ty;
165 }
166
167 static LLVM_CONSTEXPR DwarfAccelTable::Atom TypeAtoms[] = {
168     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4),
169     DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2),
170     DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1)};
171
172 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
173     : Asm(A), MMI(Asm->MMI), PrevLabel(nullptr), GlobalRangeCount(0),
174       InfoHolder(A, *this, "info_string", DIEValueAllocator),
175       UsedNonDefaultText(false),
176       SkeletonHolder(A, *this, "skel_string", DIEValueAllocator),
177       IsDarwin(Triple(A->getTargetTriple()).isOSDarwin()),
178       AccelNames(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
179                                        dwarf::DW_FORM_data4)),
180       AccelObjC(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
181                                       dwarf::DW_FORM_data4)),
182       AccelNamespace(DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset,
183                                            dwarf::DW_FORM_data4)),
184       AccelTypes(TypeAtoms) {
185
186   DwarfInfoSectionSym = DwarfAbbrevSectionSym = DwarfStrSectionSym = nullptr;
187   DwarfDebugRangeSectionSym = DwarfDebugLocSectionSym = nullptr;
188   DwarfLineSectionSym = nullptr;
189   DwarfAddrSectionSym = nullptr;
190   DwarfAbbrevDWOSectionSym = DwarfStrDWOSectionSym = nullptr;
191   FunctionBeginSym = FunctionEndSym = nullptr;
192   CurFn = nullptr;
193   CurMI = nullptr;
194
195   // Turn on accelerator tables for Darwin by default, pubnames by
196   // default for non-Darwin, and handle split dwarf.
197   if (DwarfAccelTables == Default)
198     HasDwarfAccelTables = IsDarwin;
199   else
200     HasDwarfAccelTables = DwarfAccelTables == Enable;
201
202   if (SplitDwarf == Default)
203     HasSplitDwarf = false;
204   else
205     HasSplitDwarf = SplitDwarf == Enable;
206
207   if (DwarfPubSections == Default)
208     HasDwarfPubSections = !IsDarwin;
209   else
210     HasDwarfPubSections = DwarfPubSections == Enable;
211
212   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
213   DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
214                                     : MMI->getModule()->getDwarfVersion();
215
216   Asm->OutStreamer.getContext().setDwarfVersion(DwarfVersion);
217
218   {
219     NamedRegionTimer T(DbgTimerName, DWARFGroupName, TimePassesIsEnabled);
220     beginModule();
221   }
222 }
223
224 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
225 DwarfDebug::~DwarfDebug() { }
226
227 // Switch to the specified MCSection and emit an assembler
228 // temporary label to it if SymbolStem is specified.
229 static MCSymbol *emitSectionSym(AsmPrinter *Asm, const MCSection *Section,
230                                 const char *SymbolStem = nullptr) {
231   Asm->OutStreamer.SwitchSection(Section);
232   if (!SymbolStem)
233     return nullptr;
234
235   MCSymbol *TmpSym = Asm->GetTempSymbol(SymbolStem);
236   Asm->OutStreamer.EmitLabel(TmpSym);
237   return TmpSym;
238 }
239
240 static bool isObjCClass(StringRef Name) {
241   return Name.startswith("+") || Name.startswith("-");
242 }
243
244 static bool hasObjCCategory(StringRef Name) {
245   if (!isObjCClass(Name))
246     return false;
247
248   return Name.find(") ") != StringRef::npos;
249 }
250
251 static void getObjCClassCategory(StringRef In, StringRef &Class,
252                                  StringRef &Category) {
253   if (!hasObjCCategory(In)) {
254     Class = In.slice(In.find('[') + 1, In.find(' '));
255     Category = "";
256     return;
257   }
258
259   Class = In.slice(In.find('[') + 1, In.find('('));
260   Category = In.slice(In.find('[') + 1, In.find(' '));
261   return;
262 }
263
264 static StringRef getObjCMethodName(StringRef In) {
265   return In.slice(In.find(' ') + 1, In.find(']'));
266 }
267
268 // Helper for sorting sections into a stable output order.
269 static bool SectionSort(const MCSection *A, const MCSection *B) {
270   std::string LA = (A ? A->getLabelBeginName() : "");
271   std::string LB = (B ? B->getLabelBeginName() : "");
272   return LA < LB;
273 }
274
275 // Add the various names to the Dwarf accelerator table names.
276 // TODO: Determine whether or not we should add names for programs
277 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
278 // is only slightly different than the lookup of non-standard ObjC names.
279 void DwarfDebug::addSubprogramNames(DISubprogram SP, DIE &Die) {
280   if (!SP.isDefinition())
281     return;
282   addAccelName(SP.getName(), Die);
283
284   // If the linkage name is different than the name, go ahead and output
285   // that as well into the name table.
286   if (SP.getLinkageName() != "" && SP.getName() != SP.getLinkageName())
287     addAccelName(SP.getLinkageName(), Die);
288
289   // If this is an Objective-C selector name add it to the ObjC accelerator
290   // too.
291   if (isObjCClass(SP.getName())) {
292     StringRef Class, Category;
293     getObjCClassCategory(SP.getName(), Class, Category);
294     addAccelObjC(Class, Die);
295     if (Category != "")
296       addAccelObjC(Category, Die);
297     // Also add the base method name to the name table.
298     addAccelName(getObjCMethodName(SP.getName()), Die);
299   }
300 }
301
302 /// isSubprogramContext - Return true if Context is either a subprogram
303 /// or another context nested inside a subprogram.
304 bool DwarfDebug::isSubprogramContext(const MDNode *Context) {
305   if (!Context)
306     return false;
307   DIDescriptor D(Context);
308   if (D.isSubprogram())
309     return true;
310   if (D.isType())
311     return isSubprogramContext(resolve(DIType(Context).getContext()));
312   return false;
313 }
314
315 /// Check whether we should create a DIE for the given Scope, return true
316 /// if we don't create a DIE (the corresponding DIE is null).
317 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
318   if (Scope->isAbstractScope())
319     return false;
320
321   // We don't create a DIE if there is no Range.
322   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
323   if (Ranges.empty())
324     return true;
325
326   if (Ranges.size() > 1)
327     return false;
328
329   // We don't create a DIE if we have a single Range and the end label
330   // is null.
331   return !getLabelAfterInsn(Ranges.front().second);
332 }
333
334 template <typename Func> void forBothCUs(DwarfCompileUnit &CU, Func F) {
335   F(CU);
336   if (auto *SkelCU = CU.getSkeleton())
337     F(*SkelCU);
338 }
339
340 void DwarfDebug::constructAbstractSubprogramScopeDIE(LexicalScope *Scope) {
341   assert(Scope && Scope->getScopeNode());
342   assert(Scope->isAbstractScope());
343   assert(!Scope->getInlinedAt());
344
345   const MDNode *SP = Scope->getScopeNode();
346
347   ProcessedSPNodes.insert(SP);
348
349   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
350   // was inlined from another compile unit.
351   auto &CU = SPMap[SP];
352   forBothCUs(*CU, [&](DwarfCompileUnit &CU) {
353     CU.constructAbstractSubprogramScopeDIE(Scope);
354   });
355 }
356
357 void DwarfDebug::addGnuPubAttributes(DwarfUnit &U, DIE &D) const {
358   if (!GenerateGnuPubSections)
359     return;
360
361   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
362 }
363
364 // Create new DwarfCompileUnit for the given metadata node with tag
365 // DW_TAG_compile_unit.
366 DwarfCompileUnit &DwarfDebug::constructDwarfCompileUnit(DICompileUnit DIUnit) {
367   StringRef FN = DIUnit.getFilename();
368   CompilationDir = DIUnit.getDirectory();
369
370   auto OwnedUnit = make_unique<DwarfCompileUnit>(
371       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
372   DwarfCompileUnit &NewCU = *OwnedUnit;
373   DIE &Die = NewCU.getUnitDie();
374   InfoHolder.addUnit(std::move(OwnedUnit));
375   if (useSplitDwarf())
376     NewCU.setSkeleton(constructSkeletonCU(NewCU));
377
378   // LTO with assembly output shares a single line table amongst multiple CUs.
379   // To avoid the compilation directory being ambiguous, let the line table
380   // explicitly describe the directory of all files, never relying on the
381   // compilation directory.
382   if (!Asm->OutStreamer.hasRawTextSupport() || SingleCU)
383     Asm->OutStreamer.getContext().setMCLineTableCompilationDir(
384         NewCU.getUniqueID(), CompilationDir);
385
386   NewCU.addString(Die, dwarf::DW_AT_producer, DIUnit.getProducer());
387   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
388                 DIUnit.getLanguage());
389   NewCU.addString(Die, dwarf::DW_AT_name, FN);
390
391   if (!useSplitDwarf()) {
392     NewCU.initStmtList(DwarfLineSectionSym);
393
394     // If we're using split dwarf the compilation dir is going to be in the
395     // skeleton CU and so we don't need to duplicate it here.
396     if (!CompilationDir.empty())
397       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
398
399     addGnuPubAttributes(NewCU, Die);
400   }
401
402   if (DIUnit.isOptimized())
403     NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
404
405   StringRef Flags = DIUnit.getFlags();
406   if (!Flags.empty())
407     NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
408
409   if (unsigned RVer = DIUnit.getRunTimeVersion())
410     NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
411                   dwarf::DW_FORM_data1, RVer);
412
413   if (useSplitDwarf())
414     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoDWOSection(),
415                       DwarfInfoDWOSectionSym);
416   else
417     NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
418                       DwarfInfoSectionSym);
419
420   CUMap.insert(std::make_pair(DIUnit, &NewCU));
421   CUDieMap.insert(std::make_pair(&Die, &NewCU));
422   return NewCU;
423 }
424
425 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
426                                                   const MDNode *N) {
427   DIImportedEntity Module(N);
428   assert(Module.Verify());
429   if (DIE *D = TheCU.getOrCreateContextDIE(Module.getContext()))
430     D->addChild(TheCU.constructImportedEntityDIE(Module));
431 }
432
433 // Emit all Dwarf sections that should come prior to the content. Create
434 // global DIEs and emit initial debug info sections. This is invoked by
435 // the target AsmPrinter.
436 void DwarfDebug::beginModule() {
437   if (DisableDebugInfoPrinting)
438     return;
439
440   const Module *M = MMI->getModule();
441
442   FunctionDIs = makeSubprogramMap(*M);
443
444   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
445   if (!CU_Nodes)
446     return;
447   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
448
449   // Emit initial sections so we can reference labels later.
450   emitSectionLabels();
451
452   SingleCU = CU_Nodes->getNumOperands() == 1;
453
454   for (MDNode *N : CU_Nodes->operands()) {
455     DICompileUnit CUNode(N);
456     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
457     DIArray ImportedEntities = CUNode.getImportedEntities();
458     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
459       ScopesWithImportedEntities.push_back(std::make_pair(
460           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
461           ImportedEntities.getElement(i)));
462     std::sort(ScopesWithImportedEntities.begin(),
463               ScopesWithImportedEntities.end(), less_first());
464     DIArray GVs = CUNode.getGlobalVariables();
465     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
466       CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
467     DIArray SPs = CUNode.getSubprograms();
468     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
469       SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
470     DIArray EnumTypes = CUNode.getEnumTypes();
471     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
472       DIType Ty(EnumTypes.getElement(i));
473       // The enum types array by design contains pointers to
474       // MDNodes rather than DIRefs. Unique them here.
475       DIType UniqueTy(resolve(Ty.getRef()));
476       CU.getOrCreateTypeDIE(UniqueTy);
477     }
478     DIArray RetainedTypes = CUNode.getRetainedTypes();
479     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
480       DIType Ty(RetainedTypes.getElement(i));
481       // The retained types array by design contains pointers to
482       // MDNodes rather than DIRefs. Unique them here.
483       DIType UniqueTy(resolve(Ty.getRef()));
484       CU.getOrCreateTypeDIE(UniqueTy);
485     }
486     // Emit imported_modules last so that the relevant context is already
487     // available.
488     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
489       constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
490   }
491
492   // Tell MMI that we have debug info.
493   MMI->setDebugInfoAvailability(true);
494
495   // Prime section data.
496   SectionMap[Asm->getObjFileLowering().getTextSection()];
497 }
498
499 void DwarfDebug::finishVariableDefinitions() {
500   for (const auto &Var : ConcreteVariables) {
501     DIE *VariableDie = Var->getDIE();
502     assert(VariableDie);
503     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
504     // in the ConcreteVariables list, rather than looking it up again here.
505     // DIE::getUnit isn't simple - it walks parent pointers, etc.
506     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
507     assert(Unit);
508     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
509     if (AbsVar && AbsVar->getDIE()) {
510       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
511                         *AbsVar->getDIE());
512     } else
513       Unit->applyVariableAttributes(*Var, *VariableDie);
514   }
515 }
516
517 void DwarfDebug::finishSubprogramDefinitions() {
518   for (const auto &P : SPMap)
519     forBothCUs(*P.second, [&](DwarfCompileUnit &CU) {
520       CU.finishSubprogramDefinition(DISubprogram(P.first));
521     });
522 }
523
524
525 // Collect info for variables that were optimized out.
526 void DwarfDebug::collectDeadVariables() {
527   const Module *M = MMI->getModule();
528
529   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
530     for (MDNode *N : CU_Nodes->operands()) {
531       DICompileUnit TheCU(N);
532       // Construct subprogram DIE and add variables DIEs.
533       DwarfCompileUnit *SPCU =
534           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
535       assert(SPCU && "Unable to find Compile Unit!");
536       DIArray Subprograms = TheCU.getSubprograms();
537       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
538         DISubprogram SP(Subprograms.getElement(i));
539         if (ProcessedSPNodes.count(SP) != 0)
540           continue;
541         SPCU->collectDeadVariables(SP);
542       }
543     }
544   }
545 }
546
547 void DwarfDebug::finalizeModuleInfo() {
548   finishSubprogramDefinitions();
549
550   finishVariableDefinitions();
551
552   // Collect info for variables that were optimized out.
553   collectDeadVariables();
554
555   // Handle anything that needs to be done on a per-unit basis after
556   // all other generation.
557   for (const auto &P : CUMap) {
558     auto &TheCU = *P.second;
559     // Emit DW_AT_containing_type attribute to connect types with their
560     // vtable holding type.
561     TheCU.constructContainingTypeDIEs();
562
563     // Add CU specific attributes if we need to add any.
564     // If we're splitting the dwarf out now that we've got the entire
565     // CU then add the dwo id to it.
566     auto *SkCU = TheCU.getSkeleton();
567     if (useSplitDwarf()) {
568       // Emit a unique identifier for this CU.
569       uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
570       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
571                     dwarf::DW_FORM_data8, ID);
572       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
573                     dwarf::DW_FORM_data8, ID);
574
575       // We don't keep track of which addresses are used in which CU so this
576       // is a bit pessimistic under LTO.
577       if (!AddrPool.isEmpty())
578         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
579                               DwarfAddrSectionSym, DwarfAddrSectionSym);
580       if (!SkCU->getRangeLists().empty())
581         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
582                               DwarfDebugRangeSectionSym,
583                               DwarfDebugRangeSectionSym);
584     }
585
586     // If we have code split among multiple sections or non-contiguous
587     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
588     // remain in the .o file, otherwise add a DW_AT_low_pc.
589     // FIXME: We should use ranges allow reordering of code ala
590     // .subsections_via_symbols in mach-o. This would mean turning on
591     // ranges for all subprogram DIEs for mach-o.
592     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
593     if (unsigned NumRanges = TheCU.getRanges().size()) {
594       if (NumRanges > 1)
595         // A DW_AT_low_pc attribute may also be specified in combination with
596         // DW_AT_ranges to specify the default base address for use in
597         // location lists (see Section 2.6.2) and range lists (see Section
598         // 2.17.3).
599         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
600       else
601         TheCU.setBaseAddress(TheCU.getRanges().front().getStart());
602       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
603     }
604   }
605
606   // Compute DIE offsets and sizes.
607   InfoHolder.computeSizeAndOffsets();
608   if (useSplitDwarf())
609     SkeletonHolder.computeSizeAndOffsets();
610 }
611
612 void DwarfDebug::endSections() {
613   // Filter labels by section.
614   for (const SymbolCU &SCU : ArangeLabels) {
615     if (SCU.Sym->isInSection()) {
616       // Make a note of this symbol and it's section.
617       const MCSection *Section = &SCU.Sym->getSection();
618       if (!Section->getKind().isMetadata())
619         SectionMap[Section].push_back(SCU);
620     } else {
621       // Some symbols (e.g. common/bss on mach-o) can have no section but still
622       // appear in the output. This sucks as we rely on sections to build
623       // arange spans. We can do it without, but it's icky.
624       SectionMap[nullptr].push_back(SCU);
625     }
626   }
627
628   // Build a list of sections used.
629   std::vector<const MCSection *> Sections;
630   for (const auto &it : SectionMap) {
631     const MCSection *Section = it.first;
632     Sections.push_back(Section);
633   }
634
635   // Sort the sections into order.
636   // This is only done to ensure consistent output order across different runs.
637   std::sort(Sections.begin(), Sections.end(), SectionSort);
638
639   // Add terminating symbols for each section.
640   for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
641     const MCSection *Section = Sections[ID];
642     MCSymbol *Sym = nullptr;
643
644     if (Section) {
645       // We can't call MCSection::getLabelEndName, as it's only safe to do so
646       // if we know the section name up-front. For user-created sections, the
647       // resulting label may not be valid to use as a label. (section names can
648       // use a greater set of characters on some systems)
649       Sym = Asm->GetTempSymbol("debug_end", ID);
650       Asm->OutStreamer.SwitchSection(Section);
651       Asm->OutStreamer.EmitLabel(Sym);
652     }
653
654     // Insert a final terminator.
655     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
656   }
657 }
658
659 // Emit all Dwarf sections that should come after the content.
660 void DwarfDebug::endModule() {
661   assert(CurFn == nullptr);
662   assert(CurMI == nullptr);
663
664   // If we aren't actually generating debug info (check beginModule -
665   // conditionalized on !DisableDebugInfoPrinting and the presence of the
666   // llvm.dbg.cu metadata node)
667   if (!DwarfInfoSectionSym)
668     return;
669
670   // End any existing sections.
671   // TODO: Does this need to happen?
672   endSections();
673
674   // Finalize the debug info for the module.
675   finalizeModuleInfo();
676
677   emitDebugStr();
678
679   // Emit all the DIEs into a debug info section.
680   emitDebugInfo();
681
682   // Corresponding abbreviations into a abbrev section.
683   emitAbbreviations();
684
685   // Emit info into a debug aranges section.
686   if (GenerateARangeSection)
687     emitDebugARanges();
688
689   // Emit info into a debug ranges section.
690   emitDebugRanges();
691
692   if (useSplitDwarf()) {
693     emitDebugStrDWO();
694     emitDebugInfoDWO();
695     emitDebugAbbrevDWO();
696     emitDebugLineDWO();
697     emitDebugLocDWO();
698     // Emit DWO addresses.
699     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
700   } else
701     // Emit info into a debug loc section.
702     emitDebugLoc();
703
704   // Emit info into the dwarf accelerator table sections.
705   if (useDwarfAccelTables()) {
706     emitAccelNames();
707     emitAccelObjC();
708     emitAccelNamespaces();
709     emitAccelTypes();
710   }
711
712   // Emit the pubnames and pubtypes sections if requested.
713   if (HasDwarfPubSections) {
714     emitDebugPubNames(GenerateGnuPubSections);
715     emitDebugPubTypes(GenerateGnuPubSections);
716   }
717
718   // clean up.
719   SPMap.clear();
720   AbstractVariables.clear();
721 }
722
723 // Find abstract variable, if any, associated with Var.
724 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
725                                                      DIVariable &Cleansed) {
726   LLVMContext &Ctx = DV->getContext();
727   // More then one inlined variable corresponds to one abstract variable.
728   // FIXME: This duplication of variables when inlining should probably be
729   // removed. It's done to allow each DIVariable to describe its location
730   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
731   // make it accurate then remove this duplication/cleansing stuff.
732   Cleansed = cleanseInlinedVariable(DV, Ctx);
733   auto I = AbstractVariables.find(Cleansed);
734   if (I != AbstractVariables.end())
735     return I->second.get();
736   return nullptr;
737 }
738
739 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
740   DIVariable Cleansed;
741   return getExistingAbstractVariable(DV, Cleansed);
742 }
743
744 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
745                                         LexicalScope *Scope) {
746   auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
747   InfoHolder.addScopeVariable(Scope, AbsDbgVariable.get());
748   AbstractVariables[Var] = std::move(AbsDbgVariable);
749 }
750
751 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
752                                                  const MDNode *ScopeNode) {
753   DIVariable Cleansed = DV;
754   if (getExistingAbstractVariable(DV, Cleansed))
755     return;
756
757   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
758 }
759
760 void
761 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
762                                                     const MDNode *ScopeNode) {
763   DIVariable Cleansed = DV;
764   if (getExistingAbstractVariable(DV, Cleansed))
765     return;
766
767   if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
768     createAbstractVariable(Cleansed, Scope);
769 }
770
771 // Collect variable information from side table maintained by MMI.
772 void DwarfDebug::collectVariableInfoFromMMITable(
773     SmallPtrSetImpl<const MDNode *> &Processed) {
774   for (const auto &VI : MMI->getVariableDbgInfo()) {
775     if (!VI.Var)
776       continue;
777     Processed.insert(VI.Var);
778     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
779
780     // If variable scope is not found then skip this variable.
781     if (!Scope)
782       continue;
783
784     DIVariable DV(VI.Var);
785     DIExpression Expr(VI.Expr);
786     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
787     ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
788     DbgVariable *RegVar = ConcreteVariables.back().get();
789     RegVar->setFrameIndex(VI.Slot);
790     InfoHolder.addScopeVariable(Scope, RegVar);
791   }
792 }
793
794 // Get .debug_loc entry for the instruction range starting at MI.
795 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
796   const MDNode *Expr = MI->getDebugExpression();
797   const MDNode *Var = MI->getDebugVariable();
798
799   assert(MI->getNumOperands() == 4);
800   if (MI->getOperand(0).isReg()) {
801     MachineLocation MLoc;
802     // If the second operand is an immediate, this is a
803     // register-indirect address.
804     if (!MI->getOperand(1).isImm())
805       MLoc.set(MI->getOperand(0).getReg());
806     else
807       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
808     return DebugLocEntry::Value(Var, Expr, MLoc);
809   }
810   if (MI->getOperand(0).isImm())
811     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
812   if (MI->getOperand(0).isFPImm())
813     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
814   if (MI->getOperand(0).isCImm())
815     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
816
817   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
818 }
819
820 /// Determine whether two variable pieces overlap.
821 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
822   if (!P1.isVariablePiece() || !P2.isVariablePiece())
823     return true;
824   unsigned l1 = P1.getPieceOffset();
825   unsigned l2 = P2.getPieceOffset();
826   unsigned r1 = l1 + P1.getPieceSize();
827   unsigned r2 = l2 + P2.getPieceSize();
828   // True where [l1,r1[ and [r1,r2[ overlap.
829   return (l1 < r2) && (l2 < r1);
830 }
831
832 /// Build the location list for all DBG_VALUEs in the function that
833 /// describe the same variable.  If the ranges of several independent
834 /// pieces of the same variable overlap partially, split them up and
835 /// combine the ranges. The resulting DebugLocEntries are will have
836 /// strict monotonically increasing begin addresses and will never
837 /// overlap.
838 //
839 // Input:
840 //
841 //   Ranges History [var, loc, piece ofs size]
842 // 0 |      [x, (reg0, piece 0, 32)]
843 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
844 // 2 | |    ...
845 // 3   |    [clobber reg0]
846 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
847 //
848 // Output:
849 //
850 // [0-1]    [x, (reg0, piece  0, 32)]
851 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
852 // [3-4]    [x, (reg1, piece 32, 32)]
853 // [4- ]    [x, (mem,  piece  0, 64)]
854 void
855 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
856                               const DbgValueHistoryMap::InstrRanges &Ranges) {
857   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
858
859   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
860     const MachineInstr *Begin = I->first;
861     const MachineInstr *End = I->second;
862     assert(Begin->isDebugValue() && "Invalid History entry");
863
864     // Check if a variable is inaccessible in this range.
865     if (Begin->getNumOperands() > 1 &&
866         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
867       OpenRanges.clear();
868       continue;
869     }
870
871     // If this piece overlaps with any open ranges, truncate them.
872     DIExpression DIExpr = Begin->getDebugExpression();
873     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
874                                [&](DebugLocEntry::Value R) {
875       return piecesOverlap(DIExpr, R.getExpression());
876     });
877     OpenRanges.erase(Last, OpenRanges.end());
878
879     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
880     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
881
882     const MCSymbol *EndLabel;
883     if (End != nullptr)
884       EndLabel = getLabelAfterInsn(End);
885     else if (std::next(I) == Ranges.end())
886       EndLabel = FunctionEndSym;
887     else
888       EndLabel = getLabelBeforeInsn(std::next(I)->first);
889     assert(EndLabel && "Forgot label after instruction ending a range!");
890
891     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
892
893     auto Value = getDebugLocValue(Begin);
894     DebugLocEntry Loc(StartLabel, EndLabel, Value);
895     bool couldMerge = false;
896
897     // If this is a piece, it may belong to the current DebugLocEntry.
898     if (DIExpr.isVariablePiece()) {
899       // Add this value to the list of open ranges.
900       OpenRanges.push_back(Value);
901
902       // Attempt to add the piece to the last entry.
903       if (!DebugLoc.empty())
904         if (DebugLoc.back().MergeValues(Loc))
905           couldMerge = true;
906     }
907
908     if (!couldMerge) {
909       // Need to add a new DebugLocEntry. Add all values from still
910       // valid non-overlapping pieces.
911       if (OpenRanges.size())
912         Loc.addValues(OpenRanges);
913
914       DebugLoc.push_back(std::move(Loc));
915     }
916
917     // Attempt to coalesce the ranges of two otherwise identical
918     // DebugLocEntries.
919     auto CurEntry = DebugLoc.rbegin();
920     auto PrevEntry = std::next(CurEntry);
921     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
922       DebugLoc.pop_back();
923
924     DEBUG({
925       dbgs() << CurEntry->getValues().size() << " Values:\n";
926       for (auto Value : CurEntry->getValues()) {
927         Value.getVariable()->dump();
928         Value.getExpression()->dump();
929       }
930       dbgs() << "-----\n";
931     });
932   }
933 }
934
935
936 // Find variables for each lexical scope.
937 void
938 DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU, DISubprogram SP,
939                                 SmallPtrSetImpl<const MDNode *> &Processed) {
940   // Grab the variable info that was squirreled away in the MMI side-table.
941   collectVariableInfoFromMMITable(Processed);
942
943   for (const auto &I : DbgValues) {
944     DIVariable DV(I.first);
945     if (Processed.count(DV))
946       continue;
947
948     // Instruction ranges, specifying where DV is accessible.
949     const auto &Ranges = I.second;
950     if (Ranges.empty())
951       continue;
952
953     LexicalScope *Scope = nullptr;
954     if (MDNode *IA = DV.getInlinedAt()) {
955       DebugLoc DL = DebugLoc::getFromDILocation(IA);
956       Scope = LScopes.findInlinedScope(DebugLoc::get(
957           DL.getLine(), DL.getCol(), DV.getContext(), IA));
958     } else
959       Scope = LScopes.findLexicalScope(DV.getContext());
960     // If variable scope is not found then skip this variable.
961     if (!Scope)
962       continue;
963
964     Processed.insert(DV);
965     const MachineInstr *MInsn = Ranges.front().first;
966     assert(MInsn->isDebugValue() && "History must begin with debug value");
967     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
968     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
969     DbgVariable *RegVar = ConcreteVariables.back().get();
970     InfoHolder.addScopeVariable(Scope, RegVar);
971
972     // Check if the first DBG_VALUE is valid for the rest of the function.
973     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
974       continue;
975
976     // Handle multiple DBG_VALUE instructions describing one variable.
977     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
978
979     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
980     DebugLocList &LocList = DotDebugLocEntries.back();
981     LocList.CU = &TheCU;
982     LocList.Label =
983         Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
984
985     // Build the location list for this variable.
986     buildLocationList(LocList.List, Ranges);
987   }
988
989   // Collect info for variables that were optimized out.
990   DIArray Variables = SP.getVariables();
991   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
992     DIVariable DV(Variables.getElement(i));
993     assert(DV.isVariable());
994     if (!Processed.insert(DV).second)
995       continue;
996     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
997       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
998       DIExpression NoExpr;
999       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1000       InfoHolder.addScopeVariable(Scope, ConcreteVariables.back().get());
1001     }
1002   }
1003 }
1004
1005 // Return Label preceding the instruction.
1006 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1007   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1008   assert(Label && "Didn't insert label before instruction");
1009   return Label;
1010 }
1011
1012 // Return Label immediately following the instruction.
1013 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1014   return LabelsAfterInsn.lookup(MI);
1015 }
1016
1017 // Process beginning of an instruction.
1018 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1019   assert(CurMI == nullptr);
1020   CurMI = MI;
1021   // Check if source location changes, but ignore DBG_VALUE locations.
1022   if (!MI->isDebugValue()) {
1023     DebugLoc DL = MI->getDebugLoc();
1024     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1025       unsigned Flags = 0;
1026       PrevInstLoc = DL;
1027       if (DL == PrologEndLoc) {
1028         Flags |= DWARF2_FLAG_PROLOGUE_END;
1029         PrologEndLoc = DebugLoc();
1030         Flags |= DWARF2_FLAG_IS_STMT;
1031       }
1032       if (DL.getLine() !=
1033           Asm->OutStreamer.getContext().getCurrentDwarfLoc().getLine())
1034         Flags |= DWARF2_FLAG_IS_STMT;
1035
1036       if (!DL.isUnknown()) {
1037         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1038         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1039       } else
1040         recordSourceLine(0, 0, nullptr, 0);
1041     }
1042   }
1043
1044   // Insert labels where requested.
1045   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1046       LabelsBeforeInsn.find(MI);
1047
1048   // No label needed.
1049   if (I == LabelsBeforeInsn.end())
1050     return;
1051
1052   // Label already assigned.
1053   if (I->second)
1054     return;
1055
1056   if (!PrevLabel) {
1057     PrevLabel = MMI->getContext().CreateTempSymbol();
1058     Asm->OutStreamer.EmitLabel(PrevLabel);
1059   }
1060   I->second = PrevLabel;
1061 }
1062
1063 // Process end of an instruction.
1064 void DwarfDebug::endInstruction() {
1065   assert(CurMI != nullptr);
1066   // Don't create a new label after DBG_VALUE instructions.
1067   // They don't generate code.
1068   if (!CurMI->isDebugValue())
1069     PrevLabel = nullptr;
1070
1071   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1072       LabelsAfterInsn.find(CurMI);
1073   CurMI = nullptr;
1074
1075   // No label needed.
1076   if (I == LabelsAfterInsn.end())
1077     return;
1078
1079   // Label already assigned.
1080   if (I->second)
1081     return;
1082
1083   // We need a label after this instruction.
1084   if (!PrevLabel) {
1085     PrevLabel = MMI->getContext().CreateTempSymbol();
1086     Asm->OutStreamer.EmitLabel(PrevLabel);
1087   }
1088   I->second = PrevLabel;
1089 }
1090
1091 // Each LexicalScope has first instruction and last instruction to mark
1092 // beginning and end of a scope respectively. Create an inverse map that list
1093 // scopes starts (and ends) with an instruction. One instruction may start (or
1094 // end) multiple scopes. Ignore scopes that are not reachable.
1095 void DwarfDebug::identifyScopeMarkers() {
1096   SmallVector<LexicalScope *, 4> WorkList;
1097   WorkList.push_back(LScopes.getCurrentFunctionScope());
1098   while (!WorkList.empty()) {
1099     LexicalScope *S = WorkList.pop_back_val();
1100
1101     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1102     if (!Children.empty())
1103       WorkList.append(Children.begin(), Children.end());
1104
1105     if (S->isAbstractScope())
1106       continue;
1107
1108     for (const InsnRange &R : S->getRanges()) {
1109       assert(R.first && "InsnRange does not have first instruction!");
1110       assert(R.second && "InsnRange does not have second instruction!");
1111       requestLabelBeforeInsn(R.first);
1112       requestLabelAfterInsn(R.second);
1113     }
1114   }
1115 }
1116
1117 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1118   // First known non-DBG_VALUE and non-frame setup location marks
1119   // the beginning of the function body.
1120   for (const auto &MBB : *MF)
1121     for (const auto &MI : MBB)
1122       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1123         !MI.getDebugLoc().isUnknown()) {
1124         // Did the target forget to set the FrameSetup flag for CFI insns?
1125         assert(!MI.isCFIInstruction() &&
1126                "First non-frame-setup instruction is a CFI instruction.");
1127         return MI.getDebugLoc();
1128       }
1129   return DebugLoc();
1130 }
1131
1132 // Gather pre-function debug information.  Assumes being called immediately
1133 // after the function entry point has been emitted.
1134 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1135   CurFn = MF;
1136
1137   // If there's no debug info for the function we're not going to do anything.
1138   if (!MMI->hasDebugInfo())
1139     return;
1140
1141   auto DI = FunctionDIs.find(MF->getFunction());
1142   if (DI == FunctionDIs.end())
1143     return;
1144
1145   // Grab the lexical scopes for the function, if we don't have any of those
1146   // then we're not going to be able to do anything.
1147   LScopes.initialize(*MF);
1148   if (LScopes.empty())
1149     return;
1150
1151   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1152
1153   // Make sure that each lexical scope will have a begin/end label.
1154   identifyScopeMarkers();
1155
1156   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1157   // belongs to so that we add to the correct per-cu line table in the
1158   // non-asm case.
1159   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1160   // FnScope->getScopeNode() and DI->second should represent the same function,
1161   // though they may not be the same MDNode due to inline functions merged in
1162   // LTO where the debug info metadata still differs (either due to distinct
1163   // written differences - two versions of a linkonce_odr function
1164   // written/copied into two separate files, or some sub-optimal metadata that
1165   // isn't structurally identical (see: file path/name info from clang, which
1166   // includes the directory of the cpp file being built, even when the file name
1167   // is absolute (such as an <> lookup header)))
1168   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1169   assert(TheCU && "Unable to find compile unit!");
1170   if (Asm->OutStreamer.hasRawTextSupport())
1171     // Use a single line table if we are generating assembly.
1172     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1173   else
1174     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1175
1176   // Emit a label for the function so that we have a beginning address.
1177   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1178   // Assumes in correct section after the entry point.
1179   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1180
1181   // Calculate history for local variables.
1182   calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1183                            DbgValues);
1184
1185   // Request labels for the full history.
1186   for (const auto &I : DbgValues) {
1187     const auto &Ranges = I.second;
1188     if (Ranges.empty())
1189       continue;
1190
1191     // The first mention of a function argument gets the FunctionBeginSym
1192     // label, so arguments are visible when breaking at function entry.
1193     DIVariable DIVar(Ranges.front().first->getDebugVariable());
1194     if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1195         getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1196       LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1197       if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1198         // Mark all non-overlapping initial pieces.
1199         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1200           DIExpression Piece = I->first->getDebugExpression();
1201           if (std::all_of(Ranges.begin(), I,
1202                           [&](DbgValueHistoryMap::InstrRange Pred) {
1203                 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1204               }))
1205             LabelsBeforeInsn[I->first] = FunctionBeginSym;
1206           else
1207             break;
1208         }
1209       }
1210     }
1211
1212     for (const auto &Range : Ranges) {
1213       requestLabelBeforeInsn(Range.first);
1214       if (Range.second)
1215         requestLabelAfterInsn(Range.second);
1216     }
1217   }
1218
1219   PrevInstLoc = DebugLoc();
1220   PrevLabel = FunctionBeginSym;
1221
1222   // Record beginning of function.
1223   PrologEndLoc = findPrologueEndLoc(MF);
1224   if (!PrologEndLoc.isUnknown()) {
1225     DebugLoc FnStartDL =
1226         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1227     recordSourceLine(
1228         FnStartDL.getLine(), FnStartDL.getCol(),
1229         FnStartDL.getScope(MF->getFunction()->getContext()),
1230         // We'd like to list the prologue as "not statements" but GDB behaves
1231         // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1232         DWARF2_FLAG_IS_STMT);
1233   }
1234 }
1235
1236 // Gather and emit post-function debug information.
1237 void DwarfDebug::endFunction(const MachineFunction *MF) {
1238   assert(CurFn == MF &&
1239       "endFunction should be called with the same function as beginFunction");
1240
1241   if (!MMI->hasDebugInfo() || LScopes.empty() ||
1242       !FunctionDIs.count(MF->getFunction())) {
1243     // If we don't have a lexical scope for this function then there will
1244     // be a hole in the range information. Keep note of this by setting the
1245     // previously used section to nullptr.
1246     PrevCU = nullptr;
1247     CurFn = nullptr;
1248     return;
1249   }
1250
1251   // Define end label for subprogram.
1252   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1253   // Assumes in correct section after the entry point.
1254   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1255
1256   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1257   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1258
1259   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1260   DISubprogram SP(FnScope->getScopeNode());
1261   DwarfCompileUnit &TheCU = *SPMap.lookup(SP);
1262
1263   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1264   collectVariableInfo(TheCU, SP, ProcessedVars);
1265
1266   // Add the range of this function to the list of ranges for the CU.
1267   TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1268
1269   // Under -gmlt, skip building the subprogram if there are no inlined
1270   // subroutines inside it.
1271   if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1272       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1273     assert(InfoHolder.getScopeVariables().empty());
1274     assert(DbgValues.empty());
1275     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1276     // by a -gmlt CU. Add a test and remove this assertion.
1277     assert(AbstractVariables.empty());
1278     LabelsBeforeInsn.clear();
1279     LabelsAfterInsn.clear();
1280     PrevLabel = nullptr;
1281     CurFn = nullptr;
1282     return;
1283   }
1284
1285 #ifndef NDEBUG
1286   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1287 #endif
1288   // Construct abstract scopes.
1289   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1290     DISubprogram SP(AScope->getScopeNode());
1291     assert(SP.isSubprogram());
1292     // Collect info for variables that were optimized out.
1293     DIArray Variables = SP.getVariables();
1294     for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1295       DIVariable DV(Variables.getElement(i));
1296       assert(DV && DV.isVariable());
1297       if (!ProcessedVars.insert(DV).second)
1298         continue;
1299       ensureAbstractVariableIsCreated(DV, DV.getContext());
1300       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1301              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1302     }
1303     constructAbstractSubprogramScopeDIE(AScope);
1304   }
1305
1306   TheCU.constructSubprogramScopeDIE(FnScope);
1307   if (auto *SkelCU = TheCU.getSkeleton())
1308     if (!LScopes.getAbstractScopesList().empty())
1309       SkelCU->constructSubprogramScopeDIE(FnScope);
1310
1311   // Clear debug info
1312   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1313   // DbgVariables except those that are also in AbstractVariables (since they
1314   // can be used cross-function)
1315   InfoHolder.getScopeVariables().clear();
1316   DbgValues.clear();
1317   LabelsBeforeInsn.clear();
1318   LabelsAfterInsn.clear();
1319   PrevLabel = nullptr;
1320   CurFn = nullptr;
1321 }
1322
1323 // Register a source line with debug info. Returns the  unique label that was
1324 // emitted and which provides correspondence to the source line list.
1325 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1326                                   unsigned Flags) {
1327   StringRef Fn;
1328   StringRef Dir;
1329   unsigned Src = 1;
1330   unsigned Discriminator = 0;
1331   if (DIScope Scope = DIScope(S)) {
1332     assert(Scope.isScope());
1333     Fn = Scope.getFilename();
1334     Dir = Scope.getDirectory();
1335     if (Scope.isLexicalBlockFile())
1336       Discriminator = DILexicalBlockFile(S).getDiscriminator();
1337
1338     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1339     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1340               .getOrCreateSourceID(Fn, Dir);
1341   }
1342   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1343                                          Discriminator, Fn);
1344 }
1345
1346 //===----------------------------------------------------------------------===//
1347 // Emit Methods
1348 //===----------------------------------------------------------------------===//
1349
1350 // Emit initial Dwarf sections with a label at the start of each one.
1351 void DwarfDebug::emitSectionLabels() {
1352   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1353
1354   // Dwarf sections base addresses.
1355   DwarfInfoSectionSym =
1356       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1357   if (useSplitDwarf()) {
1358     DwarfInfoDWOSectionSym =
1359         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1360     DwarfTypesDWOSectionSym =
1361         emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1362   }
1363   DwarfAbbrevSectionSym =
1364       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1365   if (useSplitDwarf())
1366     DwarfAbbrevDWOSectionSym = emitSectionSym(
1367         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1368   if (GenerateARangeSection)
1369     emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1370
1371   DwarfLineSectionSym =
1372       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1373   if (GenerateGnuPubSections) {
1374     DwarfGnuPubNamesSectionSym =
1375         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1376     DwarfGnuPubTypesSectionSym =
1377         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1378   } else if (HasDwarfPubSections) {
1379     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1380     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1381   }
1382
1383   DwarfStrSectionSym =
1384       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1385   if (useSplitDwarf()) {
1386     DwarfStrDWOSectionSym =
1387         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1388     DwarfAddrSectionSym =
1389         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1390     DwarfDebugLocSectionSym =
1391         emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1392   } else
1393     DwarfDebugLocSectionSym =
1394         emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1395   DwarfDebugRangeSectionSym =
1396       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1397 }
1398
1399 // Recursively emits a debug information entry.
1400 void DwarfDebug::emitDIE(DIE &Die) {
1401   // Get the abbreviation for this DIE.
1402   const DIEAbbrev &Abbrev = Die.getAbbrev();
1403
1404   // Emit the code (index) for the abbreviation.
1405   if (Asm->isVerbose())
1406     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1407                                 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1408                                 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1409                                 dwarf::TagString(Abbrev.getTag()));
1410   Asm->EmitULEB128(Abbrev.getNumber());
1411
1412   const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1413   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1414
1415   // Emit the DIE attribute values.
1416   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1417     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1418     dwarf::Form Form = AbbrevData[i].getForm();
1419     assert(Form && "Too many attributes for DIE (check abbreviation)");
1420
1421     if (Asm->isVerbose()) {
1422       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1423       if (Attr == dwarf::DW_AT_accessibility)
1424         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1425             cast<DIEInteger>(Values[i])->getValue()));
1426     }
1427
1428     // Emit an attribute using the defined form.
1429     Values[i]->EmitValue(Asm, Form);
1430   }
1431
1432   // Emit the DIE children if any.
1433   if (Abbrev.hasChildren()) {
1434     for (auto &Child : Die.getChildren())
1435       emitDIE(*Child);
1436
1437     Asm->OutStreamer.AddComment("End Of Children Mark");
1438     Asm->EmitInt8(0);
1439   }
1440 }
1441
1442 // Emit the debug info section.
1443 void DwarfDebug::emitDebugInfo() {
1444   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1445
1446   Holder.emitUnits(DwarfAbbrevSectionSym);
1447 }
1448
1449 // Emit the abbreviation section.
1450 void DwarfDebug::emitAbbreviations() {
1451   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1452
1453   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1454 }
1455
1456 // Emit the last address of the section and the end of the line matrix.
1457 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1458   // Define last address of section.
1459   Asm->OutStreamer.AddComment("Extended Op");
1460   Asm->EmitInt8(0);
1461
1462   Asm->OutStreamer.AddComment("Op size");
1463   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1464   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1465   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1466
1467   Asm->OutStreamer.AddComment("Section end label");
1468
1469   Asm->OutStreamer.EmitSymbolValue(
1470       Asm->GetTempSymbol("section_end", SectionEnd),
1471       Asm->getDataLayout().getPointerSize());
1472
1473   // Mark end of matrix.
1474   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1475   Asm->EmitInt8(0);
1476   Asm->EmitInt8(1);
1477   Asm->EmitInt8(1);
1478 }
1479
1480 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1481                            StringRef TableName, StringRef SymName) {
1482   Accel.FinalizeTable(Asm, TableName);
1483   Asm->OutStreamer.SwitchSection(Section);
1484   auto *SectionBegin = Asm->GetTempSymbol(SymName);
1485   Asm->OutStreamer.EmitLabel(SectionBegin);
1486
1487   // Emit the full data.
1488   Accel.Emit(Asm, SectionBegin, this, DwarfStrSectionSym);
1489 }
1490
1491 // Emit visible names into a hashed accelerator table section.
1492 void DwarfDebug::emitAccelNames() {
1493   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1494             "Names", "names_begin");
1495 }
1496
1497 // Emit objective C classes and categories into a hashed accelerator table
1498 // section.
1499 void DwarfDebug::emitAccelObjC() {
1500   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1501             "ObjC", "objc_begin");
1502 }
1503
1504 // Emit namespace dies into a hashed accelerator table.
1505 void DwarfDebug::emitAccelNamespaces() {
1506   emitAccel(AccelNamespace,
1507             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1508             "namespac", "namespac_begin");
1509 }
1510
1511 // Emit type dies into a hashed accelerator table.
1512 void DwarfDebug::emitAccelTypes() {
1513   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1514             "types", "types_begin");
1515 }
1516
1517 // Public name handling.
1518 // The format for the various pubnames:
1519 //
1520 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1521 // for the DIE that is named.
1522 //
1523 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1524 // into the CU and the index value is computed according to the type of value
1525 // for the DIE that is named.
1526 //
1527 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1528 // it's the offset within the debug_info/debug_types dwo section, however, the
1529 // reference in the pubname header doesn't change.
1530
1531 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1532 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1533                                                         const DIE *Die) {
1534   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1535
1536   // We could have a specification DIE that has our most of our knowledge,
1537   // look for that now.
1538   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1539   if (SpecVal) {
1540     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1541     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1542       Linkage = dwarf::GIEL_EXTERNAL;
1543   } else if (Die->findAttribute(dwarf::DW_AT_external))
1544     Linkage = dwarf::GIEL_EXTERNAL;
1545
1546   switch (Die->getTag()) {
1547   case dwarf::DW_TAG_class_type:
1548   case dwarf::DW_TAG_structure_type:
1549   case dwarf::DW_TAG_union_type:
1550   case dwarf::DW_TAG_enumeration_type:
1551     return dwarf::PubIndexEntryDescriptor(
1552         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1553                               ? dwarf::GIEL_STATIC
1554                               : dwarf::GIEL_EXTERNAL);
1555   case dwarf::DW_TAG_typedef:
1556   case dwarf::DW_TAG_base_type:
1557   case dwarf::DW_TAG_subrange_type:
1558     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1559   case dwarf::DW_TAG_namespace:
1560     return dwarf::GIEK_TYPE;
1561   case dwarf::DW_TAG_subprogram:
1562     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1563   case dwarf::DW_TAG_constant:
1564   case dwarf::DW_TAG_variable:
1565     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1566   case dwarf::DW_TAG_enumerator:
1567     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1568                                           dwarf::GIEL_STATIC);
1569   default:
1570     return dwarf::GIEK_NONE;
1571   }
1572 }
1573
1574 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1575 ///
1576 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1577   const MCSection *PSec =
1578       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1579                : Asm->getObjFileLowering().getDwarfPubNamesSection();
1580
1581   emitDebugPubSection(GnuStyle, PSec, "Names",
1582                       &DwarfCompileUnit::getGlobalNames);
1583 }
1584
1585 void DwarfDebug::emitDebugPubSection(
1586     bool GnuStyle, const MCSection *PSec, StringRef Name,
1587     const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1588   for (const auto &NU : CUMap) {
1589     DwarfCompileUnit *TheU = NU.second;
1590
1591     const auto &Globals = (TheU->*Accessor)();
1592
1593     if (Globals.empty())
1594       continue;
1595
1596     if (auto *Skeleton = TheU->getSkeleton())
1597       TheU = Skeleton;
1598     unsigned ID = TheU->getUniqueID();
1599
1600     // Start the dwarf pubnames section.
1601     Asm->OutStreamer.SwitchSection(PSec);
1602
1603     // Emit the header.
1604     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1605     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1606     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1607     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1608
1609     Asm->OutStreamer.EmitLabel(BeginLabel);
1610
1611     Asm->OutStreamer.AddComment("DWARF Version");
1612     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1613
1614     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1615     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1616
1617     Asm->OutStreamer.AddComment("Compilation Unit Length");
1618     Asm->EmitInt32(TheU->getLength());
1619
1620     // Emit the pubnames for this compilation unit.
1621     for (const auto &GI : Globals) {
1622       const char *Name = GI.getKeyData();
1623       const DIE *Entity = GI.second;
1624
1625       Asm->OutStreamer.AddComment("DIE offset");
1626       Asm->EmitInt32(Entity->getOffset());
1627
1628       if (GnuStyle) {
1629         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1630         Asm->OutStreamer.AddComment(
1631             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1632             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1633         Asm->EmitInt8(Desc.toBits());
1634       }
1635
1636       Asm->OutStreamer.AddComment("External Name");
1637       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1638     }
1639
1640     Asm->OutStreamer.AddComment("End Mark");
1641     Asm->EmitInt32(0);
1642     Asm->OutStreamer.EmitLabel(EndLabel);
1643   }
1644 }
1645
1646 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1647   const MCSection *PSec =
1648       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1649                : Asm->getObjFileLowering().getDwarfPubTypesSection();
1650
1651   emitDebugPubSection(GnuStyle, PSec, "Types",
1652                       &DwarfCompileUnit::getGlobalTypes);
1653 }
1654
1655 // Emit visible names into a debug str section.
1656 void DwarfDebug::emitDebugStr() {
1657   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1658   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1659 }
1660
1661 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
1662 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
1663                                const DITypeIdentifierMap &Map,
1664                                ArrayRef<DebugLocEntry::Value> Values) {
1665   assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1666         return P.isVariablePiece();
1667       }) && "all values are expected to be pieces");
1668   assert(std::is_sorted(Values.begin(), Values.end()) &&
1669          "pieces are expected to be sorted");
1670
1671   unsigned Offset = 0;
1672   for (auto Piece : Values) {
1673     const unsigned SizeOfByte = 8;
1674     DIExpression Expr = Piece.getExpression();
1675     unsigned PieceOffset = Expr.getPieceOffset();
1676     unsigned PieceSize = Expr.getPieceSize();
1677     assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1678     if (Offset < PieceOffset) {
1679       // The DWARF spec seriously mandates pieces with no locations for gaps.
1680       Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*SizeOfByte);
1681       Offset += PieceOffset-Offset;
1682     }
1683     Offset += PieceSize;
1684
1685 #ifndef NDEBUG
1686     DIVariable Var = Piece.getVariable();
1687     assert(!Var.isIndirect() && "indirect address for piece");
1688     unsigned VarSize = Var.getSizeInBits(Map);
1689     assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
1690            && "piece is larger than or outside of variable");
1691     assert(PieceSize*SizeOfByte != VarSize
1692            && "piece covers entire variable");
1693 #endif
1694
1695     emitDebugLocValue(Streamer, Piece, PieceOffset*SizeOfByte);
1696   }
1697 }
1698
1699
1700 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1701                                    const DebugLocEntry &Entry) {
1702   const DebugLocEntry::Value Value = Entry.getValues()[0];
1703   if (Value.isVariablePiece())
1704     // Emit all pieces that belong to the same variable and range.
1705     return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1706
1707   assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1708   emitDebugLocValue(Streamer, Value);
1709 }
1710
1711 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1712                                    const DebugLocEntry::Value &Value,
1713                                    unsigned PieceOffsetInBits) {
1714   DIVariable DV = Value.getVariable();
1715   DebugLocDwarfExpression DwarfExpr(*Asm, Streamer);
1716
1717   // Regular entry.
1718   if (Value.isInt()) {
1719     DIBasicType BTy(resolve(DV.getType()));
1720     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1721                          BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1722       DwarfExpr.AddSignedConstant(Value.getInt());
1723     else
1724       DwarfExpr.AddUnsignedConstant(Value.getInt());
1725   } else if (Value.isLocation()) {
1726     MachineLocation Loc = Value.getLoc();
1727     DIExpression Expr = Value.getExpression();
1728     if (!Expr || (Expr.getNumElements() == 0))
1729       // Regular entry.
1730       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1731     else {
1732       // Complex address entry.
1733       if (Loc.getOffset()) {
1734         DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1735         DwarfExpr.AddExpression(Expr, PieceOffsetInBits);
1736       } else
1737         DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1738                                           PieceOffsetInBits);
1739       if (DV.isIndirect())
1740         DwarfExpr.EmitOp(dwarf::DW_OP_deref);
1741     }
1742   }
1743   // else ... ignore constant fp. There is not any good way to
1744   // to represent them here in dwarf.
1745   // FIXME: ^
1746 }
1747
1748 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1749   Asm->OutStreamer.AddComment("Loc expr size");
1750   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1751   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1752   Asm->EmitLabelDifference(end, begin, 2);
1753   Asm->OutStreamer.EmitLabel(begin);
1754   // Emit the entry.
1755   APByteStreamer Streamer(*Asm);
1756   emitDebugLocEntry(Streamer, Entry);
1757   // Close the range.
1758   Asm->OutStreamer.EmitLabel(end);
1759 }
1760
1761 // Emit locations into the debug loc section.
1762 void DwarfDebug::emitDebugLoc() {
1763   // Start the dwarf loc section.
1764   Asm->OutStreamer.SwitchSection(
1765       Asm->getObjFileLowering().getDwarfLocSection());
1766   unsigned char Size = Asm->getDataLayout().getPointerSize();
1767   for (const auto &DebugLoc : DotDebugLocEntries) {
1768     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1769     const DwarfCompileUnit *CU = DebugLoc.CU;
1770     for (const auto &Entry : DebugLoc.List) {
1771       // Set up the range. This range is relative to the entry point of the
1772       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1773       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1774       if (auto *Base = CU->getBaseAddress()) {
1775         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1776         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1777       } else {
1778         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1779         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1780       }
1781
1782       emitDebugLocEntryLocation(Entry);
1783     }
1784     Asm->OutStreamer.EmitIntValue(0, Size);
1785     Asm->OutStreamer.EmitIntValue(0, Size);
1786   }
1787 }
1788
1789 void DwarfDebug::emitDebugLocDWO() {
1790   Asm->OutStreamer.SwitchSection(
1791       Asm->getObjFileLowering().getDwarfLocDWOSection());
1792   for (const auto &DebugLoc : DotDebugLocEntries) {
1793     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1794     for (const auto &Entry : DebugLoc.List) {
1795       // Just always use start_length for now - at least that's one address
1796       // rather than two. We could get fancier and try to, say, reuse an
1797       // address we know we've emitted elsewhere (the start of the function?
1798       // The start of the CU or CU subrange that encloses this range?)
1799       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1800       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1801       Asm->EmitULEB128(idx);
1802       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1803
1804       emitDebugLocEntryLocation(Entry);
1805     }
1806     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1807   }
1808 }
1809
1810 struct ArangeSpan {
1811   const MCSymbol *Start, *End;
1812 };
1813
1814 // Emit a debug aranges section, containing a CU lookup for any
1815 // address we can tie back to a CU.
1816 void DwarfDebug::emitDebugARanges() {
1817   // Start the dwarf aranges section.
1818   Asm->OutStreamer.SwitchSection(
1819       Asm->getObjFileLowering().getDwarfARangesSection());
1820
1821   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1822
1823   SpansType Spans;
1824
1825   // Build a list of sections used.
1826   std::vector<const MCSection *> Sections;
1827   for (const auto &it : SectionMap) {
1828     const MCSection *Section = it.first;
1829     Sections.push_back(Section);
1830   }
1831
1832   // Sort the sections into order.
1833   // This is only done to ensure consistent output order across different runs.
1834   std::sort(Sections.begin(), Sections.end(), SectionSort);
1835
1836   // Build a set of address spans, sorted by CU.
1837   for (const MCSection *Section : Sections) {
1838     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1839     if (List.size() < 2)
1840       continue;
1841
1842     // Sort the symbols by offset within the section.
1843     std::sort(List.begin(), List.end(),
1844               [&](const SymbolCU &A, const SymbolCU &B) {
1845       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1846       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1847
1848       // Symbols with no order assigned should be placed at the end.
1849       // (e.g. section end labels)
1850       if (IA == 0)
1851         return false;
1852       if (IB == 0)
1853         return true;
1854       return IA < IB;
1855     });
1856
1857     // If we have no section (e.g. common), just write out
1858     // individual spans for each symbol.
1859     if (!Section) {
1860       for (const SymbolCU &Cur : List) {
1861         ArangeSpan Span;
1862         Span.Start = Cur.Sym;
1863         Span.End = nullptr;
1864         if (Cur.CU)
1865           Spans[Cur.CU].push_back(Span);
1866       }
1867     } else {
1868       // Build spans between each label.
1869       const MCSymbol *StartSym = List[0].Sym;
1870       for (size_t n = 1, e = List.size(); n < e; n++) {
1871         const SymbolCU &Prev = List[n - 1];
1872         const SymbolCU &Cur = List[n];
1873
1874         // Try and build the longest span we can within the same CU.
1875         if (Cur.CU != Prev.CU) {
1876           ArangeSpan Span;
1877           Span.Start = StartSym;
1878           Span.End = Cur.Sym;
1879           Spans[Prev.CU].push_back(Span);
1880           StartSym = Cur.Sym;
1881         }
1882       }
1883     }
1884   }
1885
1886   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1887
1888   // Build a list of CUs used.
1889   std::vector<DwarfCompileUnit *> CUs;
1890   for (const auto &it : Spans) {
1891     DwarfCompileUnit *CU = it.first;
1892     CUs.push_back(CU);
1893   }
1894
1895   // Sort the CU list (again, to ensure consistent output order).
1896   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1897     return A->getUniqueID() < B->getUniqueID();
1898   });
1899
1900   // Emit an arange table for each CU we used.
1901   for (DwarfCompileUnit *CU : CUs) {
1902     std::vector<ArangeSpan> &List = Spans[CU];
1903
1904     // Describe the skeleton CU's offset and length, not the dwo file's.
1905     if (auto *Skel = CU->getSkeleton())
1906       CU = Skel;
1907
1908     // Emit size of content not including length itself.
1909     unsigned ContentSize =
1910         sizeof(int16_t) + // DWARF ARange version number
1911         sizeof(int32_t) + // Offset of CU in the .debug_info section
1912         sizeof(int8_t) +  // Pointer Size (in bytes)
1913         sizeof(int8_t);   // Segment Size (in bytes)
1914
1915     unsigned TupleSize = PtrSize * 2;
1916
1917     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1918     unsigned Padding =
1919         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1920
1921     ContentSize += Padding;
1922     ContentSize += (List.size() + 1) * TupleSize;
1923
1924     // For each compile unit, write the list of spans it covers.
1925     Asm->OutStreamer.AddComment("Length of ARange Set");
1926     Asm->EmitInt32(ContentSize);
1927     Asm->OutStreamer.AddComment("DWARF Arange version number");
1928     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1929     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1930     Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1931     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1932     Asm->EmitInt8(PtrSize);
1933     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1934     Asm->EmitInt8(0);
1935
1936     Asm->OutStreamer.EmitFill(Padding, 0xff);
1937
1938     for (const ArangeSpan &Span : List) {
1939       Asm->EmitLabelReference(Span.Start, PtrSize);
1940
1941       // Calculate the size as being from the span start to it's end.
1942       if (Span.End) {
1943         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1944       } else {
1945         // For symbols without an end marker (e.g. common), we
1946         // write a single arange entry containing just that one symbol.
1947         uint64_t Size = SymSize[Span.Start];
1948         if (Size == 0)
1949           Size = 1;
1950
1951         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1952       }
1953     }
1954
1955     Asm->OutStreamer.AddComment("ARange terminator");
1956     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1957     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1958   }
1959 }
1960
1961 // Emit visible names into a debug ranges section.
1962 void DwarfDebug::emitDebugRanges() {
1963   // Start the dwarf ranges section.
1964   Asm->OutStreamer.SwitchSection(
1965       Asm->getObjFileLowering().getDwarfRangesSection());
1966
1967   // Size for our labels.
1968   unsigned char Size = Asm->getDataLayout().getPointerSize();
1969
1970   // Grab the specific ranges for the compile units in the module.
1971   for (const auto &I : CUMap) {
1972     DwarfCompileUnit *TheCU = I.second;
1973
1974     if (auto *Skel = TheCU->getSkeleton())
1975       TheCU = Skel;
1976
1977     // Iterate over the misc ranges for the compile units in the module.
1978     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1979       // Emit our symbol so we can find the beginning of the range.
1980       Asm->OutStreamer.EmitLabel(List.getSym());
1981
1982       for (const RangeSpan &Range : List.getRanges()) {
1983         const MCSymbol *Begin = Range.getStart();
1984         const MCSymbol *End = Range.getEnd();
1985         assert(Begin && "Range without a begin symbol?");
1986         assert(End && "Range without an end symbol?");
1987         if (auto *Base = TheCU->getBaseAddress()) {
1988           Asm->EmitLabelDifference(Begin, Base, Size);
1989           Asm->EmitLabelDifference(End, Base, Size);
1990         } else {
1991           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
1992           Asm->OutStreamer.EmitSymbolValue(End, Size);
1993         }
1994       }
1995
1996       // And terminate the list with two 0 values.
1997       Asm->OutStreamer.EmitIntValue(0, Size);
1998       Asm->OutStreamer.EmitIntValue(0, Size);
1999     }
2000   }
2001 }
2002
2003 // DWARF5 Experimental Separate Dwarf emitters.
2004
2005 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2006                                   std::unique_ptr<DwarfUnit> NewU) {
2007   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2008                   U.getCUNode().getSplitDebugFilename());
2009
2010   if (!CompilationDir.empty())
2011     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2012
2013   addGnuPubAttributes(*NewU, Die);
2014
2015   SkeletonHolder.addUnit(std::move(NewU));
2016 }
2017
2018 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2019 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2020 // DW_AT_addr_base, DW_AT_ranges_base.
2021 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2022
2023   auto OwnedUnit = make_unique<DwarfCompileUnit>(
2024       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2025   DwarfCompileUnit &NewCU = *OwnedUnit;
2026   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2027                     DwarfInfoSectionSym);
2028
2029   NewCU.initStmtList(DwarfLineSectionSym);
2030
2031   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2032
2033   return NewCU;
2034 }
2035
2036 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2037 // compile units that would normally be in debug_info.
2038 void DwarfDebug::emitDebugInfoDWO() {
2039   assert(useSplitDwarf() && "No split dwarf debug info?");
2040   // Don't pass an abbrev symbol, using a constant zero instead so as not to
2041   // emit relocations into the dwo file.
2042   InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2043 }
2044
2045 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2046 // abbreviations for the .debug_info.dwo section.
2047 void DwarfDebug::emitDebugAbbrevDWO() {
2048   assert(useSplitDwarf() && "No split dwarf?");
2049   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2050 }
2051
2052 void DwarfDebug::emitDebugLineDWO() {
2053   assert(useSplitDwarf() && "No split dwarf?");
2054   Asm->OutStreamer.SwitchSection(
2055       Asm->getObjFileLowering().getDwarfLineDWOSection());
2056   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2057 }
2058
2059 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2060 // string section and is identical in format to traditional .debug_str
2061 // sections.
2062 void DwarfDebug::emitDebugStrDWO() {
2063   assert(useSplitDwarf() && "No split dwarf?");
2064   const MCSection *OffSec =
2065       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2066   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2067                          OffSec);
2068 }
2069
2070 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2071   if (!useSplitDwarf())
2072     return nullptr;
2073   if (SingleCU)
2074     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2075   return &SplitTypeUnitFileTable;
2076 }
2077
2078 static uint64_t makeTypeSignature(StringRef Identifier) {
2079   MD5 Hash;
2080   Hash.update(Identifier);
2081   // ... take the least significant 8 bytes and return those. Our MD5
2082   // implementation always returns its results in little endian, swap bytes
2083   // appropriately.
2084   MD5::MD5Result Result;
2085   Hash.final(Result);
2086   return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2087 }
2088
2089 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2090                                       StringRef Identifier, DIE &RefDie,
2091                                       DICompositeType CTy) {
2092   // Fast path if we're building some type units and one has already used the
2093   // address pool we know we're going to throw away all this work anyway, so
2094   // don't bother building dependent types.
2095   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2096     return;
2097
2098   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2099   if (TU) {
2100     CU.addDIETypeSignature(RefDie, *TU);
2101     return;
2102   }
2103
2104   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2105   AddrPool.resetUsedFlag();
2106
2107   auto OwnedUnit = make_unique<DwarfTypeUnit>(
2108       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2109       this, &InfoHolder, getDwoLineTable(CU));
2110   DwarfTypeUnit &NewTU = *OwnedUnit;
2111   DIE &UnitDie = NewTU.getUnitDie();
2112   TU = &NewTU;
2113   TypeUnitsUnderConstruction.push_back(
2114       std::make_pair(std::move(OwnedUnit), CTy));
2115
2116   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2117                 CU.getLanguage());
2118
2119   uint64_t Signature = makeTypeSignature(Identifier);
2120   NewTU.setTypeSignature(Signature);
2121
2122   if (useSplitDwarf())
2123     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2124   else {
2125     CU.applyStmtList(UnitDie);
2126     NewTU.initSection(
2127         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2128   }
2129
2130   NewTU.setType(NewTU.createTypeDIE(CTy));
2131
2132   if (TopLevelType) {
2133     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2134     TypeUnitsUnderConstruction.clear();
2135
2136     // Types referencing entries in the address table cannot be placed in type
2137     // units.
2138     if (AddrPool.hasBeenUsed()) {
2139
2140       // Remove all the types built while building this type.
2141       // This is pessimistic as some of these types might not be dependent on
2142       // the type that used an address.
2143       for (const auto &TU : TypeUnitsToAdd)
2144         DwarfTypeUnits.erase(TU.second);
2145
2146       // Construct this type in the CU directly.
2147       // This is inefficient because all the dependent types will be rebuilt
2148       // from scratch, including building them in type units, discovering that
2149       // they depend on addresses, throwing them out and rebuilding them.
2150       CU.constructTypeDIE(RefDie, CTy);
2151       return;
2152     }
2153
2154     // If the type wasn't dependent on fission addresses, finish adding the type
2155     // and all its dependent types.
2156     for (auto &TU : TypeUnitsToAdd)
2157       InfoHolder.addUnit(std::move(TU.first));
2158   }
2159   CU.addDIETypeSignature(RefDie, NewTU);
2160 }
2161
2162 // Accelerator table mutators - add each name along with its companion
2163 // DIE to the proper table while ensuring that the name that we're going
2164 // to reference is in the string table. We do this since the names we
2165 // add may not only be identical to the names in the DIE.
2166 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2167   if (!useDwarfAccelTables())
2168     return;
2169   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2170                      &Die);
2171 }
2172
2173 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2174   if (!useDwarfAccelTables())
2175     return;
2176   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2177                     &Die);
2178 }
2179
2180 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2181   if (!useDwarfAccelTables())
2182     return;
2183   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2184                          &Die);
2185 }
2186
2187 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2188   if (!useDwarfAccelTables())
2189     return;
2190   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2191                      &Die);
2192 }