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