1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for writing dwarf debug info into asm files.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "DwarfDebug.h"
14 #include "ByteStreamer.h"
15 #include "DIEHash.h"
16 #include "DebugLocEntry.h"
17 #include "DebugLocStream.h"
18 #include "DwarfCompileUnit.h"
19 #include "DwarfExpression.h"
20 #include "DwarfFile.h"
21 #include "DwarfUnit.h"
22 #include "llvm/ADT/APInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/DenseSet.h"
25 #include "llvm/ADT/MapVector.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringRef.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/CodeGen/AccelTable.h"
34 #include "llvm/CodeGen/AsmPrinter.h"
35 #include "llvm/CodeGen/DIE.h"
36 #include "llvm/CodeGen/LexicalScopes.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/TargetInstrInfo.h"
43 #include "llvm/CodeGen/TargetLowering.h"
44 #include "llvm/CodeGen/TargetRegisterInfo.h"
45 #include "llvm/CodeGen/TargetSubtargetInfo.h"
46 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
47 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
48 #include "llvm/IR/Constants.h"
49 #include "llvm/IR/DebugInfoMetadata.h"
50 #include "llvm/IR/DebugLoc.h"
51 #include "llvm/IR/Function.h"
52 #include "llvm/IR/GlobalVariable.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/MC/MCAsmInfo.h"
55 #include "llvm/MC/MCContext.h"
56 #include "llvm/MC/MCDwarf.h"
57 #include "llvm/MC/MCSection.h"
58 #include "llvm/MC/MCStreamer.h"
59 #include "llvm/MC/MCSymbol.h"
60 #include "llvm/MC/MCTargetOptions.h"
61 #include "llvm/MC/MachineLocation.h"
62 #include "llvm/MC/SectionKind.h"
63 #include "llvm/Pass.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/CommandLine.h"
66 #include "llvm/Support/Debug.h"
67 #include "llvm/Support/ErrorHandling.h"
68 #include "llvm/Support/MD5.h"
69 #include "llvm/Support/MathExtras.h"
70 #include "llvm/Support/Timer.h"
71 #include "llvm/Support/raw_ostream.h"
72 #include "llvm/Target/TargetLoweringObjectFile.h"
73 #include "llvm/Target/TargetMachine.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include <algorithm>
76 #include <cassert>
77 #include <cstddef>
78 #include <cstdint>
79 #include <iterator>
80 #include <string>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "dwarfdebug"
87 
88 STATISTIC(NumCSParams, "Number of dbg call site params created");
89 
90 static cl::opt<bool>
91 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
92                          cl::desc("Disable debug info printing"));
93 
94 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
95     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
96     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
97 
98 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
99                                            cl::Hidden,
100                                            cl::desc("Generate dwarf aranges"),
101                                            cl::init(false));
102 
103 static cl::opt<bool>
104     GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
105                            cl::desc("Generate DWARF4 type units."),
106                            cl::init(false));
107 
108 static cl::opt<bool> SplitDwarfCrossCuReferences(
109     "split-dwarf-cross-cu-references", cl::Hidden,
110     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
111 
112 enum DefaultOnOff { Default, Enable, Disable };
113 
114 static cl::opt<DefaultOnOff> UnknownLocations(
115     "use-unknown-locations", cl::Hidden,
116     cl::desc("Make an absence of debug location information explicit."),
117     cl::values(clEnumVal(Default, "At top of block or after label"),
118                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
119     cl::init(Default));
120 
121 static cl::opt<AccelTableKind> AccelTables(
122     "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
123     cl::values(clEnumValN(AccelTableKind::Default, "Default",
124                           "Default for platform"),
125                clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
126                clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
127                clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
128     cl::init(AccelTableKind::Default));
129 
130 static cl::opt<DefaultOnOff>
131 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
132                  cl::desc("Use inlined strings rather than string section."),
133                  cl::values(clEnumVal(Default, "Default for platform"),
134                             clEnumVal(Enable, "Enabled"),
135                             clEnumVal(Disable, "Disabled")),
136                  cl::init(Default));
137 
138 static cl::opt<bool>
139     NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
140                          cl::desc("Disable emission .debug_ranges section."),
141                          cl::init(false));
142 
143 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
144     "dwarf-sections-as-references", cl::Hidden,
145     cl::desc("Use sections+offset as references rather than labels."),
146     cl::values(clEnumVal(Default, "Default for platform"),
147                clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
148     cl::init(Default));
149 
150 enum LinkageNameOption {
151   DefaultLinkageNames,
152   AllLinkageNames,
153   AbstractLinkageNames
154 };
155 
156 static cl::opt<LinkageNameOption>
157     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
158                       cl::desc("Which DWARF linkage-name attributes to emit."),
159                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
160                                             "Default for platform"),
161                                  clEnumValN(AllLinkageNames, "All", "All"),
162                                  clEnumValN(AbstractLinkageNames, "Abstract",
163                                             "Abstract subprograms")),
164                       cl::init(DefaultLinkageNames));
165 
166 static const char *const DWARFGroupName = "dwarf";
167 static const char *const DWARFGroupDescription = "DWARF Emission";
168 static const char *const DbgTimerName = "writer";
169 static const char *const DbgTimerDescription = "DWARF Debug Writer";
170 static constexpr unsigned ULEB128PadSize = 4;
171 
172 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
173   getActiveStreamer().EmitInt8(
174       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
175                   : dwarf::OperationEncodingString(Op));
176 }
177 
178 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
179   getActiveStreamer().emitSLEB128(Value, Twine(Value));
180 }
181 
182 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
183   getActiveStreamer().emitULEB128(Value, Twine(Value));
184 }
185 
186 void DebugLocDwarfExpression::emitData1(uint8_t Value) {
187   getActiveStreamer().EmitInt8(Value, Twine(Value));
188 }
189 
190 void DebugLocDwarfExpression::emitBaseTypeRef(uint64_t Idx) {
191   assert(Idx < (1ULL << (ULEB128PadSize * 7)) && "Idx wont fit");
192   getActiveStreamer().emitULEB128(Idx, Twine(Idx), ULEB128PadSize);
193 }
194 
195 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
196                                               unsigned MachineReg) {
197   // This information is not available while emitting .debug_loc entries.
198   return false;
199 }
200 
201 void DebugLocDwarfExpression::enableTemporaryBuffer() {
202   assert(!IsBuffering && "Already buffering?");
203   if (!TmpBuf)
204     TmpBuf = std::make_unique<TempBuffer>(OutBS.GenerateComments);
205   IsBuffering = true;
206 }
207 
208 void DebugLocDwarfExpression::disableTemporaryBuffer() { IsBuffering = false; }
209 
210 unsigned DebugLocDwarfExpression::getTemporaryBufferSize() {
211   return TmpBuf ? TmpBuf->Bytes.size() : 0;
212 }
213 
214 void DebugLocDwarfExpression::commitTemporaryBuffer() {
215   if (!TmpBuf)
216     return;
217   for (auto Byte : enumerate(TmpBuf->Bytes)) {
218     const char *Comment = (Byte.index() < TmpBuf->Comments.size())
219                               ? TmpBuf->Comments[Byte.index()].c_str()
220                               : "";
221     OutBS.EmitInt8(Byte.value(), Comment);
222   }
223   TmpBuf->Bytes.clear();
224   TmpBuf->Comments.clear();
225 }
226 
227 const DIType *DbgVariable::getType() const {
228   return getVariable()->getType();
229 }
230 
231 /// Get .debug_loc entry for the instruction range starting at MI.
232 static DbgValueLoc getDebugLocValue(const MachineInstr *MI) {
233   const DIExpression *Expr = MI->getDebugExpression();
234   assert(MI->getNumOperands() == 4);
235   if (MI->getOperand(0).isReg()) {
236     auto RegOp = MI->getOperand(0);
237     auto Op1 = MI->getOperand(1);
238     // If the second operand is an immediate, this is a
239     // register-indirect address.
240     assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
241     MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
242     return DbgValueLoc(Expr, MLoc);
243   }
244   if (MI->getOperand(0).isTargetIndex()) {
245     auto Op = MI->getOperand(0);
246     return DbgValueLoc(Expr,
247                        TargetIndexLocation(Op.getIndex(), Op.getOffset()));
248   }
249   if (MI->getOperand(0).isImm())
250     return DbgValueLoc(Expr, MI->getOperand(0).getImm());
251   if (MI->getOperand(0).isFPImm())
252     return DbgValueLoc(Expr, MI->getOperand(0).getFPImm());
253   if (MI->getOperand(0).isCImm())
254     return DbgValueLoc(Expr, MI->getOperand(0).getCImm());
255 
256   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
257 }
258 
259 void DbgVariable::initializeDbgValue(const MachineInstr *DbgValue) {
260   assert(FrameIndexExprs.empty() && "Already initialized?");
261   assert(!ValueLoc.get() && "Already initialized?");
262 
263   assert(getVariable() == DbgValue->getDebugVariable() && "Wrong variable");
264   assert(getInlinedAt() == DbgValue->getDebugLoc()->getInlinedAt() &&
265          "Wrong inlined-at");
266 
267   ValueLoc = std::make_unique<DbgValueLoc>(getDebugLocValue(DbgValue));
268   if (auto *E = DbgValue->getDebugExpression())
269     if (E->getNumElements())
270       FrameIndexExprs.push_back({0, E});
271 }
272 
273 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
274   if (FrameIndexExprs.size() == 1)
275     return FrameIndexExprs;
276 
277   assert(llvm::all_of(FrameIndexExprs,
278                       [](const FrameIndexExpr &A) {
279                         return A.Expr->isFragment();
280                       }) &&
281          "multiple FI expressions without DW_OP_LLVM_fragment");
282   llvm::sort(FrameIndexExprs,
283              [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
284                return A.Expr->getFragmentInfo()->OffsetInBits <
285                       B.Expr->getFragmentInfo()->OffsetInBits;
286              });
287 
288   return FrameIndexExprs;
289 }
290 
291 void DbgVariable::addMMIEntry(const DbgVariable &V) {
292   assert(DebugLocListIndex == ~0U && !ValueLoc.get() && "not an MMI entry");
293   assert(V.DebugLocListIndex == ~0U && !V.ValueLoc.get() && "not an MMI entry");
294   assert(V.getVariable() == getVariable() && "conflicting variable");
295   assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
296 
297   assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
298   assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
299 
300   // FIXME: This logic should not be necessary anymore, as we now have proper
301   // deduplication. However, without it, we currently run into the assertion
302   // below, which means that we are likely dealing with broken input, i.e. two
303   // non-fragment entries for the same variable at different frame indices.
304   if (FrameIndexExprs.size()) {
305     auto *Expr = FrameIndexExprs.back().Expr;
306     if (!Expr || !Expr->isFragment())
307       return;
308   }
309 
310   for (const auto &FIE : V.FrameIndexExprs)
311     // Ignore duplicate entries.
312     if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
313           return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
314         }))
315       FrameIndexExprs.push_back(FIE);
316 
317   assert((FrameIndexExprs.size() == 1 ||
318           llvm::all_of(FrameIndexExprs,
319                        [](FrameIndexExpr &FIE) {
320                          return FIE.Expr && FIE.Expr->isFragment();
321                        })) &&
322          "conflicting locations for variable");
323 }
324 
325 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
326                                             bool GenerateTypeUnits,
327                                             DebuggerKind Tuning,
328                                             const Triple &TT) {
329   // Honor an explicit request.
330   if (AccelTables != AccelTableKind::Default)
331     return AccelTables;
332 
333   // Accelerator tables with type units are currently not supported.
334   if (GenerateTypeUnits)
335     return AccelTableKind::None;
336 
337   // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
338   // always implies debug_names. For lower standard versions we use apple
339   // accelerator tables on apple platforms and debug_names elsewhere.
340   if (DwarfVersion >= 5)
341     return AccelTableKind::Dwarf;
342   if (Tuning == DebuggerKind::LLDB)
343     return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
344                                    : AccelTableKind::Dwarf;
345   return AccelTableKind::None;
346 }
347 
348 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
349     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
350       InfoHolder(A, "info_string", DIEValueAllocator),
351       SkeletonHolder(A, "skel_string", DIEValueAllocator),
352       IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
353   const Triple &TT = Asm->TM.getTargetTriple();
354 
355   // Make sure we know our "debugger tuning".  The target option takes
356   // precedence; fall back to triple-based defaults.
357   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
358     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
359   else if (IsDarwin)
360     DebuggerTuning = DebuggerKind::LLDB;
361   else if (TT.isPS4CPU())
362     DebuggerTuning = DebuggerKind::SCE;
363   else
364     DebuggerTuning = DebuggerKind::GDB;
365 
366   if (DwarfInlinedStrings == Default)
367     UseInlineStrings = TT.isNVPTX();
368   else
369     UseInlineStrings = DwarfInlinedStrings == Enable;
370 
371   UseLocSection = !TT.isNVPTX();
372 
373   HasAppleExtensionAttributes = tuneForLLDB();
374 
375   // Handle split DWARF.
376   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
377 
378   // SCE defaults to linkage names only for abstract subprograms.
379   if (DwarfLinkageNames == DefaultLinkageNames)
380     UseAllLinkageNames = !tuneForSCE();
381   else
382     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
383 
384   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
385   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
386                                     : MMI->getModule()->getDwarfVersion();
387   // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
388   DwarfVersion =
389       TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
390 
391   UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
392 
393   // Use sections as references. Force for NVPTX.
394   if (DwarfSectionsAsReferences == Default)
395     UseSectionsAsReferences = TT.isNVPTX();
396   else
397     UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
398 
399   // Don't generate type units for unsupported object file formats.
400   GenerateTypeUnits =
401       A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
402 
403   TheAccelTableKind = computeAccelTableKind(
404       DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
405 
406   // Work around a GDB bug. GDB doesn't support the standard opcode;
407   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
408   // is defined as of DWARF 3.
409   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
410   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
411   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
412 
413   // GDB does not fully support the DWARF 4 representation for bitfields.
414   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
415 
416   // The DWARF v5 string offsets table has - possibly shared - contributions
417   // from each compile and type unit each preceded by a header. The string
418   // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
419   // a monolithic string offsets table without any header.
420   UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
421 
422   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
423 }
424 
425 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
426 DwarfDebug::~DwarfDebug() = default;
427 
428 static bool isObjCClass(StringRef Name) {
429   return Name.startswith("+") || Name.startswith("-");
430 }
431 
432 static bool hasObjCCategory(StringRef Name) {
433   if (!isObjCClass(Name))
434     return false;
435 
436   return Name.find(") ") != StringRef::npos;
437 }
438 
439 static void getObjCClassCategory(StringRef In, StringRef &Class,
440                                  StringRef &Category) {
441   if (!hasObjCCategory(In)) {
442     Class = In.slice(In.find('[') + 1, In.find(' '));
443     Category = "";
444     return;
445   }
446 
447   Class = In.slice(In.find('[') + 1, In.find('('));
448   Category = In.slice(In.find('[') + 1, In.find(' '));
449 }
450 
451 static StringRef getObjCMethodName(StringRef In) {
452   return In.slice(In.find(' ') + 1, In.find(']'));
453 }
454 
455 // Add the various names to the Dwarf accelerator table names.
456 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
457                                     const DISubprogram *SP, DIE &Die) {
458   if (getAccelTableKind() != AccelTableKind::Apple &&
459       CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
460     return;
461 
462   if (!SP->isDefinition())
463     return;
464 
465   if (SP->getName() != "")
466     addAccelName(CU, SP->getName(), Die);
467 
468   // If the linkage name is different than the name, go ahead and output that as
469   // well into the name table. Only do that if we are going to actually emit
470   // that name.
471   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
472       (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
473     addAccelName(CU, SP->getLinkageName(), Die);
474 
475   // If this is an Objective-C selector name add it to the ObjC accelerator
476   // too.
477   if (isObjCClass(SP->getName())) {
478     StringRef Class, Category;
479     getObjCClassCategory(SP->getName(), Class, Category);
480     addAccelObjC(CU, Class, Die);
481     if (Category != "")
482       addAccelObjC(CU, Category, Die);
483     // Also add the base method name to the name table.
484     addAccelName(CU, getObjCMethodName(SP->getName()), Die);
485   }
486 }
487 
488 /// Check whether we should create a DIE for the given Scope, return true
489 /// if we don't create a DIE (the corresponding DIE is null).
490 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
491   if (Scope->isAbstractScope())
492     return false;
493 
494   // We don't create a DIE if there is no Range.
495   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
496   if (Ranges.empty())
497     return true;
498 
499   if (Ranges.size() > 1)
500     return false;
501 
502   // We don't create a DIE if we have a single Range and the end label
503   // is null.
504   return !getLabelAfterInsn(Ranges.front().second);
505 }
506 
507 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
508   F(CU);
509   if (auto *SkelCU = CU.getSkeleton())
510     if (CU.getCUNode()->getSplitDebugInlining())
511       F(*SkelCU);
512 }
513 
514 bool DwarfDebug::shareAcrossDWOCUs() const {
515   return SplitDwarfCrossCuReferences;
516 }
517 
518 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
519                                                      LexicalScope *Scope) {
520   assert(Scope && Scope->getScopeNode());
521   assert(Scope->isAbstractScope());
522   assert(!Scope->getInlinedAt());
523 
524   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
525 
526   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
527   // was inlined from another compile unit.
528   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
529     // Avoid building the original CU if it won't be used
530     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
531   else {
532     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
533     if (auto *SkelCU = CU.getSkeleton()) {
534       (shareAcrossDWOCUs() ? CU : SrcCU)
535           .constructAbstractSubprogramScopeDIE(Scope);
536       if (CU.getCUNode()->getSplitDebugInlining())
537         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
538     } else
539       CU.constructAbstractSubprogramScopeDIE(Scope);
540   }
541 }
542 
543 DIE &DwarfDebug::constructSubprogramDefinitionDIE(const DISubprogram *SP) {
544   DICompileUnit *Unit = SP->getUnit();
545   assert(SP->isDefinition() && "Subprogram not a definition");
546   assert(Unit && "Subprogram definition without parent unit");
547   auto &CU = getOrCreateDwarfCompileUnit(Unit);
548   return *CU.getOrCreateSubprogramDIE(SP);
549 }
550 
551 /// Represents a parameter whose call site value can be described by applying a
552 /// debug expression to a register in the forwarded register worklist.
553 struct FwdRegParamInfo {
554   /// The described parameter register.
555   unsigned ParamReg;
556 
557   /// Debug expression that has been built up when walking through the
558   /// instruction chain that produces the parameter's value.
559   const DIExpression *Expr;
560 };
561 
562 /// Register worklist for finding call site values.
563 using FwdRegWorklist = MapVector<unsigned, SmallVector<FwdRegParamInfo, 2>>;
564 
565 /// Emit call site parameter entries that are described by the given value and
566 /// debug expression.
567 template <typename ValT>
568 static void finishCallSiteParams(ValT Val, const DIExpression *Expr,
569                                  ArrayRef<FwdRegParamInfo> DescribedParams,
570                                  ParamSet &Params) {
571   for (auto Param : DescribedParams) {
572     bool ShouldCombineExpressions = Expr && Param.Expr->getNumElements() > 0;
573 
574     // TODO: Entry value operations can currently not be combined with any
575     // other expressions, so we can't emit call site entries in those cases.
576     if (ShouldCombineExpressions && Expr->isEntryValue())
577       continue;
578 
579     // If a parameter's call site value is produced by a chain of
580     // instructions we may have already created an expression for the
581     // parameter when walking through the instructions. Append that to the
582     // base expression.
583     const DIExpression *CombinedExpr =
584         ShouldCombineExpressions
585             ? DIExpression::append(Expr, Param.Expr->getElements())
586             : Expr;
587     assert((!CombinedExpr || CombinedExpr->isValid()) &&
588            "Combined debug expression is invalid");
589 
590     DbgValueLoc DbgLocVal(CombinedExpr, Val);
591     DbgCallSiteParam CSParm(Param.ParamReg, DbgLocVal);
592     Params.push_back(CSParm);
593     ++NumCSParams;
594   }
595 }
596 
597 /// Add \p Reg to the worklist, if it's not already present, and mark that the
598 /// given parameter registers' values can (potentially) be described using
599 /// that register and an debug expression.
600 static void addToFwdRegWorklist(FwdRegWorklist &Worklist, unsigned Reg,
601                                 const DIExpression *Expr,
602                                 ArrayRef<FwdRegParamInfo> ParamsToAdd) {
603   auto I = Worklist.insert({Reg, {}});
604   auto &ParamsForFwdReg = I.first->second;
605   for (auto Param : ParamsToAdd) {
606     assert(none_of(ParamsForFwdReg,
607                    [Param](const FwdRegParamInfo &D) {
608                      return D.ParamReg == Param.ParamReg;
609                    }) &&
610            "Same parameter described twice by forwarding reg");
611 
612     // If a parameter's call site value is produced by a chain of
613     // instructions we may have already created an expression for the
614     // parameter when walking through the instructions. Append that to the
615     // new expression.
616     const DIExpression *CombinedExpr =
617         (Param.Expr->getNumElements() > 0)
618             ? DIExpression::append(Expr, Param.Expr->getElements())
619             : Expr;
620     assert(CombinedExpr->isValid() && "Combined debug expression is invalid");
621 
622     ParamsForFwdReg.push_back({Param.ParamReg, CombinedExpr});
623   }
624 }
625 
626 /// Try to interpret values loaded into registers that forward parameters
627 /// for \p CallMI. Store parameters with interpreted value into \p Params.
628 static void collectCallSiteParameters(const MachineInstr *CallMI,
629                                       ParamSet &Params) {
630   auto *MF = CallMI->getMF();
631   auto CalleesMap = MF->getCallSitesInfo();
632   auto CallFwdRegsInfo = CalleesMap.find(CallMI);
633 
634   // There is no information for the call instruction.
635   if (CallFwdRegsInfo == CalleesMap.end())
636     return;
637 
638   auto *MBB = CallMI->getParent();
639   const auto &TRI = MF->getSubtarget().getRegisterInfo();
640   const auto &TII = MF->getSubtarget().getInstrInfo();
641   const auto &TLI = MF->getSubtarget().getTargetLowering();
642 
643   // Skip the call instruction.
644   auto I = std::next(CallMI->getReverseIterator());
645 
646   FwdRegWorklist ForwardedRegWorklist;
647 
648   // If an instruction defines more than one item in the worklist, we may run
649   // into situations where a worklist register's value is (potentially)
650   // described by the previous value of another register that is also defined
651   // by that instruction.
652   //
653   // This can for example occur in cases like this:
654   //
655   //   $r1 = mov 123
656   //   $r0, $r1 = mvrr $r1, 456
657   //   call @foo, $r0, $r1
658   //
659   // When describing $r1's value for the mvrr instruction, we need to make sure
660   // that we don't finalize an entry value for $r0, as that is dependent on the
661   // previous value of $r1 (123 rather than 456).
662   //
663   // In order to not have to distinguish between those cases when finalizing
664   // entry values, we simply postpone adding new parameter registers to the
665   // worklist, by first keeping them in this temporary container until the
666   // instruction has been handled.
667   FwdRegWorklist NewWorklistItems;
668 
669   const DIExpression *EmptyExpr =
670       DIExpression::get(MF->getFunction().getContext(), {});
671 
672   // Add all the forwarding registers into the ForwardedRegWorklist.
673   for (auto ArgReg : CallFwdRegsInfo->second) {
674     bool InsertedReg =
675         ForwardedRegWorklist.insert({ArgReg.Reg, {{ArgReg.Reg, EmptyExpr}}})
676             .second;
677     assert(InsertedReg && "Single register used to forward two arguments?");
678     (void)InsertedReg;
679   }
680 
681   // We erase, from the ForwardedRegWorklist, those forwarding registers for
682   // which we successfully describe a loaded value (by using
683   // the describeLoadedValue()). For those remaining arguments in the working
684   // list, for which we do not describe a loaded value by
685   // the describeLoadedValue(), we try to generate an entry value expression
686   // for their call site value description, if the call is within the entry MBB.
687   // TODO: Handle situations when call site parameter value can be described
688   // as the entry value within basic blocks other than the first one.
689   bool ShouldTryEmitEntryVals = MBB->getIterator() == MF->begin();
690 
691   // If the MI is an instruction defining one or more parameters' forwarding
692   // registers, add those defines.
693   auto getForwardingRegsDefinedByMI = [&](const MachineInstr &MI,
694                                           SmallSetVector<unsigned, 4> &Defs) {
695     if (MI.isDebugInstr())
696       return;
697 
698     for (const MachineOperand &MO : MI.operands()) {
699       if (MO.isReg() && MO.isDef() &&
700           Register::isPhysicalRegister(MO.getReg())) {
701         for (auto FwdReg : ForwardedRegWorklist)
702           if (TRI->regsOverlap(FwdReg.first, MO.getReg()))
703             Defs.insert(FwdReg.first);
704       }
705     }
706   };
707 
708   // Search for a loading value in forwarding registers.
709   for (; I != MBB->rend(); ++I) {
710     // Skip bundle headers.
711     if (I->isBundle())
712       continue;
713 
714     // If the next instruction is a call we can not interpret parameter's
715     // forwarding registers or we finished the interpretation of all parameters.
716     if (I->isCall())
717       return;
718 
719     if (ForwardedRegWorklist.empty())
720       return;
721 
722     // Set of worklist registers that are defined by this instruction.
723     SmallSetVector<unsigned, 4> FwdRegDefs;
724 
725     getForwardingRegsDefinedByMI(*I, FwdRegDefs);
726     if (FwdRegDefs.empty())
727       continue;
728 
729     for (auto ParamFwdReg : FwdRegDefs) {
730       if (auto ParamValue = TII->describeLoadedValue(*I, ParamFwdReg)) {
731         if (ParamValue->first.isImm()) {
732           int64_t Val = ParamValue->first.getImm();
733           finishCallSiteParams(Val, ParamValue->second,
734                                ForwardedRegWorklist[ParamFwdReg], Params);
735         } else if (ParamValue->first.isReg()) {
736           Register RegLoc = ParamValue->first.getReg();
737           unsigned SP = TLI->getStackPointerRegisterToSaveRestore();
738           Register FP = TRI->getFrameRegister(*MF);
739           bool IsSPorFP = (RegLoc == SP) || (RegLoc == FP);
740           if (TRI->isCalleeSavedPhysReg(RegLoc, *MF) || IsSPorFP) {
741             MachineLocation MLoc(RegLoc, /*IsIndirect=*/IsSPorFP);
742             finishCallSiteParams(MLoc, ParamValue->second,
743                                  ForwardedRegWorklist[ParamFwdReg], Params);
744           } else {
745             // ParamFwdReg was described by the non-callee saved register
746             // RegLoc. Mark that the call site values for the parameters are
747             // dependent on that register instead of ParamFwdReg. Since RegLoc
748             // may be a register that will be handled in this iteration, we
749             // postpone adding the items to the worklist, and instead keep them
750             // in a temporary container.
751             addToFwdRegWorklist(NewWorklistItems, RegLoc, ParamValue->second,
752                                 ForwardedRegWorklist[ParamFwdReg]);
753           }
754         }
755       }
756     }
757 
758     // Remove all registers that this instruction defines from the worklist.
759     for (auto ParamFwdReg : FwdRegDefs)
760       ForwardedRegWorklist.erase(ParamFwdReg);
761 
762     // Now that we are done handling this instruction, add items from the
763     // temporary worklist to the real one.
764     for (auto New : NewWorklistItems)
765       addToFwdRegWorklist(ForwardedRegWorklist, New.first, EmptyExpr,
766                           New.second);
767     NewWorklistItems.clear();
768   }
769 
770   // Emit the call site parameter's value as an entry value.
771   if (ShouldTryEmitEntryVals) {
772     // Create an expression where the register's entry value is used.
773     DIExpression *EntryExpr = DIExpression::get(
774         MF->getFunction().getContext(), {dwarf::DW_OP_LLVM_entry_value, 1});
775     for (auto RegEntry : ForwardedRegWorklist) {
776       MachineLocation MLoc(RegEntry.first);
777       finishCallSiteParams(MLoc, EntryExpr, RegEntry.second, Params);
778     }
779   }
780 }
781 
782 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
783                                             DwarfCompileUnit &CU, DIE &ScopeDIE,
784                                             const MachineFunction &MF) {
785   // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
786   // the subprogram is required to have one.
787   if (!SP.areAllCallsDescribed() || !SP.isDefinition())
788     return;
789 
790   // Use DW_AT_call_all_calls to express that call site entries are present
791   // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
792   // because one of its requirements is not met: call site entries for
793   // optimized-out calls are elided.
794   CU.addFlag(ScopeDIE, CU.getDwarf5OrGNUAttr(dwarf::DW_AT_call_all_calls));
795 
796   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
797   assert(TII && "TargetInstrInfo not found: cannot label tail calls");
798 
799   // Emit call site entries for each call or tail call in the function.
800   for (const MachineBasicBlock &MBB : MF) {
801     for (const MachineInstr &MI : MBB.instrs()) {
802       // Bundles with call in them will pass the isCall() test below but do not
803       // have callee operand information so skip them here. Iterator will
804       // eventually reach the call MI.
805       if (MI.isBundle())
806         continue;
807 
808       // Skip instructions which aren't calls. Both calls and tail-calling jump
809       // instructions (e.g TAILJMPd64) are classified correctly here.
810       if (!MI.isCandidateForCallSiteEntry())
811         continue;
812 
813       // Skip instructions marked as frame setup, as they are not interesting to
814       // the user.
815       if (MI.getFlag(MachineInstr::FrameSetup))
816         continue;
817 
818       // TODO: Add support for targets with delay slots (see: beginInstruction).
819       if (MI.hasDelaySlot())
820         return;
821 
822       // If this is a direct call, find the callee's subprogram.
823       // In the case of an indirect call find the register that holds
824       // the callee.
825       const MachineOperand &CalleeOp = MI.getOperand(0);
826       if (!CalleeOp.isGlobal() && !CalleeOp.isReg())
827         continue;
828 
829       unsigned CallReg = 0;
830       DIE *CalleeDIE = nullptr;
831       const Function *CalleeDecl = nullptr;
832       if (CalleeOp.isReg()) {
833         CallReg = CalleeOp.getReg();
834         if (!CallReg)
835           continue;
836       } else {
837         CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
838         if (!CalleeDecl || !CalleeDecl->getSubprogram())
839           continue;
840         const DISubprogram *CalleeSP = CalleeDecl->getSubprogram();
841 
842         if (CalleeSP->isDefinition()) {
843           // Ensure that a subprogram DIE for the callee is available in the
844           // appropriate CU.
845           CalleeDIE = &constructSubprogramDefinitionDIE(CalleeSP);
846         } else {
847           // Create the declaration DIE if it is missing. This is required to
848           // support compilation of old bitcode with an incomplete list of
849           // retained metadata.
850           CalleeDIE = CU.getOrCreateSubprogramDIE(CalleeSP);
851         }
852         assert(CalleeDIE && "Must have a DIE for the callee");
853       }
854 
855       // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
856 
857       bool IsTail = TII->isTailCall(MI);
858 
859       // If MI is in a bundle, the label was created after the bundle since
860       // EmitFunctionBody iterates over top-level MIs. Get that top-level MI
861       // to search for that label below.
862       const MachineInstr *TopLevelCallMI =
863           MI.isInsideBundle() ? &*getBundleStart(MI.getIterator()) : &MI;
864 
865       // For tail calls, no return PC information is needed.
866       // For regular calls (and tail calls in GDB tuning), the return PC
867       // is needed to disambiguate paths in the call graph which could lead to
868       // some target function.
869       const MCSymbol *PCAddr =
870           (IsTail && !tuneForGDB())
871               ? nullptr
872               : const_cast<MCSymbol *>(getLabelAfterInsn(TopLevelCallMI));
873 
874       assert((IsTail || PCAddr) && "Call without return PC information");
875 
876       LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
877                         << (CalleeDecl ? CalleeDecl->getName()
878                                        : StringRef(MF.getSubtarget()
879                                                        .getRegisterInfo()
880                                                        ->getName(CallReg)))
881                         << (IsTail ? " [IsTail]" : "") << "\n");
882 
883       DIE &CallSiteDIE = CU.constructCallSiteEntryDIE(ScopeDIE, CalleeDIE,
884                                                       IsTail, PCAddr, CallReg);
885 
886       // GDB and LLDB support call site parameter debug info.
887       if (Asm->TM.Options.EnableDebugEntryValues &&
888           (tuneForGDB() || tuneForLLDB())) {
889         ParamSet Params;
890         // Try to interpret values of call site parameters.
891         collectCallSiteParameters(&MI, Params);
892         CU.constructCallSiteParmEntryDIEs(CallSiteDIE, Params);
893       }
894     }
895   }
896 }
897 
898 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
899   if (!U.hasDwarfPubSections())
900     return;
901 
902   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
903 }
904 
905 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
906                                       DwarfCompileUnit &NewCU) {
907   DIE &Die = NewCU.getUnitDie();
908   StringRef FN = DIUnit->getFilename();
909 
910   StringRef Producer = DIUnit->getProducer();
911   StringRef Flags = DIUnit->getFlags();
912   if (!Flags.empty() && !useAppleExtensionAttributes()) {
913     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
914     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
915   } else
916     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
917 
918   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
919                 DIUnit->getSourceLanguage());
920   NewCU.addString(Die, dwarf::DW_AT_name, FN);
921   StringRef SysRoot = DIUnit->getSysRoot();
922   if (!SysRoot.empty())
923     NewCU.addString(Die, dwarf::DW_AT_LLVM_sysroot, SysRoot);
924 
925   // Add DW_str_offsets_base to the unit DIE, except for split units.
926   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
927     NewCU.addStringOffsetsStart();
928 
929   if (!useSplitDwarf()) {
930     NewCU.initStmtList();
931 
932     // If we're using split dwarf the compilation dir is going to be in the
933     // skeleton CU and so we don't need to duplicate it here.
934     if (!CompilationDir.empty())
935       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
936     addGnuPubAttributes(NewCU, Die);
937   }
938 
939   if (useAppleExtensionAttributes()) {
940     if (DIUnit->isOptimized())
941       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
942 
943     StringRef Flags = DIUnit->getFlags();
944     if (!Flags.empty())
945       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
946 
947     if (unsigned RVer = DIUnit->getRuntimeVersion())
948       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
949                     dwarf::DW_FORM_data1, RVer);
950   }
951 
952   if (DIUnit->getDWOId()) {
953     // This CU is either a clang module DWO or a skeleton CU.
954     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
955                   DIUnit->getDWOId());
956     if (!DIUnit->getSplitDebugFilename().empty()) {
957       // This is a prefabricated skeleton CU.
958       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
959                                          ? dwarf::DW_AT_dwo_name
960                                          : dwarf::DW_AT_GNU_dwo_name;
961       NewCU.addString(Die, attrDWOName, DIUnit->getSplitDebugFilename());
962     }
963   }
964 }
965 // Create new DwarfCompileUnit for the given metadata node with tag
966 // DW_TAG_compile_unit.
967 DwarfCompileUnit &
968 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
969   if (auto *CU = CUMap.lookup(DIUnit))
970     return *CU;
971 
972   CompilationDir = DIUnit->getDirectory();
973 
974   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
975       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
976   DwarfCompileUnit &NewCU = *OwnedUnit;
977   InfoHolder.addUnit(std::move(OwnedUnit));
978 
979   for (auto *IE : DIUnit->getImportedEntities())
980     NewCU.addImportedEntity(IE);
981 
982   // LTO with assembly output shares a single line table amongst multiple CUs.
983   // To avoid the compilation directory being ambiguous, let the line table
984   // explicitly describe the directory of all files, never relying on the
985   // compilation directory.
986   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
987     Asm->OutStreamer->emitDwarfFile0Directive(
988         CompilationDir, DIUnit->getFilename(),
989         NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
990         NewCU.getUniqueID());
991 
992   if (useSplitDwarf()) {
993     NewCU.setSkeleton(constructSkeletonCU(NewCU));
994     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
995   } else {
996     finishUnitAttributes(DIUnit, NewCU);
997     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
998   }
999 
1000   CUMap.insert({DIUnit, &NewCU});
1001   CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
1002   return NewCU;
1003 }
1004 
1005 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
1006                                                   const DIImportedEntity *N) {
1007   if (isa<DILocalScope>(N->getScope()))
1008     return;
1009   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
1010     D->addChild(TheCU.constructImportedEntityDIE(N));
1011 }
1012 
1013 /// Sort and unique GVEs by comparing their fragment offset.
1014 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
1015 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
1016   llvm::sort(
1017       GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
1018         // Sort order: first null exprs, then exprs without fragment
1019         // info, then sort by fragment offset in bits.
1020         // FIXME: Come up with a more comprehensive comparator so
1021         // the sorting isn't non-deterministic, and so the following
1022         // std::unique call works correctly.
1023         if (!A.Expr || !B.Expr)
1024           return !!B.Expr;
1025         auto FragmentA = A.Expr->getFragmentInfo();
1026         auto FragmentB = B.Expr->getFragmentInfo();
1027         if (!FragmentA || !FragmentB)
1028           return !!FragmentB;
1029         return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1030       });
1031   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
1032                          [](DwarfCompileUnit::GlobalExpr A,
1033                             DwarfCompileUnit::GlobalExpr B) {
1034                            return A.Expr == B.Expr;
1035                          }),
1036              GVEs.end());
1037   return GVEs;
1038 }
1039 
1040 // Emit all Dwarf sections that should come prior to the content. Create
1041 // global DIEs and emit initial debug info sections. This is invoked by
1042 // the target AsmPrinter.
1043 void DwarfDebug::beginModule() {
1044   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
1045                      DWARFGroupDescription, TimePassesIsEnabled);
1046   if (DisableDebugInfoPrinting) {
1047     MMI->setDebugInfoAvailability(false);
1048     return;
1049   }
1050 
1051   const Module *M = MMI->getModule();
1052 
1053   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1054                                        M->debug_compile_units_end());
1055   // Tell MMI whether we have debug info.
1056   assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
1057          "DebugInfoAvailabilty initialized unexpectedly");
1058   SingleCU = NumDebugCUs == 1;
1059   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
1060       GVMap;
1061   for (const GlobalVariable &Global : M->globals()) {
1062     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1063     Global.getDebugInfo(GVs);
1064     for (auto *GVE : GVs)
1065       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1066   }
1067 
1068   // Create the symbol that designates the start of the unit's contribution
1069   // to the string offsets table. In a split DWARF scenario, only the skeleton
1070   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1071   if (useSegmentedStringOffsetsTable())
1072     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1073         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1074 
1075 
1076   // Create the symbols that designates the start of the DWARF v5 range list
1077   // and locations list tables. They are located past the table headers.
1078   if (getDwarfVersion() >= 5) {
1079     DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1080     Holder.setRnglistsTableBaseSym(
1081         Asm->createTempSymbol("rnglists_table_base"));
1082 
1083     if (useSplitDwarf())
1084       InfoHolder.setRnglistsTableBaseSym(
1085           Asm->createTempSymbol("rnglists_dwo_table_base"));
1086   }
1087 
1088   // Create the symbol that points to the first entry following the debug
1089   // address table (.debug_addr) header.
1090   AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1091   DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1092 
1093   for (DICompileUnit *CUNode : M->debug_compile_units()) {
1094     // FIXME: Move local imported entities into a list attached to the
1095     // subprogram, then this search won't be needed and a
1096     // getImportedEntities().empty() test should go below with the rest.
1097     bool HasNonLocalImportedEntities = llvm::any_of(
1098         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1099           return !isa<DILocalScope>(IE->getScope());
1100         });
1101 
1102     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1103         CUNode->getRetainedTypes().empty() &&
1104         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1105       continue;
1106 
1107     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1108 
1109     // Global Variables.
1110     for (auto *GVE : CUNode->getGlobalVariables()) {
1111       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1112       // already know about the variable and it isn't adding a constant
1113       // expression.
1114       auto &GVMapEntry = GVMap[GVE->getVariable()];
1115       auto *Expr = GVE->getExpression();
1116       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1117         GVMapEntry.push_back({nullptr, Expr});
1118     }
1119     DenseSet<DIGlobalVariable *> Processed;
1120     for (auto *GVE : CUNode->getGlobalVariables()) {
1121       DIGlobalVariable *GV = GVE->getVariable();
1122       if (Processed.insert(GV).second)
1123         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1124     }
1125 
1126     for (auto *Ty : CUNode->getEnumTypes()) {
1127       // The enum types array by design contains pointers to
1128       // MDNodes rather than DIRefs. Unique them here.
1129       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1130     }
1131     for (auto *Ty : CUNode->getRetainedTypes()) {
1132       // The retained types array by design contains pointers to
1133       // MDNodes rather than DIRefs. Unique them here.
1134       if (DIType *RT = dyn_cast<DIType>(Ty))
1135           // There is no point in force-emitting a forward declaration.
1136           CU.getOrCreateTypeDIE(RT);
1137     }
1138     // Emit imported_modules last so that the relevant context is already
1139     // available.
1140     for (auto *IE : CUNode->getImportedEntities())
1141       constructAndAddImportedEntityDIE(CU, IE);
1142   }
1143 }
1144 
1145 void DwarfDebug::finishEntityDefinitions() {
1146   for (const auto &Entity : ConcreteEntities) {
1147     DIE *Die = Entity->getDIE();
1148     assert(Die);
1149     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1150     // in the ConcreteEntities list, rather than looking it up again here.
1151     // DIE::getUnit isn't simple - it walks parent pointers, etc.
1152     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1153     assert(Unit);
1154     Unit->finishEntityDefinition(Entity.get());
1155   }
1156 }
1157 
1158 void DwarfDebug::finishSubprogramDefinitions() {
1159   for (const DISubprogram *SP : ProcessedSPNodes) {
1160     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1161     forBothCUs(
1162         getOrCreateDwarfCompileUnit(SP->getUnit()),
1163         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1164   }
1165 }
1166 
1167 void DwarfDebug::finalizeModuleInfo() {
1168   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1169 
1170   finishSubprogramDefinitions();
1171 
1172   finishEntityDefinitions();
1173 
1174   // Include the DWO file name in the hash if there's more than one CU.
1175   // This handles ThinLTO's situation where imported CUs may very easily be
1176   // duplicate with the same CU partially imported into another ThinLTO unit.
1177   StringRef DWOName;
1178   if (CUMap.size() > 1)
1179     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1180 
1181   // Handle anything that needs to be done on a per-unit basis after
1182   // all other generation.
1183   for (const auto &P : CUMap) {
1184     auto &TheCU = *P.second;
1185     if (TheCU.getCUNode()->isDebugDirectivesOnly())
1186       continue;
1187     // Emit DW_AT_containing_type attribute to connect types with their
1188     // vtable holding type.
1189     TheCU.constructContainingTypeDIEs();
1190 
1191     // Add CU specific attributes if we need to add any.
1192     // If we're splitting the dwarf out now that we've got the entire
1193     // CU then add the dwo id to it.
1194     auto *SkCU = TheCU.getSkeleton();
1195 
1196     bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1197 
1198     if (HasSplitUnit) {
1199       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1200                                          ? dwarf::DW_AT_dwo_name
1201                                          : dwarf::DW_AT_GNU_dwo_name;
1202       finishUnitAttributes(TheCU.getCUNode(), TheCU);
1203       TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1204                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1205       SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1206                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1207       // Emit a unique identifier for this CU.
1208       uint64_t ID =
1209           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
1210       if (getDwarfVersion() >= 5) {
1211         TheCU.setDWOId(ID);
1212         SkCU->setDWOId(ID);
1213       } else {
1214         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1215                       dwarf::DW_FORM_data8, ID);
1216         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1217                       dwarf::DW_FORM_data8, ID);
1218       }
1219 
1220       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1221         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1222         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1223                               Sym, Sym);
1224       }
1225     } else if (SkCU) {
1226       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1227     }
1228 
1229     // If we have code split among multiple sections or non-contiguous
1230     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1231     // remain in the .o file, otherwise add a DW_AT_low_pc.
1232     // FIXME: We should use ranges allow reordering of code ala
1233     // .subsections_via_symbols in mach-o. This would mean turning on
1234     // ranges for all subprogram DIEs for mach-o.
1235     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1236 
1237     if (unsigned NumRanges = TheCU.getRanges().size()) {
1238       if (NumRanges > 1 && useRangesSection())
1239         // A DW_AT_low_pc attribute may also be specified in combination with
1240         // DW_AT_ranges to specify the default base address for use in
1241         // location lists (see Section 2.6.2) and range lists (see Section
1242         // 2.17.3).
1243         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1244       else
1245         U.setBaseAddress(TheCU.getRanges().front().Begin);
1246       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1247     }
1248 
1249     // We don't keep track of which addresses are used in which CU so this
1250     // is a bit pessimistic under LTO.
1251     if ((!AddrPool.isEmpty() || TheCU.hasRangeLists()) &&
1252         (getDwarfVersion() >= 5 || HasSplitUnit))
1253       U.addAddrTableBase();
1254 
1255     if (getDwarfVersion() >= 5) {
1256       if (U.hasRangeLists())
1257         U.addRnglistsBase();
1258 
1259       if (!DebugLocs.getLists().empty()) {
1260         if (!useSplitDwarf())
1261           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1262                             DebugLocs.getSym(),
1263                             TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1264       }
1265     }
1266 
1267     auto *CUNode = cast<DICompileUnit>(P.first);
1268     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
1269     if (CUNode->getMacros()) {
1270       if (useSplitDwarf())
1271         TheCU.addSectionDelta(TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1272                             U.getMacroLabelBegin(),
1273                             TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1274       else
1275         U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1276                           U.getMacroLabelBegin(),
1277                           TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1278     }
1279   }
1280 
1281   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1282   for (auto *CUNode : MMI->getModule()->debug_compile_units())
1283     if (CUNode->getDWOId())
1284       getOrCreateDwarfCompileUnit(CUNode);
1285 
1286   // Compute DIE offsets and sizes.
1287   InfoHolder.computeSizeAndOffsets();
1288   if (useSplitDwarf())
1289     SkeletonHolder.computeSizeAndOffsets();
1290 }
1291 
1292 // Emit all Dwarf sections that should come after the content.
1293 void DwarfDebug::endModule() {
1294   assert(CurFn == nullptr);
1295   assert(CurMI == nullptr);
1296 
1297   for (const auto &P : CUMap) {
1298     auto &CU = *P.second;
1299     CU.createBaseTypeDIEs();
1300   }
1301 
1302   // If we aren't actually generating debug info (check beginModule -
1303   // conditionalized on !DisableDebugInfoPrinting and the presence of the
1304   // llvm.dbg.cu metadata node)
1305   if (!MMI->hasDebugInfo())
1306     return;
1307 
1308   // Finalize the debug info for the module.
1309   finalizeModuleInfo();
1310 
1311   if (useSplitDwarf())
1312     // Emit debug_loc.dwo/debug_loclists.dwo section.
1313     emitDebugLocDWO();
1314   else
1315     // Emit debug_loc/debug_loclists section.
1316     emitDebugLoc();
1317 
1318   // Corresponding abbreviations into a abbrev section.
1319   emitAbbreviations();
1320 
1321   // Emit all the DIEs into a debug info section.
1322   emitDebugInfo();
1323 
1324   // Emit info into a debug aranges section.
1325   if (GenerateARangeSection)
1326     emitDebugARanges();
1327 
1328   // Emit info into a debug ranges section.
1329   emitDebugRanges();
1330 
1331   if (useSplitDwarf())
1332   // Emit info into a debug macinfo.dwo section.
1333     emitDebugMacinfoDWO();
1334   else
1335   // Emit info into a debug macinfo section.
1336     emitDebugMacinfo();
1337 
1338   emitDebugStr();
1339 
1340   if (useSplitDwarf()) {
1341     emitDebugStrDWO();
1342     emitDebugInfoDWO();
1343     emitDebugAbbrevDWO();
1344     emitDebugLineDWO();
1345     emitDebugRangesDWO();
1346   }
1347 
1348   emitDebugAddr();
1349 
1350   // Emit info into the dwarf accelerator table sections.
1351   switch (getAccelTableKind()) {
1352   case AccelTableKind::Apple:
1353     emitAccelNames();
1354     emitAccelObjC();
1355     emitAccelNamespaces();
1356     emitAccelTypes();
1357     break;
1358   case AccelTableKind::Dwarf:
1359     emitAccelDebugNames();
1360     break;
1361   case AccelTableKind::None:
1362     break;
1363   case AccelTableKind::Default:
1364     llvm_unreachable("Default should have already been resolved.");
1365   }
1366 
1367   // Emit the pubnames and pubtypes sections if requested.
1368   emitDebugPubSections();
1369 
1370   // clean up.
1371   // FIXME: AbstractVariables.clear();
1372 }
1373 
1374 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1375                                                const DINode *Node,
1376                                                const MDNode *ScopeNode) {
1377   if (CU.getExistingAbstractEntity(Node))
1378     return;
1379 
1380   CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1381                                        cast<DILocalScope>(ScopeNode)));
1382 }
1383 
1384 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1385     const DINode *Node, const MDNode *ScopeNode) {
1386   if (CU.getExistingAbstractEntity(Node))
1387     return;
1388 
1389   if (LexicalScope *Scope =
1390           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1391     CU.createAbstractEntity(Node, Scope);
1392 }
1393 
1394 // Collect variable information from side table maintained by MF.
1395 void DwarfDebug::collectVariableInfoFromMFTable(
1396     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1397   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1398   LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1399   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1400     if (!VI.Var)
1401       continue;
1402     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1403            "Expected inlined-at fields to agree");
1404 
1405     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1406     Processed.insert(Var);
1407     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1408 
1409     // If variable scope is not found then skip this variable.
1410     if (!Scope) {
1411       LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1412                         << ", no variable scope found\n");
1413       continue;
1414     }
1415 
1416     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1417     auto RegVar = std::make_unique<DbgVariable>(
1418                     cast<DILocalVariable>(Var.first), Var.second);
1419     RegVar->initializeMMI(VI.Expr, VI.Slot);
1420     LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1421                       << "\n");
1422     if (DbgVariable *DbgVar = MFVars.lookup(Var))
1423       DbgVar->addMMIEntry(*RegVar);
1424     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1425       MFVars.insert({Var, RegVar.get()});
1426       ConcreteEntities.push_back(std::move(RegVar));
1427     }
1428   }
1429 }
1430 
1431 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1432 /// enclosing lexical scope. The check ensures there are no other instructions
1433 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1434 /// either open or otherwise rolls off the end of the scope.
1435 static bool validThroughout(LexicalScopes &LScopes,
1436                             const MachineInstr *DbgValue,
1437                             const MachineInstr *RangeEnd) {
1438   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1439   auto MBB = DbgValue->getParent();
1440   auto DL = DbgValue->getDebugLoc();
1441   auto *LScope = LScopes.findLexicalScope(DL);
1442   // Scope doesn't exist; this is a dead DBG_VALUE.
1443   if (!LScope)
1444     return false;
1445   auto &LSRange = LScope->getRanges();
1446   if (LSRange.size() == 0)
1447     return false;
1448 
1449   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1450   const MachineInstr *LScopeBegin = LSRange.front().first;
1451   // Early exit if the lexical scope begins outside of the current block.
1452   if (LScopeBegin->getParent() != MBB)
1453     return false;
1454   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1455   for (++Pred; Pred != MBB->rend(); ++Pred) {
1456     if (Pred->getFlag(MachineInstr::FrameSetup))
1457       break;
1458     auto PredDL = Pred->getDebugLoc();
1459     if (!PredDL || Pred->isMetaInstruction())
1460       continue;
1461     // Check whether the instruction preceding the DBG_VALUE is in the same
1462     // (sub)scope as the DBG_VALUE.
1463     if (DL->getScope() == PredDL->getScope())
1464       return false;
1465     auto *PredScope = LScopes.findLexicalScope(PredDL);
1466     if (!PredScope || LScope->dominates(PredScope))
1467       return false;
1468   }
1469 
1470   // If the range of the DBG_VALUE is open-ended, report success.
1471   if (!RangeEnd)
1472     return true;
1473 
1474   // Fail if there are instructions belonging to our scope in another block.
1475   const MachineInstr *LScopeEnd = LSRange.back().second;
1476   if (LScopeEnd->getParent() != MBB)
1477     return false;
1478 
1479   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1480   // throughout the function. This is a hack, presumably for DWARF v2 and not
1481   // necessarily correct. It would be much better to use a dbg.declare instead
1482   // if we know the constant is live throughout the scope.
1483   if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1484     return true;
1485 
1486   return false;
1487 }
1488 
1489 /// Build the location list for all DBG_VALUEs in the function that
1490 /// describe the same variable. The resulting DebugLocEntries will have
1491 /// strict monotonically increasing begin addresses and will never
1492 /// overlap. If the resulting list has only one entry that is valid
1493 /// throughout variable's scope return true.
1494 //
1495 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1496 // different kinds of history map entries. One thing to be aware of is that if
1497 // a debug value is ended by another entry (rather than being valid until the
1498 // end of the function), that entry's instruction may or may not be included in
1499 // the range, depending on if the entry is a clobbering entry (it has an
1500 // instruction that clobbers one or more preceding locations), or if it is an
1501 // (overlapping) debug value entry. This distinction can be seen in the example
1502 // below. The first debug value is ended by the clobbering entry 2, and the
1503 // second and third debug values are ended by the overlapping debug value entry
1504 // 4.
1505 //
1506 // Input:
1507 //
1508 //   History map entries [type, end index, mi]
1509 //
1510 // 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1511 // 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1512 // 2 | |    [Clobber, $reg0 = [...], -, -]
1513 // 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1514 // 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1515 //
1516 // Output [start, end) [Value...]:
1517 //
1518 // [0-1)    [(reg0, fragment 0, 32)]
1519 // [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1520 // [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1521 // [4-)     [(@g, fragment 0, 96)]
1522 bool DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1523                                    const DbgValueHistoryMap::Entries &Entries) {
1524   using OpenRange =
1525       std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1526   SmallVector<OpenRange, 4> OpenRanges;
1527   bool isSafeForSingleLocation = true;
1528   const MachineInstr *StartDebugMI = nullptr;
1529   const MachineInstr *EndMI = nullptr;
1530 
1531   for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1532     const MachineInstr *Instr = EI->getInstr();
1533 
1534     // Remove all values that are no longer live.
1535     size_t Index = std::distance(EB, EI);
1536     auto Last =
1537         remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1538     OpenRanges.erase(Last, OpenRanges.end());
1539 
1540     // If we are dealing with a clobbering entry, this iteration will result in
1541     // a location list entry starting after the clobbering instruction.
1542     const MCSymbol *StartLabel =
1543         EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1544     assert(StartLabel &&
1545            "Forgot label before/after instruction starting a range!");
1546 
1547     const MCSymbol *EndLabel;
1548     if (std::next(EI) == Entries.end()) {
1549       EndLabel = Asm->getFunctionEnd();
1550       if (EI->isClobber())
1551         EndMI = EI->getInstr();
1552     }
1553     else if (std::next(EI)->isClobber())
1554       EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1555     else
1556       EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1557     assert(EndLabel && "Forgot label after instruction ending a range!");
1558 
1559     if (EI->isDbgValue())
1560       LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1561 
1562     // If this history map entry has a debug value, add that to the list of
1563     // open ranges and check if its location is valid for a single value
1564     // location.
1565     if (EI->isDbgValue()) {
1566       // Do not add undef debug values, as they are redundant information in
1567       // the location list entries. An undef debug results in an empty location
1568       // description. If there are any non-undef fragments then padding pieces
1569       // with empty location descriptions will automatically be inserted, and if
1570       // all fragments are undef then the whole location list entry is
1571       // redundant.
1572       if (!Instr->isUndefDebugValue()) {
1573         auto Value = getDebugLocValue(Instr);
1574         OpenRanges.emplace_back(EI->getEndIndex(), Value);
1575 
1576         // TODO: Add support for single value fragment locations.
1577         if (Instr->getDebugExpression()->isFragment())
1578           isSafeForSingleLocation = false;
1579 
1580         if (!StartDebugMI)
1581           StartDebugMI = Instr;
1582       } else {
1583         isSafeForSingleLocation = false;
1584       }
1585     }
1586 
1587     // Location list entries with empty location descriptions are redundant
1588     // information in DWARF, so do not emit those.
1589     if (OpenRanges.empty())
1590       continue;
1591 
1592     // Omit entries with empty ranges as they do not have any effect in DWARF.
1593     if (StartLabel == EndLabel) {
1594       LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1595       continue;
1596     }
1597 
1598     SmallVector<DbgValueLoc, 4> Values;
1599     for (auto &R : OpenRanges)
1600       Values.push_back(R.second);
1601     DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1602 
1603     // Attempt to coalesce the ranges of two otherwise identical
1604     // DebugLocEntries.
1605     auto CurEntry = DebugLoc.rbegin();
1606     LLVM_DEBUG({
1607       dbgs() << CurEntry->getValues().size() << " Values:\n";
1608       for (auto &Value : CurEntry->getValues())
1609         Value.dump();
1610       dbgs() << "-----\n";
1611     });
1612 
1613     auto PrevEntry = std::next(CurEntry);
1614     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1615       DebugLoc.pop_back();
1616   }
1617 
1618   return DebugLoc.size() == 1 && isSafeForSingleLocation &&
1619          validThroughout(LScopes, StartDebugMI, EndMI);
1620 }
1621 
1622 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1623                                             LexicalScope &Scope,
1624                                             const DINode *Node,
1625                                             const DILocation *Location,
1626                                             const MCSymbol *Sym) {
1627   ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1628   if (isa<const DILocalVariable>(Node)) {
1629     ConcreteEntities.push_back(
1630         std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1631                                        Location));
1632     InfoHolder.addScopeVariable(&Scope,
1633         cast<DbgVariable>(ConcreteEntities.back().get()));
1634   } else if (isa<const DILabel>(Node)) {
1635     ConcreteEntities.push_back(
1636         std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1637                                     Location, Sym));
1638     InfoHolder.addScopeLabel(&Scope,
1639         cast<DbgLabel>(ConcreteEntities.back().get()));
1640   }
1641   return ConcreteEntities.back().get();
1642 }
1643 
1644 // Find variables for each lexical scope.
1645 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1646                                    const DISubprogram *SP,
1647                                    DenseSet<InlinedEntity> &Processed) {
1648   // Grab the variable info that was squirreled away in the MMI side-table.
1649   collectVariableInfoFromMFTable(TheCU, Processed);
1650 
1651   for (const auto &I : DbgValues) {
1652     InlinedEntity IV = I.first;
1653     if (Processed.count(IV))
1654       continue;
1655 
1656     // Instruction ranges, specifying where IV is accessible.
1657     const auto &HistoryMapEntries = I.second;
1658     if (HistoryMapEntries.empty())
1659       continue;
1660 
1661     LexicalScope *Scope = nullptr;
1662     const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1663     if (const DILocation *IA = IV.second)
1664       Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1665     else
1666       Scope = LScopes.findLexicalScope(LocalVar->getScope());
1667     // If variable scope is not found then skip this variable.
1668     if (!Scope)
1669       continue;
1670 
1671     Processed.insert(IV);
1672     DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1673                                             *Scope, LocalVar, IV.second));
1674 
1675     const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1676     assert(MInsn->isDebugValue() && "History must begin with debug value");
1677 
1678     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1679     // If the history map contains a single debug value, there may be an
1680     // additional entry which clobbers the debug value.
1681     size_t HistSize = HistoryMapEntries.size();
1682     bool SingleValueWithClobber =
1683         HistSize == 2 && HistoryMapEntries[1].isClobber();
1684     if (HistSize == 1 || SingleValueWithClobber) {
1685       const auto *End =
1686           SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1687       if (validThroughout(LScopes, MInsn, End)) {
1688         RegVar->initializeDbgValue(MInsn);
1689         continue;
1690       }
1691     }
1692 
1693     // Do not emit location lists if .debug_loc secton is disabled.
1694     if (!useLocSection())
1695       continue;
1696 
1697     // Handle multiple DBG_VALUE instructions describing one variable.
1698     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1699 
1700     // Build the location list for this variable.
1701     SmallVector<DebugLocEntry, 8> Entries;
1702     bool isValidSingleLocation = buildLocationList(Entries, HistoryMapEntries);
1703 
1704     // Check whether buildLocationList managed to merge all locations to one
1705     // that is valid throughout the variable's scope. If so, produce single
1706     // value location.
1707     if (isValidSingleLocation) {
1708       RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1709       continue;
1710     }
1711 
1712     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1713     // unique identifiers, so don't bother resolving the type with the
1714     // identifier map.
1715     const DIBasicType *BT = dyn_cast<DIBasicType>(
1716         static_cast<const Metadata *>(LocalVar->getType()));
1717 
1718     // Finalize the entry by lowering it into a DWARF bytestream.
1719     for (auto &Entry : Entries)
1720       Entry.finalize(*Asm, List, BT, TheCU);
1721   }
1722 
1723   // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1724   // DWARF-related DbgLabel.
1725   for (const auto &I : DbgLabels) {
1726     InlinedEntity IL = I.first;
1727     const MachineInstr *MI = I.second;
1728     if (MI == nullptr)
1729       continue;
1730 
1731     LexicalScope *Scope = nullptr;
1732     const DILabel *Label = cast<DILabel>(IL.first);
1733     // The scope could have an extra lexical block file.
1734     const DILocalScope *LocalScope =
1735         Label->getScope()->getNonLexicalBlockFileScope();
1736     // Get inlined DILocation if it is inlined label.
1737     if (const DILocation *IA = IL.second)
1738       Scope = LScopes.findInlinedScope(LocalScope, IA);
1739     else
1740       Scope = LScopes.findLexicalScope(LocalScope);
1741     // If label scope is not found then skip this label.
1742     if (!Scope)
1743       continue;
1744 
1745     Processed.insert(IL);
1746     /// At this point, the temporary label is created.
1747     /// Save the temporary label to DbgLabel entity to get the
1748     /// actually address when generating Dwarf DIE.
1749     MCSymbol *Sym = getLabelBeforeInsn(MI);
1750     createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1751   }
1752 
1753   // Collect info for variables/labels that were optimized out.
1754   for (const DINode *DN : SP->getRetainedNodes()) {
1755     if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1756       continue;
1757     LexicalScope *Scope = nullptr;
1758     if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1759       Scope = LScopes.findLexicalScope(DV->getScope());
1760     } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1761       Scope = LScopes.findLexicalScope(DL->getScope());
1762     }
1763 
1764     if (Scope)
1765       createConcreteEntity(TheCU, *Scope, DN, nullptr);
1766   }
1767 }
1768 
1769 // Process beginning of an instruction.
1770 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1771   DebugHandlerBase::beginInstruction(MI);
1772   assert(CurMI);
1773 
1774   const auto *SP = MI->getMF()->getFunction().getSubprogram();
1775   if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1776     return;
1777 
1778   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1779   // If the instruction is part of the function frame setup code, do not emit
1780   // any line record, as there is no correspondence with any user code.
1781   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1782     return;
1783   const DebugLoc &DL = MI->getDebugLoc();
1784   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1785   // the last line number actually emitted, to see if it was line 0.
1786   unsigned LastAsmLine =
1787       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1788 
1789   // Request a label after the call in order to emit AT_return_pc information
1790   // in call site entries. TODO: Add support for targets with delay slots.
1791   if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1792     requestLabelAfterInsn(MI);
1793 
1794   if (DL == PrevInstLoc) {
1795     // If we have an ongoing unspecified location, nothing to do here.
1796     if (!DL)
1797       return;
1798     // We have an explicit location, same as the previous location.
1799     // But we might be coming back to it after a line 0 record.
1800     if (LastAsmLine == 0 && DL.getLine() != 0) {
1801       // Reinstate the source location but not marked as a statement.
1802       const MDNode *Scope = DL.getScope();
1803       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1804     }
1805     return;
1806   }
1807 
1808   if (!DL) {
1809     // We have an unspecified location, which might want to be line 0.
1810     // If we have already emitted a line-0 record, don't repeat it.
1811     if (LastAsmLine == 0)
1812       return;
1813     // If user said Don't Do That, don't do that.
1814     if (UnknownLocations == Disable)
1815       return;
1816     // See if we have a reason to emit a line-0 record now.
1817     // Reasons to emit a line-0 record include:
1818     // - User asked for it (UnknownLocations).
1819     // - Instruction has a label, so it's referenced from somewhere else,
1820     //   possibly debug information; we want it to have a source location.
1821     // - Instruction is at the top of a block; we don't want to inherit the
1822     //   location from the physically previous (maybe unrelated) block.
1823     if (UnknownLocations == Enable || PrevLabel ||
1824         (PrevInstBB && PrevInstBB != MI->getParent())) {
1825       // Preserve the file and column numbers, if we can, to save space in
1826       // the encoded line table.
1827       // Do not update PrevInstLoc, it remembers the last non-0 line.
1828       const MDNode *Scope = nullptr;
1829       unsigned Column = 0;
1830       if (PrevInstLoc) {
1831         Scope = PrevInstLoc.getScope();
1832         Column = PrevInstLoc.getCol();
1833       }
1834       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1835     }
1836     return;
1837   }
1838 
1839   // We have an explicit location, different from the previous location.
1840   // Don't repeat a line-0 record, but otherwise emit the new location.
1841   // (The new location might be an explicit line 0, which we do emit.)
1842   if (DL.getLine() == 0 && LastAsmLine == 0)
1843     return;
1844   unsigned Flags = 0;
1845   if (DL == PrologEndLoc) {
1846     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1847     PrologEndLoc = DebugLoc();
1848   }
1849   // If the line changed, we call that a new statement; unless we went to
1850   // line 0 and came back, in which case it is not a new statement.
1851   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1852   if (DL.getLine() && DL.getLine() != OldLine)
1853     Flags |= DWARF2_FLAG_IS_STMT;
1854 
1855   const MDNode *Scope = DL.getScope();
1856   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1857 
1858   // If we're not at line 0, remember this location.
1859   if (DL.getLine())
1860     PrevInstLoc = DL;
1861 }
1862 
1863 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1864   // First known non-DBG_VALUE and non-frame setup location marks
1865   // the beginning of the function body.
1866   for (const auto &MBB : *MF)
1867     for (const auto &MI : MBB)
1868       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1869           MI.getDebugLoc())
1870         return MI.getDebugLoc();
1871   return DebugLoc();
1872 }
1873 
1874 /// Register a source line with debug info. Returns the  unique label that was
1875 /// emitted and which provides correspondence to the source line list.
1876 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
1877                              const MDNode *S, unsigned Flags, unsigned CUID,
1878                              uint16_t DwarfVersion,
1879                              ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
1880   StringRef Fn;
1881   unsigned FileNo = 1;
1882   unsigned Discriminator = 0;
1883   if (auto *Scope = cast_or_null<DIScope>(S)) {
1884     Fn = Scope->getFilename();
1885     if (Line != 0 && DwarfVersion >= 4)
1886       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1887         Discriminator = LBF->getDiscriminator();
1888 
1889     FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
1890                  .getOrCreateSourceID(Scope->getFile());
1891   }
1892   Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1893                                          Discriminator, Fn);
1894 }
1895 
1896 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
1897                                              unsigned CUID) {
1898   // Get beginning of function.
1899   if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
1900     // Ensure the compile unit is created if the function is called before
1901     // beginFunction().
1902     (void)getOrCreateDwarfCompileUnit(
1903         MF.getFunction().getSubprogram()->getUnit());
1904     // We'd like to list the prologue as "not statements" but GDB behaves
1905     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1906     const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1907     ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
1908                        CUID, getDwarfVersion(), getUnits());
1909     return PrologEndLoc;
1910   }
1911   return DebugLoc();
1912 }
1913 
1914 // Gather pre-function debug information.  Assumes being called immediately
1915 // after the function entry point has been emitted.
1916 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1917   CurFn = MF;
1918 
1919   auto *SP = MF->getFunction().getSubprogram();
1920   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1921   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1922     return;
1923 
1924   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1925 
1926   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1927   // belongs to so that we add to the correct per-cu line table in the
1928   // non-asm case.
1929   if (Asm->OutStreamer->hasRawTextSupport())
1930     // Use a single line table if we are generating assembly.
1931     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1932   else
1933     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1934 
1935   // Record beginning of function.
1936   PrologEndLoc = emitInitialLocDirective(
1937       *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
1938 }
1939 
1940 void DwarfDebug::skippedNonDebugFunction() {
1941   // If we don't have a subprogram for this function then there will be a hole
1942   // in the range information. Keep note of this by setting the previously used
1943   // section to nullptr.
1944   PrevCU = nullptr;
1945   CurFn = nullptr;
1946 }
1947 
1948 // Gather and emit post-function debug information.
1949 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1950   const DISubprogram *SP = MF->getFunction().getSubprogram();
1951 
1952   assert(CurFn == MF &&
1953       "endFunction should be called with the same function as beginFunction");
1954 
1955   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1956   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1957 
1958   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1959   assert(!FnScope || SP == FnScope->getScopeNode());
1960   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1961   if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1962     PrevLabel = nullptr;
1963     CurFn = nullptr;
1964     return;
1965   }
1966 
1967   DenseSet<InlinedEntity> Processed;
1968   collectEntityInfo(TheCU, SP, Processed);
1969 
1970   // Add the range of this function to the list of ranges for the CU.
1971   TheCU.addRange({Asm->getFunctionBegin(), Asm->getFunctionEnd()});
1972 
1973   // Under -gmlt, skip building the subprogram if there are no inlined
1974   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1975   // is still needed as we need its source location.
1976   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1977       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1978       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1979     assert(InfoHolder.getScopeVariables().empty());
1980     PrevLabel = nullptr;
1981     CurFn = nullptr;
1982     return;
1983   }
1984 
1985 #ifndef NDEBUG
1986   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1987 #endif
1988   // Construct abstract scopes.
1989   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1990     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1991     for (const DINode *DN : SP->getRetainedNodes()) {
1992       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1993         continue;
1994 
1995       const MDNode *Scope = nullptr;
1996       if (auto *DV = dyn_cast<DILocalVariable>(DN))
1997         Scope = DV->getScope();
1998       else if (auto *DL = dyn_cast<DILabel>(DN))
1999         Scope = DL->getScope();
2000       else
2001         llvm_unreachable("Unexpected DI type!");
2002 
2003       // Collect info for variables/labels that were optimized out.
2004       ensureAbstractEntityIsCreated(TheCU, DN, Scope);
2005       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
2006              && "ensureAbstractEntityIsCreated inserted abstract scopes");
2007     }
2008     constructAbstractSubprogramScopeDIE(TheCU, AScope);
2009   }
2010 
2011   ProcessedSPNodes.insert(SP);
2012   DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
2013   if (auto *SkelCU = TheCU.getSkeleton())
2014     if (!LScopes.getAbstractScopesList().empty() &&
2015         TheCU.getCUNode()->getSplitDebugInlining())
2016       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2017 
2018   // Construct call site entries.
2019   constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2020 
2021   // Clear debug info
2022   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2023   // DbgVariables except those that are also in AbstractVariables (since they
2024   // can be used cross-function)
2025   InfoHolder.getScopeVariables().clear();
2026   InfoHolder.getScopeLabels().clear();
2027   PrevLabel = nullptr;
2028   CurFn = nullptr;
2029 }
2030 
2031 // Register a source line with debug info. Returns the  unique label that was
2032 // emitted and which provides correspondence to the source line list.
2033 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2034                                   unsigned Flags) {
2035   ::recordSourceLine(*Asm, Line, Col, S, Flags,
2036                      Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2037                      getDwarfVersion(), getUnits());
2038 }
2039 
2040 //===----------------------------------------------------------------------===//
2041 // Emit Methods
2042 //===----------------------------------------------------------------------===//
2043 
2044 // Emit the debug info section.
2045 void DwarfDebug::emitDebugInfo() {
2046   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2047   Holder.emitUnits(/* UseOffsets */ false);
2048 }
2049 
2050 // Emit the abbreviation section.
2051 void DwarfDebug::emitAbbreviations() {
2052   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2053 
2054   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2055 }
2056 
2057 void DwarfDebug::emitStringOffsetsTableHeader() {
2058   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2059   Holder.getStringPool().emitStringOffsetsTableHeader(
2060       *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
2061       Holder.getStringOffsetsStartSym());
2062 }
2063 
2064 template <typename AccelTableT>
2065 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2066                            StringRef TableName) {
2067   Asm->OutStreamer->SwitchSection(Section);
2068 
2069   // Emit the full data.
2070   emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2071 }
2072 
2073 void DwarfDebug::emitAccelDebugNames() {
2074   // Don't emit anything if we have no compilation units to index.
2075   if (getUnits().empty())
2076     return;
2077 
2078   emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2079 }
2080 
2081 // Emit visible names into a hashed accelerator table section.
2082 void DwarfDebug::emitAccelNames() {
2083   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2084             "Names");
2085 }
2086 
2087 // Emit objective C classes and categories into a hashed accelerator table
2088 // section.
2089 void DwarfDebug::emitAccelObjC() {
2090   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2091             "ObjC");
2092 }
2093 
2094 // Emit namespace dies into a hashed accelerator table.
2095 void DwarfDebug::emitAccelNamespaces() {
2096   emitAccel(AccelNamespace,
2097             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
2098             "namespac");
2099 }
2100 
2101 // Emit type dies into a hashed accelerator table.
2102 void DwarfDebug::emitAccelTypes() {
2103   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2104             "types");
2105 }
2106 
2107 // Public name handling.
2108 // The format for the various pubnames:
2109 //
2110 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2111 // for the DIE that is named.
2112 //
2113 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2114 // into the CU and the index value is computed according to the type of value
2115 // for the DIE that is named.
2116 //
2117 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2118 // it's the offset within the debug_info/debug_types dwo section, however, the
2119 // reference in the pubname header doesn't change.
2120 
2121 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2122 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2123                                                         const DIE *Die) {
2124   // Entities that ended up only in a Type Unit reference the CU instead (since
2125   // the pub entry has offsets within the CU there's no real offset that can be
2126   // provided anyway). As it happens all such entities (namespaces and types,
2127   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2128   // not to be true it would be necessary to persist this information from the
2129   // point at which the entry is added to the index data structure - since by
2130   // the time the index is built from that, the original type/namespace DIE in a
2131   // type unit has already been destroyed so it can't be queried for properties
2132   // like tag, etc.
2133   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2134     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2135                                           dwarf::GIEL_EXTERNAL);
2136   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2137 
2138   // We could have a specification DIE that has our most of our knowledge,
2139   // look for that now.
2140   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2141     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2142     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2143       Linkage = dwarf::GIEL_EXTERNAL;
2144   } else if (Die->findAttribute(dwarf::DW_AT_external))
2145     Linkage = dwarf::GIEL_EXTERNAL;
2146 
2147   switch (Die->getTag()) {
2148   case dwarf::DW_TAG_class_type:
2149   case dwarf::DW_TAG_structure_type:
2150   case dwarf::DW_TAG_union_type:
2151   case dwarf::DW_TAG_enumeration_type:
2152     return dwarf::PubIndexEntryDescriptor(
2153         dwarf::GIEK_TYPE,
2154         dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
2155             ? dwarf::GIEL_EXTERNAL
2156             : dwarf::GIEL_STATIC);
2157   case dwarf::DW_TAG_typedef:
2158   case dwarf::DW_TAG_base_type:
2159   case dwarf::DW_TAG_subrange_type:
2160     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2161   case dwarf::DW_TAG_namespace:
2162     return dwarf::GIEK_TYPE;
2163   case dwarf::DW_TAG_subprogram:
2164     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2165   case dwarf::DW_TAG_variable:
2166     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2167   case dwarf::DW_TAG_enumerator:
2168     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2169                                           dwarf::GIEL_STATIC);
2170   default:
2171     return dwarf::GIEK_NONE;
2172   }
2173 }
2174 
2175 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2176 /// pubtypes sections.
2177 void DwarfDebug::emitDebugPubSections() {
2178   for (const auto &NU : CUMap) {
2179     DwarfCompileUnit *TheU = NU.second;
2180     if (!TheU->hasDwarfPubSections())
2181       continue;
2182 
2183     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2184                     DICompileUnit::DebugNameTableKind::GNU;
2185 
2186     Asm->OutStreamer->SwitchSection(
2187         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2188                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
2189     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2190 
2191     Asm->OutStreamer->SwitchSection(
2192         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2193                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
2194     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2195   }
2196 }
2197 
2198 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2199   if (useSectionsAsReferences())
2200     Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2201                          CU.getDebugSectionOffset());
2202   else
2203     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2204 }
2205 
2206 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2207                                      DwarfCompileUnit *TheU,
2208                                      const StringMap<const DIE *> &Globals) {
2209   if (auto *Skeleton = TheU->getSkeleton())
2210     TheU = Skeleton;
2211 
2212   // Emit the header.
2213   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
2214   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
2215   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
2216   Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
2217 
2218   Asm->OutStreamer->emitLabel(BeginLabel);
2219 
2220   Asm->OutStreamer->AddComment("DWARF Version");
2221   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2222 
2223   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2224   emitSectionReference(*TheU);
2225 
2226   Asm->OutStreamer->AddComment("Compilation Unit Length");
2227   Asm->emitInt32(TheU->getLength());
2228 
2229   // Emit the pubnames for this compilation unit.
2230   for (const auto &GI : Globals) {
2231     const char *Name = GI.getKeyData();
2232     const DIE *Entity = GI.second;
2233 
2234     Asm->OutStreamer->AddComment("DIE offset");
2235     Asm->emitInt32(Entity->getOffset());
2236 
2237     if (GnuStyle) {
2238       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2239       Asm->OutStreamer->AddComment(
2240           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2241           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2242       Asm->emitInt8(Desc.toBits());
2243     }
2244 
2245     Asm->OutStreamer->AddComment("External Name");
2246     Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
2247   }
2248 
2249   Asm->OutStreamer->AddComment("End Mark");
2250   Asm->emitInt32(0);
2251   Asm->OutStreamer->emitLabel(EndLabel);
2252 }
2253 
2254 /// Emit null-terminated strings into a debug str section.
2255 void DwarfDebug::emitDebugStr() {
2256   MCSection *StringOffsetsSection = nullptr;
2257   if (useSegmentedStringOffsetsTable()) {
2258     emitStringOffsetsTableHeader();
2259     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2260   }
2261   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2262   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2263                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
2264 }
2265 
2266 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2267                                    const DebugLocStream::Entry &Entry,
2268                                    const DwarfCompileUnit *CU) {
2269   auto &&Comments = DebugLocs.getComments(Entry);
2270   auto Comment = Comments.begin();
2271   auto End = Comments.end();
2272 
2273   // The expressions are inserted into a byte stream rather early (see
2274   // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2275   // need to reference a base_type DIE the offset of that DIE is not yet known.
2276   // To deal with this we instead insert a placeholder early and then extract
2277   // it here and replace it with the real reference.
2278   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2279   DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2280                                     DebugLocs.getBytes(Entry).size()),
2281                           Asm->getDataLayout().isLittleEndian(), PtrSize);
2282   DWARFExpression Expr(Data, PtrSize);
2283 
2284   using Encoding = DWARFExpression::Operation::Encoding;
2285   uint64_t Offset = 0;
2286   for (auto &Op : Expr) {
2287     assert(Op.getCode() != dwarf::DW_OP_const_type &&
2288            "3 operand ops not yet supported");
2289     Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2290     Offset++;
2291     for (unsigned I = 0; I < 2; ++I) {
2292       if (Op.getDescription().Op[I] == Encoding::SizeNA)
2293         continue;
2294       if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2295         uint64_t Offset =
2296             CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
2297         assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
2298         Streamer.emitULEB128(Offset, "", ULEB128PadSize);
2299         // Make sure comments stay aligned.
2300         for (unsigned J = 0; J < ULEB128PadSize; ++J)
2301           if (Comment != End)
2302             Comment++;
2303       } else {
2304         for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2305           Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2306       }
2307       Offset = Op.getOperandEndOffset(I);
2308     }
2309     assert(Offset == Op.getEndOffset());
2310   }
2311 }
2312 
2313 void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2314                                    const DbgValueLoc &Value,
2315                                    DwarfExpression &DwarfExpr) {
2316   auto *DIExpr = Value.getExpression();
2317   DIExpressionCursor ExprCursor(DIExpr);
2318   DwarfExpr.addFragmentOffset(DIExpr);
2319   // Regular entry.
2320   if (Value.isInt()) {
2321     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2322                BT->getEncoding() == dwarf::DW_ATE_signed_char))
2323       DwarfExpr.addSignedConstant(Value.getInt());
2324     else
2325       DwarfExpr.addUnsignedConstant(Value.getInt());
2326   } else if (Value.isLocation()) {
2327     MachineLocation Location = Value.getLoc();
2328     if (Location.isIndirect())
2329       DwarfExpr.setMemoryLocationKind();
2330     DIExpressionCursor Cursor(DIExpr);
2331 
2332     if (DIExpr->isEntryValue()) {
2333       DwarfExpr.setEntryValueFlag();
2334       DwarfExpr.beginEntryValueExpression(Cursor);
2335     }
2336 
2337     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
2338     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
2339       return;
2340     return DwarfExpr.addExpression(std::move(Cursor));
2341   } else if (Value.isTargetIndexLocation()) {
2342     TargetIndexLocation Loc = Value.getTargetIndexLocation();
2343     // TODO TargetIndexLocation is a target-independent. Currently only the WebAssembly-specific
2344     // encoding is supported.
2345     DwarfExpr.addWasmLocation(Loc.Index, Loc.Offset);
2346   } else if (Value.isConstantFP()) {
2347     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
2348     DwarfExpr.addUnsignedConstant(RawBytes);
2349   }
2350   DwarfExpr.addExpression(std::move(ExprCursor));
2351 }
2352 
2353 void DebugLocEntry::finalize(const AsmPrinter &AP,
2354                              DebugLocStream::ListBuilder &List,
2355                              const DIBasicType *BT,
2356                              DwarfCompileUnit &TheCU) {
2357   assert(!Values.empty() &&
2358          "location list entries without values are redundant");
2359   assert(Begin != End && "unexpected location list entry with empty range");
2360   DebugLocStream::EntryBuilder Entry(List, Begin, End);
2361   BufferByteStreamer Streamer = Entry.getStreamer();
2362   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2363   const DbgValueLoc &Value = Values[0];
2364   if (Value.isFragment()) {
2365     // Emit all fragments that belong to the same variable and range.
2366     assert(llvm::all_of(Values, [](DbgValueLoc P) {
2367           return P.isFragment();
2368         }) && "all values are expected to be fragments");
2369     assert(std::is_sorted(Values.begin(), Values.end()) &&
2370            "fragments are expected to be sorted");
2371 
2372     for (auto Fragment : Values)
2373       DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2374 
2375   } else {
2376     assert(Values.size() == 1 && "only fragments may have >1 value");
2377     DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2378   }
2379   DwarfExpr.finalize();
2380   if (DwarfExpr.TagOffset)
2381     List.setTagOffset(*DwarfExpr.TagOffset);
2382 }
2383 
2384 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2385                                            const DwarfCompileUnit *CU) {
2386   // Emit the size.
2387   Asm->OutStreamer->AddComment("Loc expr size");
2388   if (getDwarfVersion() >= 5)
2389     Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2390   else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2391     Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2392   else {
2393     // The entry is too big to fit into 16 bit, drop it as there is nothing we
2394     // can do.
2395     Asm->emitInt16(0);
2396     return;
2397   }
2398   // Emit the entry.
2399   APByteStreamer Streamer(*Asm);
2400   emitDebugLocEntry(Streamer, Entry, CU);
2401 }
2402 
2403 // Emit the common part of the DWARF 5 range/locations list tables header.
2404 static void emitListsTableHeaderStart(AsmPrinter *Asm,
2405                                       MCSymbol *TableStart,
2406                                       MCSymbol *TableEnd) {
2407   // Build the table header, which starts with the length field.
2408   Asm->OutStreamer->AddComment("Length");
2409   Asm->emitLabelDifference(TableEnd, TableStart, 4);
2410   Asm->OutStreamer->emitLabel(TableStart);
2411   // Version number (DWARF v5 and later).
2412   Asm->OutStreamer->AddComment("Version");
2413   Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
2414   // Address size.
2415   Asm->OutStreamer->AddComment("Address size");
2416   Asm->emitInt8(Asm->MAI->getCodePointerSize());
2417   // Segment selector size.
2418   Asm->OutStreamer->AddComment("Segment selector size");
2419   Asm->emitInt8(0);
2420 }
2421 
2422 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2423 // that designates the end of the table for the caller to emit when the table is
2424 // complete.
2425 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2426                                          const DwarfFile &Holder) {
2427   MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
2428   MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
2429   emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2430 
2431   Asm->OutStreamer->AddComment("Offset entry count");
2432   Asm->emitInt32(Holder.getRangeLists().size());
2433   Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2434 
2435   for (const RangeSpanList &List : Holder.getRangeLists())
2436     Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(), 4);
2437 
2438   return TableEnd;
2439 }
2440 
2441 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2442 // designates the end of the table for the caller to emit when the table is
2443 // complete.
2444 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2445                                          const DwarfDebug &DD) {
2446   MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2447   MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2448   emitListsTableHeaderStart(Asm, TableStart, TableEnd);
2449 
2450   const auto &DebugLocs = DD.getDebugLocs();
2451 
2452   Asm->OutStreamer->AddComment("Offset entry count");
2453   Asm->emitInt32(DebugLocs.getLists().size());
2454   Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2455 
2456   for (const auto &List : DebugLocs.getLists())
2457     Asm->emitLabelDifference(List.Label, DebugLocs.getSym(), 4);
2458 
2459   return TableEnd;
2460 }
2461 
2462 template <typename Ranges, typename PayloadEmitter>
2463 static void emitRangeList(
2464     DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2465     const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2466     unsigned StartxLength, unsigned EndOfList,
2467     StringRef (*StringifyEnum)(unsigned),
2468     bool ShouldUseBaseAddress,
2469     PayloadEmitter EmitPayload) {
2470 
2471   auto Size = Asm->MAI->getCodePointerSize();
2472   bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2473 
2474   // Emit our symbol so we can find the beginning of the range.
2475   Asm->OutStreamer->emitLabel(Sym);
2476 
2477   // Gather all the ranges that apply to the same section so they can share
2478   // a base address entry.
2479   MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2480 
2481   for (const auto &Range : R)
2482     SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2483 
2484   const MCSymbol *CUBase = CU.getBaseAddress();
2485   bool BaseIsSet = false;
2486   for (const auto &P : SectionRanges) {
2487     auto *Base = CUBase;
2488     if (!Base && ShouldUseBaseAddress) {
2489       const MCSymbol *Begin = P.second.front()->Begin;
2490       const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2491       if (!UseDwarf5) {
2492         Base = NewBase;
2493         BaseIsSet = true;
2494         Asm->OutStreamer->emitIntValue(-1, Size);
2495         Asm->OutStreamer->AddComment("  base address");
2496         Asm->OutStreamer->emitSymbolValue(Base, Size);
2497       } else if (NewBase != Begin || P.second.size() > 1) {
2498         // Only use a base address if
2499         //  * the existing pool address doesn't match (NewBase != Begin)
2500         //  * or, there's more than one entry to share the base address
2501         Base = NewBase;
2502         BaseIsSet = true;
2503         Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2504         Asm->emitInt8(BaseAddressx);
2505         Asm->OutStreamer->AddComment("  base address index");
2506         Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
2507       }
2508     } else if (BaseIsSet && !UseDwarf5) {
2509       BaseIsSet = false;
2510       assert(!Base);
2511       Asm->OutStreamer->emitIntValue(-1, Size);
2512       Asm->OutStreamer->emitIntValue(0, Size);
2513     }
2514 
2515     for (const auto *RS : P.second) {
2516       const MCSymbol *Begin = RS->Begin;
2517       const MCSymbol *End = RS->End;
2518       assert(Begin && "Range without a begin symbol?");
2519       assert(End && "Range without an end symbol?");
2520       if (Base) {
2521         if (UseDwarf5) {
2522           // Emit offset_pair when we have a base.
2523           Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2524           Asm->emitInt8(OffsetPair);
2525           Asm->OutStreamer->AddComment("  starting offset");
2526           Asm->emitLabelDifferenceAsULEB128(Begin, Base);
2527           Asm->OutStreamer->AddComment("  ending offset");
2528           Asm->emitLabelDifferenceAsULEB128(End, Base);
2529         } else {
2530           Asm->emitLabelDifference(Begin, Base, Size);
2531           Asm->emitLabelDifference(End, Base, Size);
2532         }
2533       } else if (UseDwarf5) {
2534         Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2535         Asm->emitInt8(StartxLength);
2536         Asm->OutStreamer->AddComment("  start index");
2537         Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
2538         Asm->OutStreamer->AddComment("  length");
2539         Asm->emitLabelDifferenceAsULEB128(End, Begin);
2540       } else {
2541         Asm->OutStreamer->emitSymbolValue(Begin, Size);
2542         Asm->OutStreamer->emitSymbolValue(End, Size);
2543       }
2544       EmitPayload(*RS);
2545     }
2546   }
2547 
2548   if (UseDwarf5) {
2549     Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2550     Asm->emitInt8(EndOfList);
2551   } else {
2552     // Terminate the list with two 0 values.
2553     Asm->OutStreamer->emitIntValue(0, Size);
2554     Asm->OutStreamer->emitIntValue(0, Size);
2555   }
2556 }
2557 
2558 // Handles emission of both debug_loclist / debug_loclist.dwo
2559 static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2560   emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2561                 *List.CU, dwarf::DW_LLE_base_addressx,
2562                 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2563                 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2564                 /* ShouldUseBaseAddress */ true,
2565                 [&](const DebugLocStream::Entry &E) {
2566                   DD.emitDebugLocEntryLocation(E, List.CU);
2567                 });
2568 }
2569 
2570 void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2571   if (DebugLocs.getLists().empty())
2572     return;
2573 
2574   Asm->OutStreamer->SwitchSection(Sec);
2575 
2576   MCSymbol *TableEnd = nullptr;
2577   if (getDwarfVersion() >= 5)
2578     TableEnd = emitLoclistsTableHeader(Asm, *this);
2579 
2580   for (const auto &List : DebugLocs.getLists())
2581     emitLocList(*this, Asm, List);
2582 
2583   if (TableEnd)
2584     Asm->OutStreamer->emitLabel(TableEnd);
2585 }
2586 
2587 // Emit locations into the .debug_loc/.debug_loclists section.
2588 void DwarfDebug::emitDebugLoc() {
2589   emitDebugLocImpl(
2590       getDwarfVersion() >= 5
2591           ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2592           : Asm->getObjFileLowering().getDwarfLocSection());
2593 }
2594 
2595 // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2596 void DwarfDebug::emitDebugLocDWO() {
2597   if (getDwarfVersion() >= 5) {
2598     emitDebugLocImpl(
2599         Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2600 
2601     return;
2602   }
2603 
2604   for (const auto &List : DebugLocs.getLists()) {
2605     Asm->OutStreamer->SwitchSection(
2606         Asm->getObjFileLowering().getDwarfLocDWOSection());
2607     Asm->OutStreamer->emitLabel(List.Label);
2608 
2609     for (const auto &Entry : DebugLocs.getEntries(List)) {
2610       // GDB only supports startx_length in pre-standard split-DWARF.
2611       // (in v5 standard loclists, it currently* /only/ supports base_address +
2612       // offset_pair, so the implementations can't really share much since they
2613       // need to use different representations)
2614       // * as of October 2018, at least
2615       //
2616       // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2617       // addresses in the address pool to minimize object size/relocations.
2618       Asm->emitInt8(dwarf::DW_LLE_startx_length);
2619       unsigned idx = AddrPool.getIndex(Entry.Begin);
2620       Asm->emitULEB128(idx);
2621       // Also the pre-standard encoding is slightly different, emitting this as
2622       // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2623       Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2624       emitDebugLocEntryLocation(Entry, List.CU);
2625     }
2626     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2627   }
2628 }
2629 
2630 struct ArangeSpan {
2631   const MCSymbol *Start, *End;
2632 };
2633 
2634 // Emit a debug aranges section, containing a CU lookup for any
2635 // address we can tie back to a CU.
2636 void DwarfDebug::emitDebugARanges() {
2637   // Provides a unique id per text section.
2638   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2639 
2640   // Filter labels by section.
2641   for (const SymbolCU &SCU : ArangeLabels) {
2642     if (SCU.Sym->isInSection()) {
2643       // Make a note of this symbol and it's section.
2644       MCSection *Section = &SCU.Sym->getSection();
2645       if (!Section->getKind().isMetadata())
2646         SectionMap[Section].push_back(SCU);
2647     } else {
2648       // Some symbols (e.g. common/bss on mach-o) can have no section but still
2649       // appear in the output. This sucks as we rely on sections to build
2650       // arange spans. We can do it without, but it's icky.
2651       SectionMap[nullptr].push_back(SCU);
2652     }
2653   }
2654 
2655   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2656 
2657   for (auto &I : SectionMap) {
2658     MCSection *Section = I.first;
2659     SmallVector<SymbolCU, 8> &List = I.second;
2660     if (List.size() < 1)
2661       continue;
2662 
2663     // If we have no section (e.g. common), just write out
2664     // individual spans for each symbol.
2665     if (!Section) {
2666       for (const SymbolCU &Cur : List) {
2667         ArangeSpan Span;
2668         Span.Start = Cur.Sym;
2669         Span.End = nullptr;
2670         assert(Cur.CU);
2671         Spans[Cur.CU].push_back(Span);
2672       }
2673       continue;
2674     }
2675 
2676     // Sort the symbols by offset within the section.
2677     llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2678       unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2679       unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2680 
2681       // Symbols with no order assigned should be placed at the end.
2682       // (e.g. section end labels)
2683       if (IA == 0)
2684         return false;
2685       if (IB == 0)
2686         return true;
2687       return IA < IB;
2688     });
2689 
2690     // Insert a final terminator.
2691     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2692 
2693     // Build spans between each label.
2694     const MCSymbol *StartSym = List[0].Sym;
2695     for (size_t n = 1, e = List.size(); n < e; n++) {
2696       const SymbolCU &Prev = List[n - 1];
2697       const SymbolCU &Cur = List[n];
2698 
2699       // Try and build the longest span we can within the same CU.
2700       if (Cur.CU != Prev.CU) {
2701         ArangeSpan Span;
2702         Span.Start = StartSym;
2703         Span.End = Cur.Sym;
2704         assert(Prev.CU);
2705         Spans[Prev.CU].push_back(Span);
2706         StartSym = Cur.Sym;
2707       }
2708     }
2709   }
2710 
2711   // Start the dwarf aranges section.
2712   Asm->OutStreamer->SwitchSection(
2713       Asm->getObjFileLowering().getDwarfARangesSection());
2714 
2715   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2716 
2717   // Build a list of CUs used.
2718   std::vector<DwarfCompileUnit *> CUs;
2719   for (const auto &it : Spans) {
2720     DwarfCompileUnit *CU = it.first;
2721     CUs.push_back(CU);
2722   }
2723 
2724   // Sort the CU list (again, to ensure consistent output order).
2725   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2726     return A->getUniqueID() < B->getUniqueID();
2727   });
2728 
2729   // Emit an arange table for each CU we used.
2730   for (DwarfCompileUnit *CU : CUs) {
2731     std::vector<ArangeSpan> &List = Spans[CU];
2732 
2733     // Describe the skeleton CU's offset and length, not the dwo file's.
2734     if (auto *Skel = CU->getSkeleton())
2735       CU = Skel;
2736 
2737     // Emit size of content not including length itself.
2738     unsigned ContentSize =
2739         sizeof(int16_t) + // DWARF ARange version number
2740         sizeof(int32_t) + // Offset of CU in the .debug_info section
2741         sizeof(int8_t) +  // Pointer Size (in bytes)
2742         sizeof(int8_t);   // Segment Size (in bytes)
2743 
2744     unsigned TupleSize = PtrSize * 2;
2745 
2746     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2747     unsigned Padding =
2748         offsetToAlignment(sizeof(int32_t) + ContentSize, Align(TupleSize));
2749 
2750     ContentSize += Padding;
2751     ContentSize += (List.size() + 1) * TupleSize;
2752 
2753     // For each compile unit, write the list of spans it covers.
2754     Asm->OutStreamer->AddComment("Length of ARange Set");
2755     Asm->emitInt32(ContentSize);
2756     Asm->OutStreamer->AddComment("DWARF Arange version number");
2757     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2758     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2759     emitSectionReference(*CU);
2760     Asm->OutStreamer->AddComment("Address Size (in bytes)");
2761     Asm->emitInt8(PtrSize);
2762     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2763     Asm->emitInt8(0);
2764 
2765     Asm->OutStreamer->emitFill(Padding, 0xff);
2766 
2767     for (const ArangeSpan &Span : List) {
2768       Asm->emitLabelReference(Span.Start, PtrSize);
2769 
2770       // Calculate the size as being from the span start to it's end.
2771       if (Span.End) {
2772         Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
2773       } else {
2774         // For symbols without an end marker (e.g. common), we
2775         // write a single arange entry containing just that one symbol.
2776         uint64_t Size = SymSize[Span.Start];
2777         if (Size == 0)
2778           Size = 1;
2779 
2780         Asm->OutStreamer->emitIntValue(Size, PtrSize);
2781       }
2782     }
2783 
2784     Asm->OutStreamer->AddComment("ARange terminator");
2785     Asm->OutStreamer->emitIntValue(0, PtrSize);
2786     Asm->OutStreamer->emitIntValue(0, PtrSize);
2787   }
2788 }
2789 
2790 /// Emit a single range list. We handle both DWARF v5 and earlier.
2791 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2792                           const RangeSpanList &List) {
2793   emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
2794                 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
2795                 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
2796                 llvm::dwarf::RangeListEncodingString,
2797                 List.CU->getCUNode()->getRangesBaseAddress() ||
2798                     DD.getDwarfVersion() >= 5,
2799                 [](auto) {});
2800 }
2801 
2802 void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
2803   if (Holder.getRangeLists().empty())
2804     return;
2805 
2806   assert(useRangesSection());
2807   assert(!CUMap.empty());
2808   assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2809     return !Pair.second->getCUNode()->isDebugDirectivesOnly();
2810   }));
2811 
2812   Asm->OutStreamer->SwitchSection(Section);
2813 
2814   MCSymbol *TableEnd = nullptr;
2815   if (getDwarfVersion() >= 5)
2816     TableEnd = emitRnglistsTableHeader(Asm, Holder);
2817 
2818   for (const RangeSpanList &List : Holder.getRangeLists())
2819     emitRangeList(*this, Asm, List);
2820 
2821   if (TableEnd)
2822     Asm->OutStreamer->emitLabel(TableEnd);
2823 }
2824 
2825 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2826 /// .debug_rnglists section.
2827 void DwarfDebug::emitDebugRanges() {
2828   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2829 
2830   emitDebugRangesImpl(Holder,
2831                       getDwarfVersion() >= 5
2832                           ? Asm->getObjFileLowering().getDwarfRnglistsSection()
2833                           : Asm->getObjFileLowering().getDwarfRangesSection());
2834 }
2835 
2836 void DwarfDebug::emitDebugRangesDWO() {
2837   emitDebugRangesImpl(InfoHolder,
2838                       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2839 }
2840 
2841 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2842   for (auto *MN : Nodes) {
2843     if (auto *M = dyn_cast<DIMacro>(MN))
2844       emitMacro(*M);
2845     else if (auto *F = dyn_cast<DIMacroFile>(MN))
2846       emitMacroFile(*F, U);
2847     else
2848       llvm_unreachable("Unexpected DI type!");
2849   }
2850 }
2851 
2852 void DwarfDebug::emitMacro(DIMacro &M) {
2853   Asm->emitULEB128(M.getMacinfoType());
2854   Asm->emitULEB128(M.getLine());
2855   StringRef Name = M.getName();
2856   StringRef Value = M.getValue();
2857   Asm->OutStreamer->emitBytes(Name);
2858   if (!Value.empty()) {
2859     // There should be one space between macro name and macro value.
2860     Asm->emitInt8(' ');
2861     Asm->OutStreamer->emitBytes(Value);
2862   }
2863   Asm->emitInt8('\0');
2864 }
2865 
2866 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2867   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2868   Asm->emitULEB128(dwarf::DW_MACINFO_start_file);
2869   Asm->emitULEB128(F.getLine());
2870   Asm->emitULEB128(U.getOrCreateSourceID(F.getFile()));
2871   handleMacroNodes(F.getElements(), U);
2872   Asm->emitULEB128(dwarf::DW_MACINFO_end_file);
2873 }
2874 
2875 void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
2876   for (const auto &P : CUMap) {
2877     auto &TheCU = *P.second;
2878     auto *SkCU = TheCU.getSkeleton();
2879     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2880     auto *CUNode = cast<DICompileUnit>(P.first);
2881     DIMacroNodeArray Macros = CUNode->getMacros();
2882     if (Macros.empty())
2883       continue;
2884     Asm->OutStreamer->SwitchSection(Section);
2885     Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
2886     handleMacroNodes(Macros, U);
2887     Asm->OutStreamer->AddComment("End Of Macro List Mark");
2888     Asm->emitInt8(0);
2889   }
2890 }
2891 
2892 /// Emit macros into a debug macinfo section.
2893 void DwarfDebug::emitDebugMacinfo() {
2894   emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoSection());
2895 }
2896 
2897 void DwarfDebug::emitDebugMacinfoDWO() {
2898   emitDebugMacinfoImpl(Asm->getObjFileLowering().getDwarfMacinfoDWOSection());
2899 }
2900 
2901 // DWARF5 Experimental Separate Dwarf emitters.
2902 
2903 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2904                                   std::unique_ptr<DwarfCompileUnit> NewU) {
2905 
2906   if (!CompilationDir.empty())
2907     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2908   addGnuPubAttributes(*NewU, Die);
2909 
2910   SkeletonHolder.addUnit(std::move(NewU));
2911 }
2912 
2913 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2914 
2915   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
2916       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
2917       UnitKind::Skeleton);
2918   DwarfCompileUnit &NewCU = *OwnedUnit;
2919   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2920 
2921   NewCU.initStmtList();
2922 
2923   if (useSegmentedStringOffsetsTable())
2924     NewCU.addStringOffsetsStart();
2925 
2926   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2927 
2928   return NewCU;
2929 }
2930 
2931 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2932 // compile units that would normally be in debug_info.
2933 void DwarfDebug::emitDebugInfoDWO() {
2934   assert(useSplitDwarf() && "No split dwarf debug info?");
2935   // Don't emit relocations into the dwo file.
2936   InfoHolder.emitUnits(/* UseOffsets */ true);
2937 }
2938 
2939 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2940 // abbreviations for the .debug_info.dwo section.
2941 void DwarfDebug::emitDebugAbbrevDWO() {
2942   assert(useSplitDwarf() && "No split dwarf?");
2943   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2944 }
2945 
2946 void DwarfDebug::emitDebugLineDWO() {
2947   assert(useSplitDwarf() && "No split dwarf?");
2948   SplitTypeUnitFileTable.Emit(
2949       *Asm->OutStreamer, MCDwarfLineTableParams(),
2950       Asm->getObjFileLowering().getDwarfLineDWOSection());
2951 }
2952 
2953 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2954   assert(useSplitDwarf() && "No split dwarf?");
2955   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2956       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2957       InfoHolder.getStringOffsetsStartSym());
2958 }
2959 
2960 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2961 // string section and is identical in format to traditional .debug_str
2962 // sections.
2963 void DwarfDebug::emitDebugStrDWO() {
2964   if (useSegmentedStringOffsetsTable())
2965     emitStringOffsetsTableHeaderDWO();
2966   assert(useSplitDwarf() && "No split dwarf?");
2967   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2968   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2969                          OffSec, /* UseRelativeOffsets = */ false);
2970 }
2971 
2972 // Emit address pool.
2973 void DwarfDebug::emitDebugAddr() {
2974   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2975 }
2976 
2977 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2978   if (!useSplitDwarf())
2979     return nullptr;
2980   const DICompileUnit *DIUnit = CU.getCUNode();
2981   SplitTypeUnitFileTable.maybeSetRootFile(
2982       DIUnit->getDirectory(), DIUnit->getFilename(),
2983       CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2984   return &SplitTypeUnitFileTable;
2985 }
2986 
2987 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2988   MD5 Hash;
2989   Hash.update(Identifier);
2990   // ... take the least significant 8 bytes and return those. Our MD5
2991   // implementation always returns its results in little endian, so we actually
2992   // need the "high" word.
2993   MD5::MD5Result Result;
2994   Hash.final(Result);
2995   return Result.high();
2996 }
2997 
2998 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2999                                       StringRef Identifier, DIE &RefDie,
3000                                       const DICompositeType *CTy) {
3001   // Fast path if we're building some type units and one has already used the
3002   // address pool we know we're going to throw away all this work anyway, so
3003   // don't bother building dependent types.
3004   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
3005     return;
3006 
3007   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3008   if (!Ins.second) {
3009     CU.addDIETypeSignature(RefDie, Ins.first->second);
3010     return;
3011   }
3012 
3013   bool TopLevelType = TypeUnitsUnderConstruction.empty();
3014   AddrPool.resetUsedFlag();
3015 
3016   auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
3017                                                     getDwoLineTable(CU));
3018   DwarfTypeUnit &NewTU = *OwnedUnit;
3019   DIE &UnitDie = NewTU.getUnitDie();
3020   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3021 
3022   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3023                 CU.getLanguage());
3024 
3025   uint64_t Signature = makeTypeSignature(Identifier);
3026   NewTU.setTypeSignature(Signature);
3027   Ins.first->second = Signature;
3028 
3029   if (useSplitDwarf()) {
3030     MCSection *Section =
3031         getDwarfVersion() <= 4
3032             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
3033             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
3034     NewTU.setSection(Section);
3035   } else {
3036     MCSection *Section =
3037         getDwarfVersion() <= 4
3038             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
3039             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
3040     NewTU.setSection(Section);
3041     // Non-split type units reuse the compile unit's line table.
3042     CU.applyStmtList(UnitDie);
3043   }
3044 
3045   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3046   // units.
3047   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
3048     NewTU.addStringOffsetsStart();
3049 
3050   NewTU.setType(NewTU.createTypeDIE(CTy));
3051 
3052   if (TopLevelType) {
3053     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3054     TypeUnitsUnderConstruction.clear();
3055 
3056     // Types referencing entries in the address table cannot be placed in type
3057     // units.
3058     if (AddrPool.hasBeenUsed()) {
3059 
3060       // Remove all the types built while building this type.
3061       // This is pessimistic as some of these types might not be dependent on
3062       // the type that used an address.
3063       for (const auto &TU : TypeUnitsToAdd)
3064         TypeSignatures.erase(TU.second);
3065 
3066       // Construct this type in the CU directly.
3067       // This is inefficient because all the dependent types will be rebuilt
3068       // from scratch, including building them in type units, discovering that
3069       // they depend on addresses, throwing them out and rebuilding them.
3070       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3071       return;
3072     }
3073 
3074     // If the type wasn't dependent on fission addresses, finish adding the type
3075     // and all its dependent types.
3076     for (auto &TU : TypeUnitsToAdd) {
3077       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
3078       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3079     }
3080   }
3081   CU.addDIETypeSignature(RefDie, Signature);
3082 }
3083 
3084 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
3085     : DD(DD),
3086       TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
3087   DD->TypeUnitsUnderConstruction.clear();
3088   assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
3089 }
3090 
3091 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3092   DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
3093   DD->AddrPool.resetUsedFlag();
3094 }
3095 
3096 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
3097   return NonTypeUnitContext(this);
3098 }
3099 
3100 // Add the Name along with its companion DIE to the appropriate accelerator
3101 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3102 // AccelTableKind::Apple, we use the table we got as an argument). If
3103 // accelerator tables are disabled, this function does nothing.
3104 template <typename DataT>
3105 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3106                                   AccelTable<DataT> &AppleAccel, StringRef Name,
3107                                   const DIE &Die) {
3108   if (getAccelTableKind() == AccelTableKind::None)
3109     return;
3110 
3111   if (getAccelTableKind() != AccelTableKind::Apple &&
3112       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3113     return;
3114 
3115   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3116   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3117 
3118   switch (getAccelTableKind()) {
3119   case AccelTableKind::Apple:
3120     AppleAccel.addName(Ref, Die);
3121     break;
3122   case AccelTableKind::Dwarf:
3123     AccelDebugNames.addName(Ref, Die);
3124     break;
3125   case AccelTableKind::Default:
3126     llvm_unreachable("Default should have already been resolved.");
3127   case AccelTableKind::None:
3128     llvm_unreachable("None handled above");
3129   }
3130 }
3131 
3132 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3133                               const DIE &Die) {
3134   addAccelNameImpl(CU, AccelNames, Name, Die);
3135 }
3136 
3137 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3138                               const DIE &Die) {
3139   // ObjC names go only into the Apple accelerator tables.
3140   if (getAccelTableKind() == AccelTableKind::Apple)
3141     addAccelNameImpl(CU, AccelObjC, Name, Die);
3142 }
3143 
3144 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3145                                    const DIE &Die) {
3146   addAccelNameImpl(CU, AccelNamespace, Name, Die);
3147 }
3148 
3149 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3150                               const DIE &Die, char Flags) {
3151   addAccelNameImpl(CU, AccelTypes, Name, Die);
3152 }
3153 
3154 uint16_t DwarfDebug::getDwarfVersion() const {
3155   return Asm->OutStreamer->getContext().getDwarfVersion();
3156 }
3157 
3158 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3159   return SectionLabels.find(S)->second;
3160 }
3161 void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
3162   SectionLabels.insert(std::make_pair(&S->getSection(), S));
3163 }
3164