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