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