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