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