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