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