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