cleanup.
[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     if (Piece.isLocation() && Piece.getLoc().isReg())
1695       Asm->EmitDwarfRegOpPiece(Streamer,
1696                                Piece.getLoc(),
1697                                PieceSize*SizeOfByte);
1698     else {
1699       emitDebugLocValue(Streamer, Piece);
1700       Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
1701     }
1702   }
1703 }
1704
1705
1706 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1707                                    const DebugLocEntry &Entry) {
1708   const DebugLocEntry::Value Value = Entry.getValues()[0];
1709   if (Value.isVariablePiece())
1710     // Emit all pieces that belong to the same variable and range.
1711     return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
1712
1713   assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
1714   emitDebugLocValue(Streamer, Value);
1715 }
1716
1717 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
1718                                    const DebugLocEntry::Value &Value) {
1719   DIVariable DV = Value.getVariable();
1720   DebugLocDwarfExpression Expr(*Asm, Streamer);
1721   // Regular entry.
1722   if (Value.isInt()) {
1723     DIBasicType BTy(resolve(DV.getType()));
1724     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
1725                          BTy.getEncoding() == dwarf::DW_ATE_signed_char))
1726       Expr.AddSignedConstant(Value.getInt());
1727     else
1728       Expr.AddUnsignedConstant(Value.getInt());
1729   } else if (Value.isLocation()) {
1730     MachineLocation Loc = Value.getLoc();
1731     DIExpression Expr = Value.getExpression();
1732     if (!Expr)
1733       // Regular entry.
1734       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1735     else {
1736       // Complex address entry.
1737       unsigned N = Expr.getNumElements();
1738       unsigned i = 0;
1739       if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
1740         if (Loc.getOffset()) {
1741           i = 2;
1742           Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1743           Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1744           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1745           Streamer.EmitSLEB128(Expr.getElement(1));
1746         } else {
1747           // If first address element is OpPlus then emit
1748           // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
1749           MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
1750           Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
1751           i = 2;
1752         }
1753       } else {
1754         Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
1755       }
1756
1757       // Emit remaining complex address elements.
1758       for (; i < N; ++i) {
1759         uint64_t Element = Expr.getElement(i);
1760         if (Element == dwarf::DW_OP_plus) {
1761           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
1762           Streamer.EmitULEB128(Expr.getElement(++i));
1763         } else if (Element == dwarf::DW_OP_deref) {
1764           if (!Loc.isReg())
1765             Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
1766         } else if (Element == dwarf::DW_OP_piece) {
1767           i += 3;
1768           // handled in emitDebugLocEntry.
1769         } else
1770           llvm_unreachable("unknown Opcode found in complex address");
1771       }
1772     }
1773   }
1774   // else ... ignore constant fp. There is not any good way to
1775   // to represent them here in dwarf.
1776   // FIXME: ^
1777 }
1778
1779 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
1780   Asm->OutStreamer.AddComment("Loc expr size");
1781   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
1782   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
1783   Asm->EmitLabelDifference(end, begin, 2);
1784   Asm->OutStreamer.EmitLabel(begin);
1785   // Emit the entry.
1786   APByteStreamer Streamer(*Asm);
1787   emitDebugLocEntry(Streamer, Entry);
1788   // Close the range.
1789   Asm->OutStreamer.EmitLabel(end);
1790 }
1791
1792 // Emit locations into the debug loc section.
1793 void DwarfDebug::emitDebugLoc() {
1794   // Start the dwarf loc section.
1795   Asm->OutStreamer.SwitchSection(
1796       Asm->getObjFileLowering().getDwarfLocSection());
1797   unsigned char Size = Asm->getDataLayout().getPointerSize();
1798   for (const auto &DebugLoc : DotDebugLocEntries) {
1799     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1800     const DwarfCompileUnit *CU = DebugLoc.CU;
1801     for (const auto &Entry : DebugLoc.List) {
1802       // Set up the range. This range is relative to the entry point of the
1803       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1804       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1805       if (auto *Base = CU->getBaseAddress()) {
1806         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
1807         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
1808       } else {
1809         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
1810         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
1811       }
1812
1813       emitDebugLocEntryLocation(Entry);
1814     }
1815     Asm->OutStreamer.EmitIntValue(0, Size);
1816     Asm->OutStreamer.EmitIntValue(0, Size);
1817   }
1818 }
1819
1820 void DwarfDebug::emitDebugLocDWO() {
1821   Asm->OutStreamer.SwitchSection(
1822       Asm->getObjFileLowering().getDwarfLocDWOSection());
1823   for (const auto &DebugLoc : DotDebugLocEntries) {
1824     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
1825     for (const auto &Entry : DebugLoc.List) {
1826       // Just always use start_length for now - at least that's one address
1827       // rather than two. We could get fancier and try to, say, reuse an
1828       // address we know we've emitted elsewhere (the start of the function?
1829       // The start of the CU or CU subrange that encloses this range?)
1830       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1831       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
1832       Asm->EmitULEB128(idx);
1833       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
1834
1835       emitDebugLocEntryLocation(Entry);
1836     }
1837     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1838   }
1839 }
1840
1841 struct ArangeSpan {
1842   const MCSymbol *Start, *End;
1843 };
1844
1845 // Emit a debug aranges section, containing a CU lookup for any
1846 // address we can tie back to a CU.
1847 void DwarfDebug::emitDebugARanges() {
1848   // Start the dwarf aranges section.
1849   Asm->OutStreamer.SwitchSection(
1850       Asm->getObjFileLowering().getDwarfARangesSection());
1851
1852   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
1853
1854   SpansType Spans;
1855
1856   // Build a list of sections used.
1857   std::vector<const MCSection *> Sections;
1858   for (const auto &it : SectionMap) {
1859     const MCSection *Section = it.first;
1860     Sections.push_back(Section);
1861   }
1862
1863   // Sort the sections into order.
1864   // This is only done to ensure consistent output order across different runs.
1865   std::sort(Sections.begin(), Sections.end(), SectionSort);
1866
1867   // Build a set of address spans, sorted by CU.
1868   for (const MCSection *Section : Sections) {
1869     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
1870     if (List.size() < 2)
1871       continue;
1872
1873     // Sort the symbols by offset within the section.
1874     std::sort(List.begin(), List.end(),
1875               [&](const SymbolCU &A, const SymbolCU &B) {
1876       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
1877       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
1878
1879       // Symbols with no order assigned should be placed at the end.
1880       // (e.g. section end labels)
1881       if (IA == 0)
1882         return false;
1883       if (IB == 0)
1884         return true;
1885       return IA < IB;
1886     });
1887
1888     // If we have no section (e.g. common), just write out
1889     // individual spans for each symbol.
1890     if (!Section) {
1891       for (const SymbolCU &Cur : List) {
1892         ArangeSpan Span;
1893         Span.Start = Cur.Sym;
1894         Span.End = nullptr;
1895         if (Cur.CU)
1896           Spans[Cur.CU].push_back(Span);
1897       }
1898     } else {
1899       // Build spans between each label.
1900       const MCSymbol *StartSym = List[0].Sym;
1901       for (size_t n = 1, e = List.size(); n < e; n++) {
1902         const SymbolCU &Prev = List[n - 1];
1903         const SymbolCU &Cur = List[n];
1904
1905         // Try and build the longest span we can within the same CU.
1906         if (Cur.CU != Prev.CU) {
1907           ArangeSpan Span;
1908           Span.Start = StartSym;
1909           Span.End = Cur.Sym;
1910           Spans[Prev.CU].push_back(Span);
1911           StartSym = Cur.Sym;
1912         }
1913       }
1914     }
1915   }
1916
1917   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1918
1919   // Build a list of CUs used.
1920   std::vector<DwarfCompileUnit *> CUs;
1921   for (const auto &it : Spans) {
1922     DwarfCompileUnit *CU = it.first;
1923     CUs.push_back(CU);
1924   }
1925
1926   // Sort the CU list (again, to ensure consistent output order).
1927   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
1928     return A->getUniqueID() < B->getUniqueID();
1929   });
1930
1931   // Emit an arange table for each CU we used.
1932   for (DwarfCompileUnit *CU : CUs) {
1933     std::vector<ArangeSpan> &List = Spans[CU];
1934
1935     // Describe the skeleton CU's offset and length, not the dwo file's.
1936     if (auto *Skel = CU->getSkeleton())
1937       CU = Skel;
1938
1939     // Emit size of content not including length itself.
1940     unsigned ContentSize =
1941         sizeof(int16_t) + // DWARF ARange version number
1942         sizeof(int32_t) + // Offset of CU in the .debug_info section
1943         sizeof(int8_t) +  // Pointer Size (in bytes)
1944         sizeof(int8_t);   // Segment Size (in bytes)
1945
1946     unsigned TupleSize = PtrSize * 2;
1947
1948     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1949     unsigned Padding =
1950         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1951
1952     ContentSize += Padding;
1953     ContentSize += (List.size() + 1) * TupleSize;
1954
1955     // For each compile unit, write the list of spans it covers.
1956     Asm->OutStreamer.AddComment("Length of ARange Set");
1957     Asm->EmitInt32(ContentSize);
1958     Asm->OutStreamer.AddComment("DWARF Arange version number");
1959     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1960     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
1961     Asm->EmitSectionOffset(CU->getLabelBegin(), CU->getSectionSym());
1962     Asm->OutStreamer.AddComment("Address Size (in bytes)");
1963     Asm->EmitInt8(PtrSize);
1964     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
1965     Asm->EmitInt8(0);
1966
1967     Asm->OutStreamer.EmitFill(Padding, 0xff);
1968
1969     for (const ArangeSpan &Span : List) {
1970       Asm->EmitLabelReference(Span.Start, PtrSize);
1971
1972       // Calculate the size as being from the span start to it's end.
1973       if (Span.End) {
1974         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1975       } else {
1976         // For symbols without an end marker (e.g. common), we
1977         // write a single arange entry containing just that one symbol.
1978         uint64_t Size = SymSize[Span.Start];
1979         if (Size == 0)
1980           Size = 1;
1981
1982         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
1983       }
1984     }
1985
1986     Asm->OutStreamer.AddComment("ARange terminator");
1987     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1988     Asm->OutStreamer.EmitIntValue(0, PtrSize);
1989   }
1990 }
1991
1992 // Emit visible names into a debug ranges section.
1993 void DwarfDebug::emitDebugRanges() {
1994   // Start the dwarf ranges section.
1995   Asm->OutStreamer.SwitchSection(
1996       Asm->getObjFileLowering().getDwarfRangesSection());
1997
1998   // Size for our labels.
1999   unsigned char Size = Asm->getDataLayout().getPointerSize();
2000
2001   // Grab the specific ranges for the compile units in the module.
2002   for (const auto &I : CUMap) {
2003     DwarfCompileUnit *TheCU = I.second;
2004
2005     if (auto *Skel = TheCU->getSkeleton())
2006       TheCU = Skel;
2007
2008     // Iterate over the misc ranges for the compile units in the module.
2009     for (const RangeSpanList &List : TheCU->getRangeLists()) {
2010       // Emit our symbol so we can find the beginning of the range.
2011       Asm->OutStreamer.EmitLabel(List.getSym());
2012
2013       for (const RangeSpan &Range : List.getRanges()) {
2014         const MCSymbol *Begin = Range.getStart();
2015         const MCSymbol *End = Range.getEnd();
2016         assert(Begin && "Range without a begin symbol?");
2017         assert(End && "Range without an end symbol?");
2018         if (auto *Base = TheCU->getBaseAddress()) {
2019           Asm->EmitLabelDifference(Begin, Base, Size);
2020           Asm->EmitLabelDifference(End, Base, Size);
2021         } else {
2022           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2023           Asm->OutStreamer.EmitSymbolValue(End, Size);
2024         }
2025       }
2026
2027       // And terminate the list with two 0 values.
2028       Asm->OutStreamer.EmitIntValue(0, Size);
2029       Asm->OutStreamer.EmitIntValue(0, Size);
2030     }
2031   }
2032 }
2033
2034 // DWARF5 Experimental Separate Dwarf emitters.
2035
2036 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2037                                   std::unique_ptr<DwarfUnit> NewU) {
2038   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2039                   U.getCUNode().getSplitDebugFilename());
2040
2041   if (!CompilationDir.empty())
2042     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2043
2044   addGnuPubAttributes(*NewU, Die);
2045
2046   SkeletonHolder.addUnit(std::move(NewU));
2047 }
2048
2049 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2050 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2051 // DW_AT_addr_base, DW_AT_ranges_base.
2052 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2053
2054   auto OwnedUnit = make_unique<DwarfCompileUnit>(
2055       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2056   DwarfCompileUnit &NewCU = *OwnedUnit;
2057   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2058                     DwarfInfoSectionSym);
2059
2060   NewCU.initStmtList(DwarfLineSectionSym);
2061
2062   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2063
2064   return NewCU;
2065 }
2066
2067 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2068 // compile units that would normally be in debug_info.
2069 void DwarfDebug::emitDebugInfoDWO() {
2070   assert(useSplitDwarf() && "No split dwarf debug info?");
2071   // Don't pass an abbrev symbol, using a constant zero instead so as not to
2072   // emit relocations into the dwo file.
2073   InfoHolder.emitUnits(/* AbbrevSymbol */ nullptr);
2074 }
2075
2076 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2077 // abbreviations for the .debug_info.dwo section.
2078 void DwarfDebug::emitDebugAbbrevDWO() {
2079   assert(useSplitDwarf() && "No split dwarf?");
2080   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2081 }
2082
2083 void DwarfDebug::emitDebugLineDWO() {
2084   assert(useSplitDwarf() && "No split dwarf?");
2085   Asm->OutStreamer.SwitchSection(
2086       Asm->getObjFileLowering().getDwarfLineDWOSection());
2087   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2088 }
2089
2090 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2091 // string section and is identical in format to traditional .debug_str
2092 // sections.
2093 void DwarfDebug::emitDebugStrDWO() {
2094   assert(useSplitDwarf() && "No split dwarf?");
2095   const MCSection *OffSec =
2096       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2097   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2098                          OffSec);
2099 }
2100
2101 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2102   if (!useSplitDwarf())
2103     return nullptr;
2104   if (SingleCU)
2105     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2106   return &SplitTypeUnitFileTable;
2107 }
2108
2109 static uint64_t makeTypeSignature(StringRef Identifier) {
2110   MD5 Hash;
2111   Hash.update(Identifier);
2112   // ... take the least significant 8 bytes and return those. Our MD5
2113   // implementation always returns its results in little endian, swap bytes
2114   // appropriately.
2115   MD5::MD5Result Result;
2116   Hash.final(Result);
2117   return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2118 }
2119
2120 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2121                                       StringRef Identifier, DIE &RefDie,
2122                                       DICompositeType CTy) {
2123   // Fast path if we're building some type units and one has already used the
2124   // address pool we know we're going to throw away all this work anyway, so
2125   // don't bother building dependent types.
2126   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2127     return;
2128
2129   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2130   if (TU) {
2131     CU.addDIETypeSignature(RefDie, *TU);
2132     return;
2133   }
2134
2135   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2136   AddrPool.resetUsedFlag();
2137
2138   auto OwnedUnit = make_unique<DwarfTypeUnit>(
2139       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2140       this, &InfoHolder, getDwoLineTable(CU));
2141   DwarfTypeUnit &NewTU = *OwnedUnit;
2142   DIE &UnitDie = NewTU.getUnitDie();
2143   TU = &NewTU;
2144   TypeUnitsUnderConstruction.push_back(
2145       std::make_pair(std::move(OwnedUnit), CTy));
2146
2147   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2148                 CU.getLanguage());
2149
2150   uint64_t Signature = makeTypeSignature(Identifier);
2151   NewTU.setTypeSignature(Signature);
2152
2153   if (useSplitDwarf())
2154     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2155   else {
2156     CU.applyStmtList(UnitDie);
2157     NewTU.initSection(
2158         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2159   }
2160
2161   NewTU.setType(NewTU.createTypeDIE(CTy));
2162
2163   if (TopLevelType) {
2164     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2165     TypeUnitsUnderConstruction.clear();
2166
2167     // Types referencing entries in the address table cannot be placed in type
2168     // units.
2169     if (AddrPool.hasBeenUsed()) {
2170
2171       // Remove all the types built while building this type.
2172       // This is pessimistic as some of these types might not be dependent on
2173       // the type that used an address.
2174       for (const auto &TU : TypeUnitsToAdd)
2175         DwarfTypeUnits.erase(TU.second);
2176
2177       // Construct this type in the CU directly.
2178       // This is inefficient because all the dependent types will be rebuilt
2179       // from scratch, including building them in type units, discovering that
2180       // they depend on addresses, throwing them out and rebuilding them.
2181       CU.constructTypeDIE(RefDie, CTy);
2182       return;
2183     }
2184
2185     // If the type wasn't dependent on fission addresses, finish adding the type
2186     // and all its dependent types.
2187     for (auto &TU : TypeUnitsToAdd)
2188       InfoHolder.addUnit(std::move(TU.first));
2189   }
2190   CU.addDIETypeSignature(RefDie, NewTU);
2191 }
2192
2193 // Accelerator table mutators - add each name along with its companion
2194 // DIE to the proper table while ensuring that the name that we're going
2195 // to reference is in the string table. We do this since the names we
2196 // add may not only be identical to the names in the DIE.
2197 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2198   if (!useDwarfAccelTables())
2199     return;
2200   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2201                      &Die);
2202 }
2203
2204 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2205   if (!useDwarfAccelTables())
2206     return;
2207   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2208                     &Die);
2209 }
2210
2211 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2212   if (!useDwarfAccelTables())
2213     return;
2214   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2215                          &Die);
2216 }
2217
2218 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2219   if (!useDwarfAccelTables())
2220     return;
2221   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2222                      &Die);
2223 }