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