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