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