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