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