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