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