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