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