xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/AsmPrinter/DwarfDebug.cpp (revision 6be3386466ab79a84b48429ae66244f21526d3df)
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(),
1075         NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
1076         NewCU.getUniqueID());
1077 
1078   if (useSplitDwarf()) {
1079     NewCU.setSkeleton(constructSkeletonCU(NewCU));
1080     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
1081   } else {
1082     finishUnitAttributes(DIUnit, NewCU);
1083     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
1084   }
1085 
1086   CUMap.insert({DIUnit, &NewCU});
1087   CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
1088   return NewCU;
1089 }
1090 
1091 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
1092                                                   const DIImportedEntity *N) {
1093   if (isa<DILocalScope>(N->getScope()))
1094     return;
1095   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
1096     D->addChild(TheCU.constructImportedEntityDIE(N));
1097 }
1098 
1099 /// Sort and unique GVEs by comparing their fragment offset.
1100 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
1101 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
1102   llvm::sort(
1103       GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
1104         // Sort order: first null exprs, then exprs without fragment
1105         // info, then sort by fragment offset in bits.
1106         // FIXME: Come up with a more comprehensive comparator so
1107         // the sorting isn't non-deterministic, and so the following
1108         // std::unique call works correctly.
1109         if (!A.Expr || !B.Expr)
1110           return !!B.Expr;
1111         auto FragmentA = A.Expr->getFragmentInfo();
1112         auto FragmentB = B.Expr->getFragmentInfo();
1113         if (!FragmentA || !FragmentB)
1114           return !!FragmentB;
1115         return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
1116       });
1117   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
1118                          [](DwarfCompileUnit::GlobalExpr A,
1119                             DwarfCompileUnit::GlobalExpr B) {
1120                            return A.Expr == B.Expr;
1121                          }),
1122              GVEs.end());
1123   return GVEs;
1124 }
1125 
1126 // Emit all Dwarf sections that should come prior to the content. Create
1127 // global DIEs and emit initial debug info sections. This is invoked by
1128 // the target AsmPrinter.
1129 void DwarfDebug::beginModule() {
1130   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
1131                      DWARFGroupDescription, TimePassesIsEnabled);
1132   if (DisableDebugInfoPrinting) {
1133     MMI->setDebugInfoAvailability(false);
1134     return;
1135   }
1136 
1137   const Module *M = MMI->getModule();
1138 
1139   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
1140                                        M->debug_compile_units_end());
1141   // Tell MMI whether we have debug info.
1142   assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
1143          "DebugInfoAvailabilty initialized unexpectedly");
1144   SingleCU = NumDebugCUs == 1;
1145   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
1146       GVMap;
1147   for (const GlobalVariable &Global : M->globals()) {
1148     SmallVector<DIGlobalVariableExpression *, 1> GVs;
1149     Global.getDebugInfo(GVs);
1150     for (auto *GVE : GVs)
1151       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
1152   }
1153 
1154   // Create the symbol that designates the start of the unit's contribution
1155   // to the string offsets table. In a split DWARF scenario, only the skeleton
1156   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
1157   if (useSegmentedStringOffsetsTable())
1158     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
1159         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
1160 
1161 
1162   // Create the symbols that designates the start of the DWARF v5 range list
1163   // and locations list tables. They are located past the table headers.
1164   if (getDwarfVersion() >= 5) {
1165     DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1166     Holder.setRnglistsTableBaseSym(
1167         Asm->createTempSymbol("rnglists_table_base"));
1168 
1169     if (useSplitDwarf())
1170       InfoHolder.setRnglistsTableBaseSym(
1171           Asm->createTempSymbol("rnglists_dwo_table_base"));
1172   }
1173 
1174   // Create the symbol that points to the first entry following the debug
1175   // address table (.debug_addr) header.
1176   AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
1177   DebugLocs.setSym(Asm->createTempSymbol("loclists_table_base"));
1178 
1179   for (DICompileUnit *CUNode : M->debug_compile_units()) {
1180     // FIXME: Move local imported entities into a list attached to the
1181     // subprogram, then this search won't be needed and a
1182     // getImportedEntities().empty() test should go below with the rest.
1183     bool HasNonLocalImportedEntities = llvm::any_of(
1184         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
1185           return !isa<DILocalScope>(IE->getScope());
1186         });
1187 
1188     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
1189         CUNode->getRetainedTypes().empty() &&
1190         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
1191       continue;
1192 
1193     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
1194 
1195     // Global Variables.
1196     for (auto *GVE : CUNode->getGlobalVariables()) {
1197       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
1198       // already know about the variable and it isn't adding a constant
1199       // expression.
1200       auto &GVMapEntry = GVMap[GVE->getVariable()];
1201       auto *Expr = GVE->getExpression();
1202       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
1203         GVMapEntry.push_back({nullptr, Expr});
1204     }
1205     DenseSet<DIGlobalVariable *> Processed;
1206     for (auto *GVE : CUNode->getGlobalVariables()) {
1207       DIGlobalVariable *GV = GVE->getVariable();
1208       if (Processed.insert(GV).second)
1209         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
1210     }
1211 
1212     for (auto *Ty : CUNode->getEnumTypes()) {
1213       // The enum types array by design contains pointers to
1214       // MDNodes rather than DIRefs. Unique them here.
1215       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
1216     }
1217     for (auto *Ty : CUNode->getRetainedTypes()) {
1218       // The retained types array by design contains pointers to
1219       // MDNodes rather than DIRefs. Unique them here.
1220       if (DIType *RT = dyn_cast<DIType>(Ty))
1221           // There is no point in force-emitting a forward declaration.
1222           CU.getOrCreateTypeDIE(RT);
1223     }
1224     // Emit imported_modules last so that the relevant context is already
1225     // available.
1226     for (auto *IE : CUNode->getImportedEntities())
1227       constructAndAddImportedEntityDIE(CU, IE);
1228   }
1229 }
1230 
1231 void DwarfDebug::finishEntityDefinitions() {
1232   for (const auto &Entity : ConcreteEntities) {
1233     DIE *Die = Entity->getDIE();
1234     assert(Die);
1235     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
1236     // in the ConcreteEntities list, rather than looking it up again here.
1237     // DIE::getUnit isn't simple - it walks parent pointers, etc.
1238     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
1239     assert(Unit);
1240     Unit->finishEntityDefinition(Entity.get());
1241   }
1242 }
1243 
1244 void DwarfDebug::finishSubprogramDefinitions() {
1245   for (const DISubprogram *SP : ProcessedSPNodes) {
1246     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
1247     forBothCUs(
1248         getOrCreateDwarfCompileUnit(SP->getUnit()),
1249         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
1250   }
1251 }
1252 
1253 void DwarfDebug::finalizeModuleInfo() {
1254   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1255 
1256   finishSubprogramDefinitions();
1257 
1258   finishEntityDefinitions();
1259 
1260   // Include the DWO file name in the hash if there's more than one CU.
1261   // This handles ThinLTO's situation where imported CUs may very easily be
1262   // duplicate with the same CU partially imported into another ThinLTO unit.
1263   StringRef DWOName;
1264   if (CUMap.size() > 1)
1265     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
1266 
1267   // Handle anything that needs to be done on a per-unit basis after
1268   // all other generation.
1269   for (const auto &P : CUMap) {
1270     auto &TheCU = *P.second;
1271     if (TheCU.getCUNode()->isDebugDirectivesOnly())
1272       continue;
1273     // Emit DW_AT_containing_type attribute to connect types with their
1274     // vtable holding type.
1275     TheCU.constructContainingTypeDIEs();
1276 
1277     // Add CU specific attributes if we need to add any.
1278     // If we're splitting the dwarf out now that we've got the entire
1279     // CU then add the dwo id to it.
1280     auto *SkCU = TheCU.getSkeleton();
1281 
1282     bool HasSplitUnit = SkCU && !TheCU.getUnitDie().children().empty();
1283 
1284     if (HasSplitUnit) {
1285       dwarf::Attribute attrDWOName = getDwarfVersion() >= 5
1286                                          ? dwarf::DW_AT_dwo_name
1287                                          : dwarf::DW_AT_GNU_dwo_name;
1288       finishUnitAttributes(TheCU.getCUNode(), TheCU);
1289       TheCU.addString(TheCU.getUnitDie(), attrDWOName,
1290                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1291       SkCU->addString(SkCU->getUnitDie(), attrDWOName,
1292                       Asm->TM.Options.MCOptions.SplitDwarfFile);
1293       // Emit a unique identifier for this CU.
1294       uint64_t ID =
1295           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
1296       if (getDwarfVersion() >= 5) {
1297         TheCU.setDWOId(ID);
1298         SkCU->setDWOId(ID);
1299       } else {
1300         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1301                       dwarf::DW_FORM_data8, ID);
1302         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
1303                       dwarf::DW_FORM_data8, ID);
1304       }
1305 
1306       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
1307         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
1308         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
1309                               Sym, Sym);
1310       }
1311     } else if (SkCU) {
1312       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
1313     }
1314 
1315     // If we have code split among multiple sections or non-contiguous
1316     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
1317     // remain in the .o file, otherwise add a DW_AT_low_pc.
1318     // FIXME: We should use ranges allow reordering of code ala
1319     // .subsections_via_symbols in mach-o. This would mean turning on
1320     // ranges for all subprogram DIEs for mach-o.
1321     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1322 
1323     if (unsigned NumRanges = TheCU.getRanges().size()) {
1324       if (NumRanges > 1 && useRangesSection())
1325         // A DW_AT_low_pc attribute may also be specified in combination with
1326         // DW_AT_ranges to specify the default base address for use in
1327         // location lists (see Section 2.6.2) and range lists (see Section
1328         // 2.17.3).
1329         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
1330       else
1331         U.setBaseAddress(TheCU.getRanges().front().Begin);
1332       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
1333     }
1334 
1335     // We don't keep track of which addresses are used in which CU so this
1336     // is a bit pessimistic under LTO.
1337     if ((HasSplitUnit || getDwarfVersion() >= 5) && !AddrPool.isEmpty())
1338       U.addAddrTableBase();
1339 
1340     if (getDwarfVersion() >= 5) {
1341       if (U.hasRangeLists())
1342         U.addRnglistsBase();
1343 
1344       if (!DebugLocs.getLists().empty()) {
1345         if (!useSplitDwarf())
1346           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_loclists_base,
1347                             DebugLocs.getSym(),
1348                             TLOF.getDwarfLoclistsSection()->getBeginSymbol());
1349       }
1350     }
1351 
1352     auto *CUNode = cast<DICompileUnit>(P.first);
1353     // If compile Unit has macros, emit "DW_AT_macro_info/DW_AT_macros"
1354     // attribute.
1355     if (CUNode->getMacros()) {
1356       if (getDwarfVersion() >= 5) {
1357         if (useSplitDwarf())
1358           TheCU.addSectionDelta(
1359               TheCU.getUnitDie(), dwarf::DW_AT_macros, U.getMacroLabelBegin(),
1360               TLOF.getDwarfMacroDWOSection()->getBeginSymbol());
1361         else
1362           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macros,
1363                             U.getMacroLabelBegin(),
1364                             TLOF.getDwarfMacroSection()->getBeginSymbol());
1365       } else {
1366         if (useSplitDwarf())
1367           TheCU.addSectionDelta(
1368               TheCU.getUnitDie(), dwarf::DW_AT_macro_info,
1369               U.getMacroLabelBegin(),
1370               TLOF.getDwarfMacinfoDWOSection()->getBeginSymbol());
1371         else
1372           U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
1373                             U.getMacroLabelBegin(),
1374                             TLOF.getDwarfMacinfoSection()->getBeginSymbol());
1375       }
1376     }
1377     }
1378 
1379   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
1380   for (auto *CUNode : MMI->getModule()->debug_compile_units())
1381     if (CUNode->getDWOId())
1382       getOrCreateDwarfCompileUnit(CUNode);
1383 
1384   // Compute DIE offsets and sizes.
1385   InfoHolder.computeSizeAndOffsets();
1386   if (useSplitDwarf())
1387     SkeletonHolder.computeSizeAndOffsets();
1388 }
1389 
1390 // Emit all Dwarf sections that should come after the content.
1391 void DwarfDebug::endModule() {
1392   assert(CurFn == nullptr);
1393   assert(CurMI == nullptr);
1394 
1395   for (const auto &P : CUMap) {
1396     auto &CU = *P.second;
1397     CU.createBaseTypeDIEs();
1398   }
1399 
1400   // If we aren't actually generating debug info (check beginModule -
1401   // conditionalized on !DisableDebugInfoPrinting and the presence of the
1402   // llvm.dbg.cu metadata node)
1403   if (!MMI->hasDebugInfo())
1404     return;
1405 
1406   // Finalize the debug info for the module.
1407   finalizeModuleInfo();
1408 
1409   if (useSplitDwarf())
1410     // Emit debug_loc.dwo/debug_loclists.dwo section.
1411     emitDebugLocDWO();
1412   else
1413     // Emit debug_loc/debug_loclists section.
1414     emitDebugLoc();
1415 
1416   // Corresponding abbreviations into a abbrev section.
1417   emitAbbreviations();
1418 
1419   // Emit all the DIEs into a debug info section.
1420   emitDebugInfo();
1421 
1422   // Emit info into a debug aranges section.
1423   if (GenerateARangeSection)
1424     emitDebugARanges();
1425 
1426   // Emit info into a debug ranges section.
1427   emitDebugRanges();
1428 
1429   if (useSplitDwarf())
1430   // Emit info into a debug macinfo.dwo section.
1431     emitDebugMacinfoDWO();
1432   else
1433     // Emit info into a debug macinfo/macro section.
1434     emitDebugMacinfo();
1435 
1436   emitDebugStr();
1437 
1438   if (useSplitDwarf()) {
1439     emitDebugStrDWO();
1440     emitDebugInfoDWO();
1441     emitDebugAbbrevDWO();
1442     emitDebugLineDWO();
1443     emitDebugRangesDWO();
1444   }
1445 
1446   emitDebugAddr();
1447 
1448   // Emit info into the dwarf accelerator table sections.
1449   switch (getAccelTableKind()) {
1450   case AccelTableKind::Apple:
1451     emitAccelNames();
1452     emitAccelObjC();
1453     emitAccelNamespaces();
1454     emitAccelTypes();
1455     break;
1456   case AccelTableKind::Dwarf:
1457     emitAccelDebugNames();
1458     break;
1459   case AccelTableKind::None:
1460     break;
1461   case AccelTableKind::Default:
1462     llvm_unreachable("Default should have already been resolved.");
1463   }
1464 
1465   // Emit the pubnames and pubtypes sections if requested.
1466   emitDebugPubSections();
1467 
1468   // clean up.
1469   // FIXME: AbstractVariables.clear();
1470 }
1471 
1472 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1473                                                const DINode *Node,
1474                                                const MDNode *ScopeNode) {
1475   if (CU.getExistingAbstractEntity(Node))
1476     return;
1477 
1478   CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1479                                        cast<DILocalScope>(ScopeNode)));
1480 }
1481 
1482 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1483     const DINode *Node, const MDNode *ScopeNode) {
1484   if (CU.getExistingAbstractEntity(Node))
1485     return;
1486 
1487   if (LexicalScope *Scope =
1488           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1489     CU.createAbstractEntity(Node, Scope);
1490 }
1491 
1492 // Collect variable information from side table maintained by MF.
1493 void DwarfDebug::collectVariableInfoFromMFTable(
1494     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1495   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1496   LLVM_DEBUG(dbgs() << "DwarfDebug: collecting variables from MF side table\n");
1497   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1498     if (!VI.Var)
1499       continue;
1500     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1501            "Expected inlined-at fields to agree");
1502 
1503     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1504     Processed.insert(Var);
1505     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1506 
1507     // If variable scope is not found then skip this variable.
1508     if (!Scope) {
1509       LLVM_DEBUG(dbgs() << "Dropping debug info for " << VI.Var->getName()
1510                         << ", no variable scope found\n");
1511       continue;
1512     }
1513 
1514     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1515     auto RegVar = std::make_unique<DbgVariable>(
1516                     cast<DILocalVariable>(Var.first), Var.second);
1517     RegVar->initializeMMI(VI.Expr, VI.Slot);
1518     LLVM_DEBUG(dbgs() << "Created DbgVariable for " << VI.Var->getName()
1519                       << "\n");
1520     if (DbgVariable *DbgVar = MFVars.lookup(Var))
1521       DbgVar->addMMIEntry(*RegVar);
1522     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1523       MFVars.insert({Var, RegVar.get()});
1524       ConcreteEntities.push_back(std::move(RegVar));
1525     }
1526   }
1527 }
1528 
1529 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1530 /// enclosing lexical scope. The check ensures there are no other instructions
1531 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1532 /// either open or otherwise rolls off the end of the scope.
1533 static bool validThroughout(LexicalScopes &LScopes,
1534                             const MachineInstr *DbgValue,
1535                             const MachineInstr *RangeEnd) {
1536   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1537   auto MBB = DbgValue->getParent();
1538   auto DL = DbgValue->getDebugLoc();
1539   auto *LScope = LScopes.findLexicalScope(DL);
1540   // Scope doesn't exist; this is a dead DBG_VALUE.
1541   if (!LScope)
1542     return false;
1543   auto &LSRange = LScope->getRanges();
1544   if (LSRange.size() == 0)
1545     return false;
1546 
1547 
1548   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1549   const MachineInstr *LScopeBegin = LSRange.front().first;
1550   // Early exit if the lexical scope begins outside of the current block.
1551   if (LScopeBegin->getParent() != MBB)
1552     return false;
1553 
1554   // If there are instructions belonging to our scope in another block, and
1555   // we're not a constant (see DWARF2 comment below), then we can't be
1556   // validThroughout.
1557   const MachineInstr *LScopeEnd = LSRange.back().second;
1558   if (RangeEnd && LScopeEnd->getParent() != MBB)
1559     return false;
1560 
1561   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1562   for (++Pred; Pred != MBB->rend(); ++Pred) {
1563     if (Pred->getFlag(MachineInstr::FrameSetup))
1564       break;
1565     auto PredDL = Pred->getDebugLoc();
1566     if (!PredDL || Pred->isMetaInstruction())
1567       continue;
1568     // Check whether the instruction preceding the DBG_VALUE is in the same
1569     // (sub)scope as the DBG_VALUE.
1570     if (DL->getScope() == PredDL->getScope())
1571       return false;
1572     auto *PredScope = LScopes.findLexicalScope(PredDL);
1573     if (!PredScope || LScope->dominates(PredScope))
1574       return false;
1575   }
1576 
1577   // If the range of the DBG_VALUE is open-ended, report success.
1578   if (!RangeEnd)
1579     return true;
1580 
1581   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1582   // throughout the function. This is a hack, presumably for DWARF v2 and not
1583   // necessarily correct. It would be much better to use a dbg.declare instead
1584   // if we know the constant is live throughout the scope.
1585   if (DbgValue->getDebugOperand(0).isImm() && MBB->pred_empty())
1586     return true;
1587 
1588   // Now check for situations where an "open-ended" DBG_VALUE isn't enough to
1589   // determine eligibility for a single location, e.g. nested scopes, inlined
1590   // functions.
1591   // FIXME: For now we just handle a simple (but common) case where the scope
1592   // is contained in MBB. We could be smarter here.
1593   //
1594   // At this point we know that our scope ends in MBB. So, if RangeEnd exists
1595   // outside of the block we can ignore it; the location is just leaking outside
1596   // its scope.
1597   assert(LScopeEnd->getParent() == MBB && "Scope ends outside MBB");
1598   if (RangeEnd->getParent() != DbgValue->getParent())
1599     return true;
1600 
1601   // The location range and variable's enclosing scope are both contained within
1602   // MBB, test if location terminates before end of scope.
1603   for (auto I = RangeEnd->getIterator(); I != MBB->end(); ++I)
1604     if (&*I == LScopeEnd)
1605       return false;
1606 
1607   // There's a single location which starts at the scope start, and ends at or
1608   // after the scope end.
1609   return true;
1610 }
1611 
1612 /// Build the location list for all DBG_VALUEs in the function that
1613 /// describe the same variable. The resulting DebugLocEntries will have
1614 /// strict monotonically increasing begin addresses and will never
1615 /// overlap. If the resulting list has only one entry that is valid
1616 /// throughout variable's scope return true.
1617 //
1618 // See the definition of DbgValueHistoryMap::Entry for an explanation of the
1619 // different kinds of history map entries. One thing to be aware of is that if
1620 // a debug value is ended by another entry (rather than being valid until the
1621 // end of the function), that entry's instruction may or may not be included in
1622 // the range, depending on if the entry is a clobbering entry (it has an
1623 // instruction that clobbers one or more preceding locations), or if it is an
1624 // (overlapping) debug value entry. This distinction can be seen in the example
1625 // below. The first debug value is ended by the clobbering entry 2, and the
1626 // second and third debug values are ended by the overlapping debug value entry
1627 // 4.
1628 //
1629 // Input:
1630 //
1631 //   History map entries [type, end index, mi]
1632 //
1633 // 0 |      [DbgValue, 2, DBG_VALUE $reg0, [...] (fragment 0, 32)]
1634 // 1 | |    [DbgValue, 4, DBG_VALUE $reg1, [...] (fragment 32, 32)]
1635 // 2 | |    [Clobber, $reg0 = [...], -, -]
1636 // 3   | |  [DbgValue, 4, DBG_VALUE 123, [...] (fragment 64, 32)]
1637 // 4        [DbgValue, ~0, DBG_VALUE @g, [...] (fragment 0, 96)]
1638 //
1639 // Output [start, end) [Value...]:
1640 //
1641 // [0-1)    [(reg0, fragment 0, 32)]
1642 // [1-3)    [(reg0, fragment 0, 32), (reg1, fragment 32, 32)]
1643 // [3-4)    [(reg1, fragment 32, 32), (123, fragment 64, 32)]
1644 // [4-)     [(@g, fragment 0, 96)]
1645 bool DwarfDebug::buildLocationList(
1646     SmallVectorImpl<DebugLocEntry> &DebugLoc,
1647     const DbgValueHistoryMap::Entries &Entries,
1648     DenseSet<const MachineBasicBlock *> &VeryLargeBlocks) {
1649   using OpenRange =
1650       std::pair<DbgValueHistoryMap::EntryIndex, DbgValueLoc>;
1651   SmallVector<OpenRange, 4> OpenRanges;
1652   bool isSafeForSingleLocation = true;
1653   const MachineInstr *StartDebugMI = nullptr;
1654   const MachineInstr *EndMI = nullptr;
1655 
1656   for (auto EB = Entries.begin(), EI = EB, EE = Entries.end(); EI != EE; ++EI) {
1657     const MachineInstr *Instr = EI->getInstr();
1658 
1659     // Remove all values that are no longer live.
1660     size_t Index = std::distance(EB, EI);
1661     auto Last =
1662         remove_if(OpenRanges, [&](OpenRange &R) { return R.first <= Index; });
1663     OpenRanges.erase(Last, OpenRanges.end());
1664 
1665     // If we are dealing with a clobbering entry, this iteration will result in
1666     // a location list entry starting after the clobbering instruction.
1667     const MCSymbol *StartLabel =
1668         EI->isClobber() ? getLabelAfterInsn(Instr) : getLabelBeforeInsn(Instr);
1669     assert(StartLabel &&
1670            "Forgot label before/after instruction starting a range!");
1671 
1672     const MCSymbol *EndLabel;
1673     if (std::next(EI) == Entries.end()) {
1674       const MachineBasicBlock &EndMBB = Asm->MF->back();
1675       EndLabel = Asm->MBBSectionRanges[EndMBB.getSectionIDNum()].EndLabel;
1676       if (EI->isClobber())
1677         EndMI = EI->getInstr();
1678     }
1679     else if (std::next(EI)->isClobber())
1680       EndLabel = getLabelAfterInsn(std::next(EI)->getInstr());
1681     else
1682       EndLabel = getLabelBeforeInsn(std::next(EI)->getInstr());
1683     assert(EndLabel && "Forgot label after instruction ending a range!");
1684 
1685     if (EI->isDbgValue())
1686       LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Instr << "\n");
1687 
1688     // If this history map entry has a debug value, add that to the list of
1689     // open ranges and check if its location is valid for a single value
1690     // location.
1691     if (EI->isDbgValue()) {
1692       // Do not add undef debug values, as they are redundant information in
1693       // the location list entries. An undef debug results in an empty location
1694       // description. If there are any non-undef fragments then padding pieces
1695       // with empty location descriptions will automatically be inserted, and if
1696       // all fragments are undef then the whole location list entry is
1697       // redundant.
1698       if (!Instr->isUndefDebugValue()) {
1699         auto Value = getDebugLocValue(Instr);
1700         OpenRanges.emplace_back(EI->getEndIndex(), Value);
1701 
1702         // TODO: Add support for single value fragment locations.
1703         if (Instr->getDebugExpression()->isFragment())
1704           isSafeForSingleLocation = false;
1705 
1706         if (!StartDebugMI)
1707           StartDebugMI = Instr;
1708       } else {
1709         isSafeForSingleLocation = false;
1710       }
1711     }
1712 
1713     // Location list entries with empty location descriptions are redundant
1714     // information in DWARF, so do not emit those.
1715     if (OpenRanges.empty())
1716       continue;
1717 
1718     // Omit entries with empty ranges as they do not have any effect in DWARF.
1719     if (StartLabel == EndLabel) {
1720       LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1721       continue;
1722     }
1723 
1724     SmallVector<DbgValueLoc, 4> Values;
1725     for (auto &R : OpenRanges)
1726       Values.push_back(R.second);
1727     DebugLoc.emplace_back(StartLabel, EndLabel, Values);
1728 
1729     // Attempt to coalesce the ranges of two otherwise identical
1730     // DebugLocEntries.
1731     auto CurEntry = DebugLoc.rbegin();
1732     LLVM_DEBUG({
1733       dbgs() << CurEntry->getValues().size() << " Values:\n";
1734       for (auto &Value : CurEntry->getValues())
1735         Value.dump();
1736       dbgs() << "-----\n";
1737     });
1738 
1739     auto PrevEntry = std::next(CurEntry);
1740     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1741       DebugLoc.pop_back();
1742   }
1743 
1744   // If there's a single entry, safe for a single location, and not part of
1745   // an over-sized basic block, then ask validThroughout whether this
1746   // location can be represented as a single variable location.
1747   if (DebugLoc.size() != 1 || !isSafeForSingleLocation)
1748     return false;
1749   if (VeryLargeBlocks.count(StartDebugMI->getParent()))
1750     return false;
1751   return validThroughout(LScopes, StartDebugMI, EndMI);
1752 }
1753 
1754 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1755                                             LexicalScope &Scope,
1756                                             const DINode *Node,
1757                                             const DILocation *Location,
1758                                             const MCSymbol *Sym) {
1759   ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1760   if (isa<const DILocalVariable>(Node)) {
1761     ConcreteEntities.push_back(
1762         std::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1763                                        Location));
1764     InfoHolder.addScopeVariable(&Scope,
1765         cast<DbgVariable>(ConcreteEntities.back().get()));
1766   } else if (isa<const DILabel>(Node)) {
1767     ConcreteEntities.push_back(
1768         std::make_unique<DbgLabel>(cast<const DILabel>(Node),
1769                                     Location, Sym));
1770     InfoHolder.addScopeLabel(&Scope,
1771         cast<DbgLabel>(ConcreteEntities.back().get()));
1772   }
1773   return ConcreteEntities.back().get();
1774 }
1775 
1776 // Find variables for each lexical scope.
1777 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1778                                    const DISubprogram *SP,
1779                                    DenseSet<InlinedEntity> &Processed) {
1780   // Grab the variable info that was squirreled away in the MMI side-table.
1781   collectVariableInfoFromMFTable(TheCU, Processed);
1782 
1783   // Identify blocks that are unreasonably sized, so that we can later
1784   // skip lexical scope analysis over them.
1785   DenseSet<const MachineBasicBlock *> VeryLargeBlocks;
1786   for (const auto &MBB : *CurFn)
1787     if (MBB.size() > LocationAnalysisSizeLimit)
1788       VeryLargeBlocks.insert(&MBB);
1789 
1790   for (const auto &I : DbgValues) {
1791     InlinedEntity IV = I.first;
1792     if (Processed.count(IV))
1793       continue;
1794 
1795     // Instruction ranges, specifying where IV is accessible.
1796     const auto &HistoryMapEntries = I.second;
1797     if (HistoryMapEntries.empty())
1798       continue;
1799 
1800     LexicalScope *Scope = nullptr;
1801     const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1802     if (const DILocation *IA = IV.second)
1803       Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1804     else
1805       Scope = LScopes.findLexicalScope(LocalVar->getScope());
1806     // If variable scope is not found then skip this variable.
1807     if (!Scope)
1808       continue;
1809 
1810     Processed.insert(IV);
1811     DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1812                                             *Scope, LocalVar, IV.second));
1813 
1814     const MachineInstr *MInsn = HistoryMapEntries.front().getInstr();
1815     assert(MInsn->isDebugValue() && "History must begin with debug value");
1816 
1817     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1818     // If the history map contains a single debug value, there may be an
1819     // additional entry which clobbers the debug value.
1820     size_t HistSize = HistoryMapEntries.size();
1821     bool SingleValueWithClobber =
1822         HistSize == 2 && HistoryMapEntries[1].isClobber();
1823     if (HistSize == 1 || SingleValueWithClobber) {
1824       const auto *End =
1825           SingleValueWithClobber ? HistoryMapEntries[1].getInstr() : nullptr;
1826       if (VeryLargeBlocks.count(MInsn->getParent()) == 0 &&
1827           validThroughout(LScopes, MInsn, End)) {
1828         RegVar->initializeDbgValue(MInsn);
1829         continue;
1830       }
1831     }
1832 
1833     // Do not emit location lists if .debug_loc secton is disabled.
1834     if (!useLocSection())
1835       continue;
1836 
1837     // Handle multiple DBG_VALUE instructions describing one variable.
1838     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1839 
1840     // Build the location list for this variable.
1841     SmallVector<DebugLocEntry, 8> Entries;
1842     bool isValidSingleLocation =
1843         buildLocationList(Entries, HistoryMapEntries, VeryLargeBlocks);
1844 
1845     // Check whether buildLocationList managed to merge all locations to one
1846     // that is valid throughout the variable's scope. If so, produce single
1847     // value location.
1848     if (isValidSingleLocation) {
1849       RegVar->initializeDbgValue(Entries[0].getValues()[0]);
1850       continue;
1851     }
1852 
1853     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1854     // unique identifiers, so don't bother resolving the type with the
1855     // identifier map.
1856     const DIBasicType *BT = dyn_cast<DIBasicType>(
1857         static_cast<const Metadata *>(LocalVar->getType()));
1858 
1859     // Finalize the entry by lowering it into a DWARF bytestream.
1860     for (auto &Entry : Entries)
1861       Entry.finalize(*Asm, List, BT, TheCU);
1862   }
1863 
1864   // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1865   // DWARF-related DbgLabel.
1866   for (const auto &I : DbgLabels) {
1867     InlinedEntity IL = I.first;
1868     const MachineInstr *MI = I.second;
1869     if (MI == nullptr)
1870       continue;
1871 
1872     LexicalScope *Scope = nullptr;
1873     const DILabel *Label = cast<DILabel>(IL.first);
1874     // The scope could have an extra lexical block file.
1875     const DILocalScope *LocalScope =
1876         Label->getScope()->getNonLexicalBlockFileScope();
1877     // Get inlined DILocation if it is inlined label.
1878     if (const DILocation *IA = IL.second)
1879       Scope = LScopes.findInlinedScope(LocalScope, IA);
1880     else
1881       Scope = LScopes.findLexicalScope(LocalScope);
1882     // If label scope is not found then skip this label.
1883     if (!Scope)
1884       continue;
1885 
1886     Processed.insert(IL);
1887     /// At this point, the temporary label is created.
1888     /// Save the temporary label to DbgLabel entity to get the
1889     /// actually address when generating Dwarf DIE.
1890     MCSymbol *Sym = getLabelBeforeInsn(MI);
1891     createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1892   }
1893 
1894   // Collect info for variables/labels that were optimized out.
1895   for (const DINode *DN : SP->getRetainedNodes()) {
1896     if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1897       continue;
1898     LexicalScope *Scope = nullptr;
1899     if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1900       Scope = LScopes.findLexicalScope(DV->getScope());
1901     } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1902       Scope = LScopes.findLexicalScope(DL->getScope());
1903     }
1904 
1905     if (Scope)
1906       createConcreteEntity(TheCU, *Scope, DN, nullptr);
1907   }
1908 }
1909 
1910 // Process beginning of an instruction.
1911 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1912   const MachineFunction &MF = *MI->getMF();
1913   const auto *SP = MF.getFunction().getSubprogram();
1914   bool NoDebug =
1915       !SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug;
1916 
1917   // Delay slot support check.
1918   auto delaySlotSupported = [](const MachineInstr &MI) {
1919     if (!MI.isBundledWithSucc())
1920       return false;
1921     auto Suc = std::next(MI.getIterator());
1922     (void)Suc;
1923     // Ensure that delay slot instruction is successor of the call instruction.
1924     // Ex. CALL_INSTRUCTION {
1925     //        DELAY_SLOT_INSTRUCTION }
1926     assert(Suc->isBundledWithPred() &&
1927            "Call bundle instructions are out of order");
1928     return true;
1929   };
1930 
1931   // When describing calls, we need a label for the call instruction.
1932   if (!NoDebug && SP->areAllCallsDescribed() &&
1933       MI->isCandidateForCallSiteEntry(MachineInstr::AnyInBundle) &&
1934       (!MI->hasDelaySlot() || delaySlotSupported(*MI))) {
1935     const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
1936     bool IsTail = TII->isTailCall(*MI);
1937     // For tail calls, we need the address of the branch instruction for
1938     // DW_AT_call_pc.
1939     if (IsTail)
1940       requestLabelBeforeInsn(MI);
1941     // For non-tail calls, we need the return address for the call for
1942     // DW_AT_call_return_pc. Under GDB tuning, this information is needed for
1943     // tail calls as well.
1944     requestLabelAfterInsn(MI);
1945   }
1946 
1947   DebugHandlerBase::beginInstruction(MI);
1948   assert(CurMI);
1949 
1950   if (NoDebug)
1951     return;
1952 
1953   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1954   // If the instruction is part of the function frame setup code, do not emit
1955   // any line record, as there is no correspondence with any user code.
1956   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1957     return;
1958   const DebugLoc &DL = MI->getDebugLoc();
1959   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1960   // the last line number actually emitted, to see if it was line 0.
1961   unsigned LastAsmLine =
1962       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1963 
1964   if (DL == PrevInstLoc) {
1965     // If we have an ongoing unspecified location, nothing to do here.
1966     if (!DL)
1967       return;
1968     // We have an explicit location, same as the previous location.
1969     // But we might be coming back to it after a line 0 record.
1970     if (LastAsmLine == 0 && DL.getLine() != 0) {
1971       // Reinstate the source location but not marked as a statement.
1972       const MDNode *Scope = DL.getScope();
1973       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1974     }
1975     return;
1976   }
1977 
1978   if (!DL) {
1979     // We have an unspecified location, which might want to be line 0.
1980     // If we have already emitted a line-0 record, don't repeat it.
1981     if (LastAsmLine == 0)
1982       return;
1983     // If user said Don't Do That, don't do that.
1984     if (UnknownLocations == Disable)
1985       return;
1986     // See if we have a reason to emit a line-0 record now.
1987     // Reasons to emit a line-0 record include:
1988     // - User asked for it (UnknownLocations).
1989     // - Instruction has a label, so it's referenced from somewhere else,
1990     //   possibly debug information; we want it to have a source location.
1991     // - Instruction is at the top of a block; we don't want to inherit the
1992     //   location from the physically previous (maybe unrelated) block.
1993     if (UnknownLocations == Enable || PrevLabel ||
1994         (PrevInstBB && PrevInstBB != MI->getParent())) {
1995       // Preserve the file and column numbers, if we can, to save space in
1996       // the encoded line table.
1997       // Do not update PrevInstLoc, it remembers the last non-0 line.
1998       const MDNode *Scope = nullptr;
1999       unsigned Column = 0;
2000       if (PrevInstLoc) {
2001         Scope = PrevInstLoc.getScope();
2002         Column = PrevInstLoc.getCol();
2003       }
2004       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
2005     }
2006     return;
2007   }
2008 
2009   // We have an explicit location, different from the previous location.
2010   // Don't repeat a line-0 record, but otherwise emit the new location.
2011   // (The new location might be an explicit line 0, which we do emit.)
2012   if (DL.getLine() == 0 && LastAsmLine == 0)
2013     return;
2014   unsigned Flags = 0;
2015   if (DL == PrologEndLoc) {
2016     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
2017     PrologEndLoc = DebugLoc();
2018   }
2019   // If the line changed, we call that a new statement; unless we went to
2020   // line 0 and came back, in which case it is not a new statement.
2021   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
2022   if (DL.getLine() && DL.getLine() != OldLine)
2023     Flags |= DWARF2_FLAG_IS_STMT;
2024 
2025   const MDNode *Scope = DL.getScope();
2026   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
2027 
2028   // If we're not at line 0, remember this location.
2029   if (DL.getLine())
2030     PrevInstLoc = DL;
2031 }
2032 
2033 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
2034   // First known non-DBG_VALUE and non-frame setup location marks
2035   // the beginning of the function body.
2036   for (const auto &MBB : *MF)
2037     for (const auto &MI : MBB)
2038       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
2039           MI.getDebugLoc())
2040         return MI.getDebugLoc();
2041   return DebugLoc();
2042 }
2043 
2044 /// Register a source line with debug info. Returns the  unique label that was
2045 /// emitted and which provides correspondence to the source line list.
2046 static void recordSourceLine(AsmPrinter &Asm, unsigned Line, unsigned Col,
2047                              const MDNode *S, unsigned Flags, unsigned CUID,
2048                              uint16_t DwarfVersion,
2049                              ArrayRef<std::unique_ptr<DwarfCompileUnit>> DCUs) {
2050   StringRef Fn;
2051   unsigned FileNo = 1;
2052   unsigned Discriminator = 0;
2053   if (auto *Scope = cast_or_null<DIScope>(S)) {
2054     Fn = Scope->getFilename();
2055     if (Line != 0 && DwarfVersion >= 4)
2056       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
2057         Discriminator = LBF->getDiscriminator();
2058 
2059     FileNo = static_cast<DwarfCompileUnit &>(*DCUs[CUID])
2060                  .getOrCreateSourceID(Scope->getFile());
2061   }
2062   Asm.OutStreamer->emitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
2063                                          Discriminator, Fn);
2064 }
2065 
2066 DebugLoc DwarfDebug::emitInitialLocDirective(const MachineFunction &MF,
2067                                              unsigned CUID) {
2068   // Get beginning of function.
2069   if (DebugLoc PrologEndLoc = findPrologueEndLoc(&MF)) {
2070     // Ensure the compile unit is created if the function is called before
2071     // beginFunction().
2072     (void)getOrCreateDwarfCompileUnit(
2073         MF.getFunction().getSubprogram()->getUnit());
2074     // We'd like to list the prologue as "not statements" but GDB behaves
2075     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
2076     const DISubprogram *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
2077     ::recordSourceLine(*Asm, SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT,
2078                        CUID, getDwarfVersion(), getUnits());
2079     return PrologEndLoc;
2080   }
2081   return DebugLoc();
2082 }
2083 
2084 // Gather pre-function debug information.  Assumes being called immediately
2085 // after the function entry point has been emitted.
2086 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
2087   CurFn = MF;
2088 
2089   auto *SP = MF->getFunction().getSubprogram();
2090   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
2091   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
2092     return;
2093 
2094   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
2095 
2096   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
2097   // belongs to so that we add to the correct per-cu line table in the
2098   // non-asm case.
2099   if (Asm->OutStreamer->hasRawTextSupport())
2100     // Use a single line table if we are generating assembly.
2101     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2102   else
2103     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
2104 
2105   // Record beginning of function.
2106   PrologEndLoc = emitInitialLocDirective(
2107       *MF, Asm->OutStreamer->getContext().getDwarfCompileUnitID());
2108 }
2109 
2110 void DwarfDebug::skippedNonDebugFunction() {
2111   // If we don't have a subprogram for this function then there will be a hole
2112   // in the range information. Keep note of this by setting the previously used
2113   // section to nullptr.
2114   PrevCU = nullptr;
2115   CurFn = nullptr;
2116 }
2117 
2118 // Gather and emit post-function debug information.
2119 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
2120   const DISubprogram *SP = MF->getFunction().getSubprogram();
2121 
2122   assert(CurFn == MF &&
2123       "endFunction should be called with the same function as beginFunction");
2124 
2125   // Set DwarfDwarfCompileUnitID in MCContext to default value.
2126   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
2127 
2128   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
2129   assert(!FnScope || SP == FnScope->getScopeNode());
2130   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
2131   if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
2132     PrevLabel = nullptr;
2133     CurFn = nullptr;
2134     return;
2135   }
2136 
2137   DenseSet<InlinedEntity> Processed;
2138   collectEntityInfo(TheCU, SP, Processed);
2139 
2140   // Add the range of this function to the list of ranges for the CU.
2141   // With basic block sections, add ranges for all basic block sections.
2142   for (const auto &R : Asm->MBBSectionRanges)
2143     TheCU.addRange({R.second.BeginLabel, R.second.EndLabel});
2144 
2145   // Under -gmlt, skip building the subprogram if there are no inlined
2146   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
2147   // is still needed as we need its source location.
2148   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
2149       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
2150       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
2151     assert(InfoHolder.getScopeVariables().empty());
2152     PrevLabel = nullptr;
2153     CurFn = nullptr;
2154     return;
2155   }
2156 
2157 #ifndef NDEBUG
2158   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
2159 #endif
2160   // Construct abstract scopes.
2161   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
2162     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
2163     for (const DINode *DN : SP->getRetainedNodes()) {
2164       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
2165         continue;
2166 
2167       const MDNode *Scope = nullptr;
2168       if (auto *DV = dyn_cast<DILocalVariable>(DN))
2169         Scope = DV->getScope();
2170       else if (auto *DL = dyn_cast<DILabel>(DN))
2171         Scope = DL->getScope();
2172       else
2173         llvm_unreachable("Unexpected DI type!");
2174 
2175       // Collect info for variables/labels that were optimized out.
2176       ensureAbstractEntityIsCreated(TheCU, DN, Scope);
2177       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
2178              && "ensureAbstractEntityIsCreated inserted abstract scopes");
2179     }
2180     constructAbstractSubprogramScopeDIE(TheCU, AScope);
2181   }
2182 
2183   ProcessedSPNodes.insert(SP);
2184   DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
2185   if (auto *SkelCU = TheCU.getSkeleton())
2186     if (!LScopes.getAbstractScopesList().empty() &&
2187         TheCU.getCUNode()->getSplitDebugInlining())
2188       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
2189 
2190   // Construct call site entries.
2191   constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
2192 
2193   // Clear debug info
2194   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
2195   // DbgVariables except those that are also in AbstractVariables (since they
2196   // can be used cross-function)
2197   InfoHolder.getScopeVariables().clear();
2198   InfoHolder.getScopeLabels().clear();
2199   PrevLabel = nullptr;
2200   CurFn = nullptr;
2201 }
2202 
2203 // Register a source line with debug info. Returns the  unique label that was
2204 // emitted and which provides correspondence to the source line list.
2205 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
2206                                   unsigned Flags) {
2207   ::recordSourceLine(*Asm, Line, Col, S, Flags,
2208                      Asm->OutStreamer->getContext().getDwarfCompileUnitID(),
2209                      getDwarfVersion(), getUnits());
2210 }
2211 
2212 //===----------------------------------------------------------------------===//
2213 // Emit Methods
2214 //===----------------------------------------------------------------------===//
2215 
2216 // Emit the debug info section.
2217 void DwarfDebug::emitDebugInfo() {
2218   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2219   Holder.emitUnits(/* UseOffsets */ false);
2220 }
2221 
2222 // Emit the abbreviation section.
2223 void DwarfDebug::emitAbbreviations() {
2224   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2225 
2226   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
2227 }
2228 
2229 void DwarfDebug::emitStringOffsetsTableHeader() {
2230   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2231   Holder.getStringPool().emitStringOffsetsTableHeader(
2232       *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
2233       Holder.getStringOffsetsStartSym());
2234 }
2235 
2236 template <typename AccelTableT>
2237 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
2238                            StringRef TableName) {
2239   Asm->OutStreamer->SwitchSection(Section);
2240 
2241   // Emit the full data.
2242   emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
2243 }
2244 
2245 void DwarfDebug::emitAccelDebugNames() {
2246   // Don't emit anything if we have no compilation units to index.
2247   if (getUnits().empty())
2248     return;
2249 
2250   emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
2251 }
2252 
2253 // Emit visible names into a hashed accelerator table section.
2254 void DwarfDebug::emitAccelNames() {
2255   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
2256             "Names");
2257 }
2258 
2259 // Emit objective C classes and categories into a hashed accelerator table
2260 // section.
2261 void DwarfDebug::emitAccelObjC() {
2262   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
2263             "ObjC");
2264 }
2265 
2266 // Emit namespace dies into a hashed accelerator table.
2267 void DwarfDebug::emitAccelNamespaces() {
2268   emitAccel(AccelNamespace,
2269             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
2270             "namespac");
2271 }
2272 
2273 // Emit type dies into a hashed accelerator table.
2274 void DwarfDebug::emitAccelTypes() {
2275   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
2276             "types");
2277 }
2278 
2279 // Public name handling.
2280 // The format for the various pubnames:
2281 //
2282 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2283 // for the DIE that is named.
2284 //
2285 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2286 // into the CU and the index value is computed according to the type of value
2287 // for the DIE that is named.
2288 //
2289 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2290 // it's the offset within the debug_info/debug_types dwo section, however, the
2291 // reference in the pubname header doesn't change.
2292 
2293 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2294 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2295                                                         const DIE *Die) {
2296   // Entities that ended up only in a Type Unit reference the CU instead (since
2297   // the pub entry has offsets within the CU there's no real offset that can be
2298   // provided anyway). As it happens all such entities (namespaces and types,
2299   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
2300   // not to be true it would be necessary to persist this information from the
2301   // point at which the entry is added to the index data structure - since by
2302   // the time the index is built from that, the original type/namespace DIE in a
2303   // type unit has already been destroyed so it can't be queried for properties
2304   // like tag, etc.
2305   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
2306     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
2307                                           dwarf::GIEL_EXTERNAL);
2308   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2309 
2310   // We could have a specification DIE that has our most of our knowledge,
2311   // look for that now.
2312   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
2313     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
2314     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
2315       Linkage = dwarf::GIEL_EXTERNAL;
2316   } else if (Die->findAttribute(dwarf::DW_AT_external))
2317     Linkage = dwarf::GIEL_EXTERNAL;
2318 
2319   switch (Die->getTag()) {
2320   case dwarf::DW_TAG_class_type:
2321   case dwarf::DW_TAG_structure_type:
2322   case dwarf::DW_TAG_union_type:
2323   case dwarf::DW_TAG_enumeration_type:
2324     return dwarf::PubIndexEntryDescriptor(
2325         dwarf::GIEK_TYPE,
2326         dwarf::isCPlusPlus((dwarf::SourceLanguage)CU->getLanguage())
2327             ? dwarf::GIEL_EXTERNAL
2328             : dwarf::GIEL_STATIC);
2329   case dwarf::DW_TAG_typedef:
2330   case dwarf::DW_TAG_base_type:
2331   case dwarf::DW_TAG_subrange_type:
2332     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2333   case dwarf::DW_TAG_namespace:
2334     return dwarf::GIEK_TYPE;
2335   case dwarf::DW_TAG_subprogram:
2336     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2337   case dwarf::DW_TAG_variable:
2338     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2339   case dwarf::DW_TAG_enumerator:
2340     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2341                                           dwarf::GIEL_STATIC);
2342   default:
2343     return dwarf::GIEK_NONE;
2344   }
2345 }
2346 
2347 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
2348 /// pubtypes sections.
2349 void DwarfDebug::emitDebugPubSections() {
2350   for (const auto &NU : CUMap) {
2351     DwarfCompileUnit *TheU = NU.second;
2352     if (!TheU->hasDwarfPubSections())
2353       continue;
2354 
2355     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
2356                     DICompileUnit::DebugNameTableKind::GNU;
2357 
2358     Asm->OutStreamer->SwitchSection(
2359         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2360                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
2361     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
2362 
2363     Asm->OutStreamer->SwitchSection(
2364         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2365                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
2366     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
2367   }
2368 }
2369 
2370 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
2371   if (useSectionsAsReferences())
2372     Asm->emitDwarfOffset(CU.getSection()->getBeginSymbol(),
2373                          CU.getDebugSectionOffset());
2374   else
2375     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
2376 }
2377 
2378 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
2379                                      DwarfCompileUnit *TheU,
2380                                      const StringMap<const DIE *> &Globals) {
2381   if (auto *Skeleton = TheU->getSkeleton())
2382     TheU = Skeleton;
2383 
2384   // Emit the header.
2385   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
2386   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
2387   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
2388   Asm->emitLabelDifference(EndLabel, BeginLabel, 4);
2389 
2390   Asm->OutStreamer->emitLabel(BeginLabel);
2391 
2392   Asm->OutStreamer->AddComment("DWARF Version");
2393   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
2394 
2395   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
2396   emitSectionReference(*TheU);
2397 
2398   Asm->OutStreamer->AddComment("Compilation Unit Length");
2399   Asm->emitInt32(TheU->getLength());
2400 
2401   // Emit the pubnames for this compilation unit.
2402   for (const auto &GI : Globals) {
2403     const char *Name = GI.getKeyData();
2404     const DIE *Entity = GI.second;
2405 
2406     Asm->OutStreamer->AddComment("DIE offset");
2407     Asm->emitInt32(Entity->getOffset());
2408 
2409     if (GnuStyle) {
2410       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2411       Asm->OutStreamer->AddComment(
2412           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
2413           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2414       Asm->emitInt8(Desc.toBits());
2415     }
2416 
2417     Asm->OutStreamer->AddComment("External Name");
2418     Asm->OutStreamer->emitBytes(StringRef(Name, GI.getKeyLength() + 1));
2419   }
2420 
2421   Asm->OutStreamer->AddComment("End Mark");
2422   Asm->emitInt32(0);
2423   Asm->OutStreamer->emitLabel(EndLabel);
2424 }
2425 
2426 /// Emit null-terminated strings into a debug str section.
2427 void DwarfDebug::emitDebugStr() {
2428   MCSection *StringOffsetsSection = nullptr;
2429   if (useSegmentedStringOffsetsTable()) {
2430     emitStringOffsetsTableHeader();
2431     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
2432   }
2433   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2434   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
2435                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
2436 }
2437 
2438 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2439                                    const DebugLocStream::Entry &Entry,
2440                                    const DwarfCompileUnit *CU) {
2441   auto &&Comments = DebugLocs.getComments(Entry);
2442   auto Comment = Comments.begin();
2443   auto End = Comments.end();
2444 
2445   // The expressions are inserted into a byte stream rather early (see
2446   // DwarfExpression::addExpression) so for those ops (e.g. DW_OP_convert) that
2447   // need to reference a base_type DIE the offset of that DIE is not yet known.
2448   // To deal with this we instead insert a placeholder early and then extract
2449   // it here and replace it with the real reference.
2450   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2451   DWARFDataExtractor Data(StringRef(DebugLocs.getBytes(Entry).data(),
2452                                     DebugLocs.getBytes(Entry).size()),
2453                           Asm->getDataLayout().isLittleEndian(), PtrSize);
2454   DWARFExpression Expr(Data, PtrSize, Asm->OutContext.getDwarfFormat());
2455 
2456   using Encoding = DWARFExpression::Operation::Encoding;
2457   uint64_t Offset = 0;
2458   for (auto &Op : Expr) {
2459     assert(Op.getCode() != dwarf::DW_OP_const_type &&
2460            "3 operand ops not yet supported");
2461     Streamer.EmitInt8(Op.getCode(), Comment != End ? *(Comment++) : "");
2462     Offset++;
2463     for (unsigned I = 0; I < 2; ++I) {
2464       if (Op.getDescription().Op[I] == Encoding::SizeNA)
2465         continue;
2466       if (Op.getDescription().Op[I] == Encoding::BaseTypeRef) {
2467         uint64_t Offset =
2468             CU->ExprRefedBaseTypes[Op.getRawOperand(I)].Die->getOffset();
2469         assert(Offset < (1ULL << (ULEB128PadSize * 7)) && "Offset wont fit");
2470         Streamer.emitULEB128(Offset, "", ULEB128PadSize);
2471         // Make sure comments stay aligned.
2472         for (unsigned J = 0; J < ULEB128PadSize; ++J)
2473           if (Comment != End)
2474             Comment++;
2475       } else {
2476         for (uint64_t J = Offset; J < Op.getOperandEndOffset(I); ++J)
2477           Streamer.EmitInt8(Data.getData()[J], Comment != End ? *(Comment++) : "");
2478       }
2479       Offset = Op.getOperandEndOffset(I);
2480     }
2481     assert(Offset == Op.getEndOffset());
2482   }
2483 }
2484 
2485 void DwarfDebug::emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
2486                                    const DbgValueLoc &Value,
2487                                    DwarfExpression &DwarfExpr) {
2488   auto *DIExpr = Value.getExpression();
2489   DIExpressionCursor ExprCursor(DIExpr);
2490   DwarfExpr.addFragmentOffset(DIExpr);
2491   // Regular entry.
2492   if (Value.isInt()) {
2493     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
2494                BT->getEncoding() == dwarf::DW_ATE_signed_char))
2495       DwarfExpr.addSignedConstant(Value.getInt());
2496     else
2497       DwarfExpr.addUnsignedConstant(Value.getInt());
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   } else if (Value.isConstantFP()) {
2516     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
2517     DwarfExpr.addUnsignedConstant(RawBytes);
2518   }
2519   DwarfExpr.addExpression(std::move(ExprCursor));
2520 }
2521 
2522 void DebugLocEntry::finalize(const AsmPrinter &AP,
2523                              DebugLocStream::ListBuilder &List,
2524                              const DIBasicType *BT,
2525                              DwarfCompileUnit &TheCU) {
2526   assert(!Values.empty() &&
2527          "location list entries without values are redundant");
2528   assert(Begin != End && "unexpected location list entry with empty range");
2529   DebugLocStream::EntryBuilder Entry(List, Begin, End);
2530   BufferByteStreamer Streamer = Entry.getStreamer();
2531   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer, TheCU);
2532   const DbgValueLoc &Value = Values[0];
2533   if (Value.isFragment()) {
2534     // Emit all fragments that belong to the same variable and range.
2535     assert(llvm::all_of(Values, [](DbgValueLoc P) {
2536           return P.isFragment();
2537         }) && "all values are expected to be fragments");
2538     assert(llvm::is_sorted(Values) && "fragments are expected to be sorted");
2539 
2540     for (auto Fragment : Values)
2541       DwarfDebug::emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
2542 
2543   } else {
2544     assert(Values.size() == 1 && "only fragments may have >1 value");
2545     DwarfDebug::emitDebugLocValue(AP, BT, Value, DwarfExpr);
2546   }
2547   DwarfExpr.finalize();
2548   if (DwarfExpr.TagOffset)
2549     List.setTagOffset(*DwarfExpr.TagOffset);
2550 }
2551 
2552 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry,
2553                                            const DwarfCompileUnit *CU) {
2554   // Emit the size.
2555   Asm->OutStreamer->AddComment("Loc expr size");
2556   if (getDwarfVersion() >= 5)
2557     Asm->emitULEB128(DebugLocs.getBytes(Entry).size());
2558   else if (DebugLocs.getBytes(Entry).size() <= std::numeric_limits<uint16_t>::max())
2559     Asm->emitInt16(DebugLocs.getBytes(Entry).size());
2560   else {
2561     // The entry is too big to fit into 16 bit, drop it as there is nothing we
2562     // can do.
2563     Asm->emitInt16(0);
2564     return;
2565   }
2566   // Emit the entry.
2567   APByteStreamer Streamer(*Asm);
2568   emitDebugLocEntry(Streamer, Entry, CU);
2569 }
2570 
2571 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
2572 // that designates the end of the table for the caller to emit when the table is
2573 // complete.
2574 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
2575                                          const DwarfFile &Holder) {
2576   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2577 
2578   Asm->OutStreamer->AddComment("Offset entry count");
2579   Asm->emitInt32(Holder.getRangeLists().size());
2580   Asm->OutStreamer->emitLabel(Holder.getRnglistsTableBaseSym());
2581 
2582   for (const RangeSpanList &List : Holder.getRangeLists())
2583     Asm->emitLabelDifference(List.Label, Holder.getRnglistsTableBaseSym(), 4);
2584 
2585   return TableEnd;
2586 }
2587 
2588 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2589 // designates the end of the table for the caller to emit when the table is
2590 // complete.
2591 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2592                                          const DwarfDebug &DD) {
2593   MCSymbol *TableEnd = mcdwarf::emitListsTableHeaderStart(*Asm->OutStreamer);
2594 
2595   const auto &DebugLocs = DD.getDebugLocs();
2596 
2597   Asm->OutStreamer->AddComment("Offset entry count");
2598   Asm->emitInt32(DebugLocs.getLists().size());
2599   Asm->OutStreamer->emitLabel(DebugLocs.getSym());
2600 
2601   for (const auto &List : DebugLocs.getLists())
2602     Asm->emitLabelDifference(List.Label, DebugLocs.getSym(), 4);
2603 
2604   return TableEnd;
2605 }
2606 
2607 template <typename Ranges, typename PayloadEmitter>
2608 static void emitRangeList(
2609     DwarfDebug &DD, AsmPrinter *Asm, MCSymbol *Sym, const Ranges &R,
2610     const DwarfCompileUnit &CU, unsigned BaseAddressx, unsigned OffsetPair,
2611     unsigned StartxLength, unsigned EndOfList,
2612     StringRef (*StringifyEnum)(unsigned),
2613     bool ShouldUseBaseAddress,
2614     PayloadEmitter EmitPayload) {
2615 
2616   auto Size = Asm->MAI->getCodePointerSize();
2617   bool UseDwarf5 = DD.getDwarfVersion() >= 5;
2618 
2619   // Emit our symbol so we can find the beginning of the range.
2620   Asm->OutStreamer->emitLabel(Sym);
2621 
2622   // Gather all the ranges that apply to the same section so they can share
2623   // a base address entry.
2624   MapVector<const MCSection *, std::vector<decltype(&*R.begin())>> SectionRanges;
2625 
2626   for (const auto &Range : R)
2627     SectionRanges[&Range.Begin->getSection()].push_back(&Range);
2628 
2629   const MCSymbol *CUBase = CU.getBaseAddress();
2630   bool BaseIsSet = false;
2631   for (const auto &P : SectionRanges) {
2632     auto *Base = CUBase;
2633     if (!Base && ShouldUseBaseAddress) {
2634       const MCSymbol *Begin = P.second.front()->Begin;
2635       const MCSymbol *NewBase = DD.getSectionLabel(&Begin->getSection());
2636       if (!UseDwarf5) {
2637         Base = NewBase;
2638         BaseIsSet = true;
2639         Asm->OutStreamer->emitIntValue(-1, Size);
2640         Asm->OutStreamer->AddComment("  base address");
2641         Asm->OutStreamer->emitSymbolValue(Base, Size);
2642       } else if (NewBase != Begin || P.second.size() > 1) {
2643         // Only use a base address if
2644         //  * the existing pool address doesn't match (NewBase != Begin)
2645         //  * or, there's more than one entry to share the base address
2646         Base = NewBase;
2647         BaseIsSet = true;
2648         Asm->OutStreamer->AddComment(StringifyEnum(BaseAddressx));
2649         Asm->emitInt8(BaseAddressx);
2650         Asm->OutStreamer->AddComment("  base address index");
2651         Asm->emitULEB128(DD.getAddressPool().getIndex(Base));
2652       }
2653     } else if (BaseIsSet && !UseDwarf5) {
2654       BaseIsSet = false;
2655       assert(!Base);
2656       Asm->OutStreamer->emitIntValue(-1, Size);
2657       Asm->OutStreamer->emitIntValue(0, Size);
2658     }
2659 
2660     for (const auto *RS : P.second) {
2661       const MCSymbol *Begin = RS->Begin;
2662       const MCSymbol *End = RS->End;
2663       assert(Begin && "Range without a begin symbol?");
2664       assert(End && "Range without an end symbol?");
2665       if (Base) {
2666         if (UseDwarf5) {
2667           // Emit offset_pair when we have a base.
2668           Asm->OutStreamer->AddComment(StringifyEnum(OffsetPair));
2669           Asm->emitInt8(OffsetPair);
2670           Asm->OutStreamer->AddComment("  starting offset");
2671           Asm->emitLabelDifferenceAsULEB128(Begin, Base);
2672           Asm->OutStreamer->AddComment("  ending offset");
2673           Asm->emitLabelDifferenceAsULEB128(End, Base);
2674         } else {
2675           Asm->emitLabelDifference(Begin, Base, Size);
2676           Asm->emitLabelDifference(End, Base, Size);
2677         }
2678       } else if (UseDwarf5) {
2679         Asm->OutStreamer->AddComment(StringifyEnum(StartxLength));
2680         Asm->emitInt8(StartxLength);
2681         Asm->OutStreamer->AddComment("  start index");
2682         Asm->emitULEB128(DD.getAddressPool().getIndex(Begin));
2683         Asm->OutStreamer->AddComment("  length");
2684         Asm->emitLabelDifferenceAsULEB128(End, Begin);
2685       } else {
2686         Asm->OutStreamer->emitSymbolValue(Begin, Size);
2687         Asm->OutStreamer->emitSymbolValue(End, Size);
2688       }
2689       EmitPayload(*RS);
2690     }
2691   }
2692 
2693   if (UseDwarf5) {
2694     Asm->OutStreamer->AddComment(StringifyEnum(EndOfList));
2695     Asm->emitInt8(EndOfList);
2696   } else {
2697     // Terminate the list with two 0 values.
2698     Asm->OutStreamer->emitIntValue(0, Size);
2699     Asm->OutStreamer->emitIntValue(0, Size);
2700   }
2701 }
2702 
2703 // Handles emission of both debug_loclist / debug_loclist.dwo
2704 static void emitLocList(DwarfDebug &DD, AsmPrinter *Asm, const DebugLocStream::List &List) {
2705   emitRangeList(DD, Asm, List.Label, DD.getDebugLocs().getEntries(List),
2706                 *List.CU, dwarf::DW_LLE_base_addressx,
2707                 dwarf::DW_LLE_offset_pair, dwarf::DW_LLE_startx_length,
2708                 dwarf::DW_LLE_end_of_list, llvm::dwarf::LocListEncodingString,
2709                 /* ShouldUseBaseAddress */ true,
2710                 [&](const DebugLocStream::Entry &E) {
2711                   DD.emitDebugLocEntryLocation(E, List.CU);
2712                 });
2713 }
2714 
2715 void DwarfDebug::emitDebugLocImpl(MCSection *Sec) {
2716   if (DebugLocs.getLists().empty())
2717     return;
2718 
2719   Asm->OutStreamer->SwitchSection(Sec);
2720 
2721   MCSymbol *TableEnd = nullptr;
2722   if (getDwarfVersion() >= 5)
2723     TableEnd = emitLoclistsTableHeader(Asm, *this);
2724 
2725   for (const auto &List : DebugLocs.getLists())
2726     emitLocList(*this, Asm, List);
2727 
2728   if (TableEnd)
2729     Asm->OutStreamer->emitLabel(TableEnd);
2730 }
2731 
2732 // Emit locations into the .debug_loc/.debug_loclists section.
2733 void DwarfDebug::emitDebugLoc() {
2734   emitDebugLocImpl(
2735       getDwarfVersion() >= 5
2736           ? Asm->getObjFileLowering().getDwarfLoclistsSection()
2737           : Asm->getObjFileLowering().getDwarfLocSection());
2738 }
2739 
2740 // Emit locations into the .debug_loc.dwo/.debug_loclists.dwo section.
2741 void DwarfDebug::emitDebugLocDWO() {
2742   if (getDwarfVersion() >= 5) {
2743     emitDebugLocImpl(
2744         Asm->getObjFileLowering().getDwarfLoclistsDWOSection());
2745 
2746     return;
2747   }
2748 
2749   for (const auto &List : DebugLocs.getLists()) {
2750     Asm->OutStreamer->SwitchSection(
2751         Asm->getObjFileLowering().getDwarfLocDWOSection());
2752     Asm->OutStreamer->emitLabel(List.Label);
2753 
2754     for (const auto &Entry : DebugLocs.getEntries(List)) {
2755       // GDB only supports startx_length in pre-standard split-DWARF.
2756       // (in v5 standard loclists, it currently* /only/ supports base_address +
2757       // offset_pair, so the implementations can't really share much since they
2758       // need to use different representations)
2759       // * as of October 2018, at least
2760       //
2761       // In v5 (see emitLocList), this uses SectionLabels to reuse existing
2762       // addresses in the address pool to minimize object size/relocations.
2763       Asm->emitInt8(dwarf::DW_LLE_startx_length);
2764       unsigned idx = AddrPool.getIndex(Entry.Begin);
2765       Asm->emitULEB128(idx);
2766       // Also the pre-standard encoding is slightly different, emitting this as
2767       // an address-length entry here, but its a ULEB128 in DWARFv5 loclists.
2768       Asm->emitLabelDifference(Entry.End, Entry.Begin, 4);
2769       emitDebugLocEntryLocation(Entry, List.CU);
2770     }
2771     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2772   }
2773 }
2774 
2775 struct ArangeSpan {
2776   const MCSymbol *Start, *End;
2777 };
2778 
2779 // Emit a debug aranges section, containing a CU lookup for any
2780 // address we can tie back to a CU.
2781 void DwarfDebug::emitDebugARanges() {
2782   // Provides a unique id per text section.
2783   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2784 
2785   // Filter labels by section.
2786   for (const SymbolCU &SCU : ArangeLabels) {
2787     if (SCU.Sym->isInSection()) {
2788       // Make a note of this symbol and it's section.
2789       MCSection *Section = &SCU.Sym->getSection();
2790       if (!Section->getKind().isMetadata())
2791         SectionMap[Section].push_back(SCU);
2792     } else {
2793       // Some symbols (e.g. common/bss on mach-o) can have no section but still
2794       // appear in the output. This sucks as we rely on sections to build
2795       // arange spans. We can do it without, but it's icky.
2796       SectionMap[nullptr].push_back(SCU);
2797     }
2798   }
2799 
2800   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2801 
2802   for (auto &I : SectionMap) {
2803     MCSection *Section = I.first;
2804     SmallVector<SymbolCU, 8> &List = I.second;
2805     if (List.size() < 1)
2806       continue;
2807 
2808     // If we have no section (e.g. common), just write out
2809     // individual spans for each symbol.
2810     if (!Section) {
2811       for (const SymbolCU &Cur : List) {
2812         ArangeSpan Span;
2813         Span.Start = Cur.Sym;
2814         Span.End = nullptr;
2815         assert(Cur.CU);
2816         Spans[Cur.CU].push_back(Span);
2817       }
2818       continue;
2819     }
2820 
2821     // Sort the symbols by offset within the section.
2822     llvm::stable_sort(List, [&](const SymbolCU &A, const SymbolCU &B) {
2823       unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2824       unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2825 
2826       // Symbols with no order assigned should be placed at the end.
2827       // (e.g. section end labels)
2828       if (IA == 0)
2829         return false;
2830       if (IB == 0)
2831         return true;
2832       return IA < IB;
2833     });
2834 
2835     // Insert a final terminator.
2836     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2837 
2838     // Build spans between each label.
2839     const MCSymbol *StartSym = List[0].Sym;
2840     for (size_t n = 1, e = List.size(); n < e; n++) {
2841       const SymbolCU &Prev = List[n - 1];
2842       const SymbolCU &Cur = List[n];
2843 
2844       // Try and build the longest span we can within the same CU.
2845       if (Cur.CU != Prev.CU) {
2846         ArangeSpan Span;
2847         Span.Start = StartSym;
2848         Span.End = Cur.Sym;
2849         assert(Prev.CU);
2850         Spans[Prev.CU].push_back(Span);
2851         StartSym = Cur.Sym;
2852       }
2853     }
2854   }
2855 
2856   // Start the dwarf aranges section.
2857   Asm->OutStreamer->SwitchSection(
2858       Asm->getObjFileLowering().getDwarfARangesSection());
2859 
2860   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2861 
2862   // Build a list of CUs used.
2863   std::vector<DwarfCompileUnit *> CUs;
2864   for (const auto &it : Spans) {
2865     DwarfCompileUnit *CU = it.first;
2866     CUs.push_back(CU);
2867   }
2868 
2869   // Sort the CU list (again, to ensure consistent output order).
2870   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2871     return A->getUniqueID() < B->getUniqueID();
2872   });
2873 
2874   // Emit an arange table for each CU we used.
2875   for (DwarfCompileUnit *CU : CUs) {
2876     std::vector<ArangeSpan> &List = Spans[CU];
2877 
2878     // Describe the skeleton CU's offset and length, not the dwo file's.
2879     if (auto *Skel = CU->getSkeleton())
2880       CU = Skel;
2881 
2882     // Emit size of content not including length itself.
2883     unsigned ContentSize =
2884         sizeof(int16_t) + // DWARF ARange version number
2885         sizeof(int32_t) + // Offset of CU in the .debug_info section
2886         sizeof(int8_t) +  // Pointer Size (in bytes)
2887         sizeof(int8_t);   // Segment Size (in bytes)
2888 
2889     unsigned TupleSize = PtrSize * 2;
2890 
2891     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2892     unsigned Padding =
2893         offsetToAlignment(sizeof(int32_t) + ContentSize, Align(TupleSize));
2894 
2895     ContentSize += Padding;
2896     ContentSize += (List.size() + 1) * TupleSize;
2897 
2898     // For each compile unit, write the list of spans it covers.
2899     Asm->OutStreamer->AddComment("Length of ARange Set");
2900     Asm->emitInt32(ContentSize);
2901     Asm->OutStreamer->AddComment("DWARF Arange version number");
2902     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2903     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2904     emitSectionReference(*CU);
2905     Asm->OutStreamer->AddComment("Address Size (in bytes)");
2906     Asm->emitInt8(PtrSize);
2907     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2908     Asm->emitInt8(0);
2909 
2910     Asm->OutStreamer->emitFill(Padding, 0xff);
2911 
2912     for (const ArangeSpan &Span : List) {
2913       Asm->emitLabelReference(Span.Start, PtrSize);
2914 
2915       // Calculate the size as being from the span start to it's end.
2916       if (Span.End) {
2917         Asm->emitLabelDifference(Span.End, Span.Start, PtrSize);
2918       } else {
2919         // For symbols without an end marker (e.g. common), we
2920         // write a single arange entry containing just that one symbol.
2921         uint64_t Size = SymSize[Span.Start];
2922         if (Size == 0)
2923           Size = 1;
2924 
2925         Asm->OutStreamer->emitIntValue(Size, PtrSize);
2926       }
2927     }
2928 
2929     Asm->OutStreamer->AddComment("ARange terminator");
2930     Asm->OutStreamer->emitIntValue(0, PtrSize);
2931     Asm->OutStreamer->emitIntValue(0, PtrSize);
2932   }
2933 }
2934 
2935 /// Emit a single range list. We handle both DWARF v5 and earlier.
2936 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2937                           const RangeSpanList &List) {
2938   emitRangeList(DD, Asm, List.Label, List.Ranges, *List.CU,
2939                 dwarf::DW_RLE_base_addressx, dwarf::DW_RLE_offset_pair,
2940                 dwarf::DW_RLE_startx_length, dwarf::DW_RLE_end_of_list,
2941                 llvm::dwarf::RangeListEncodingString,
2942                 List.CU->getCUNode()->getRangesBaseAddress() ||
2943                     DD.getDwarfVersion() >= 5,
2944                 [](auto) {});
2945 }
2946 
2947 void DwarfDebug::emitDebugRangesImpl(const DwarfFile &Holder, MCSection *Section) {
2948   if (Holder.getRangeLists().empty())
2949     return;
2950 
2951   assert(useRangesSection());
2952   assert(!CUMap.empty());
2953   assert(llvm::any_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2954     return !Pair.second->getCUNode()->isDebugDirectivesOnly();
2955   }));
2956 
2957   Asm->OutStreamer->SwitchSection(Section);
2958 
2959   MCSymbol *TableEnd = nullptr;
2960   if (getDwarfVersion() >= 5)
2961     TableEnd = emitRnglistsTableHeader(Asm, Holder);
2962 
2963   for (const RangeSpanList &List : Holder.getRangeLists())
2964     emitRangeList(*this, Asm, List);
2965 
2966   if (TableEnd)
2967     Asm->OutStreamer->emitLabel(TableEnd);
2968 }
2969 
2970 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2971 /// .debug_rnglists section.
2972 void DwarfDebug::emitDebugRanges() {
2973   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2974 
2975   emitDebugRangesImpl(Holder,
2976                       getDwarfVersion() >= 5
2977                           ? Asm->getObjFileLowering().getDwarfRnglistsSection()
2978                           : Asm->getObjFileLowering().getDwarfRangesSection());
2979 }
2980 
2981 void DwarfDebug::emitDebugRangesDWO() {
2982   emitDebugRangesImpl(InfoHolder,
2983                       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2984 }
2985 
2986 /// Emit the header of a DWARF 5 macro section.
2987 static void emitMacroHeader(AsmPrinter *Asm, const DwarfDebug &DD,
2988                             const DwarfCompileUnit &CU) {
2989   enum HeaderFlagMask {
2990 #define HANDLE_MACRO_FLAG(ID, NAME) MACRO_FLAG_##NAME = ID,
2991 #include "llvm/BinaryFormat/Dwarf.def"
2992   };
2993   uint8_t Flags = 0;
2994   Asm->OutStreamer->AddComment("Macro information version");
2995   Asm->emitInt16(5);
2996   // We are setting Offset and line offset flags unconditionally here,
2997   // since we're only supporting DWARF32 and line offset should be mostly
2998   // present.
2999   // FIXME: Add support for DWARF64.
3000   Flags |= MACRO_FLAG_DEBUG_LINE_OFFSET;
3001   Asm->OutStreamer->AddComment("Flags: 32 bit, debug_line_offset present");
3002   Asm->emitInt8(Flags);
3003   Asm->OutStreamer->AddComment("debug_line_offset");
3004   Asm->OutStreamer->emitSymbolValue(CU.getLineTableStartSym(), /*Size=*/4);
3005 }
3006 
3007 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
3008   for (auto *MN : Nodes) {
3009     if (auto *M = dyn_cast<DIMacro>(MN))
3010       emitMacro(*M);
3011     else if (auto *F = dyn_cast<DIMacroFile>(MN))
3012       emitMacroFile(*F, U);
3013     else
3014       llvm_unreachable("Unexpected DI type!");
3015   }
3016 }
3017 
3018 void DwarfDebug::emitMacro(DIMacro &M) {
3019   StringRef Name = M.getName();
3020   StringRef Value = M.getValue();
3021   bool UseMacro = getDwarfVersion() >= 5;
3022 
3023   if (UseMacro) {
3024     unsigned Type = M.getMacinfoType() == dwarf::DW_MACINFO_define
3025                         ? dwarf::DW_MACRO_define_strx
3026                         : dwarf::DW_MACRO_undef_strx;
3027     Asm->OutStreamer->AddComment(dwarf::MacroString(Type));
3028     Asm->emitULEB128(Type);
3029     Asm->OutStreamer->AddComment("Line Number");
3030     Asm->emitULEB128(M.getLine());
3031     Asm->OutStreamer->AddComment("Macro String");
3032     if (!Value.empty())
3033       Asm->emitULEB128(this->InfoHolder.getStringPool()
3034                            .getIndexedEntry(*Asm, (Name + " " + Value).str())
3035                            .getIndex());
3036     else
3037       // DW_MACRO_undef_strx doesn't have a value, so just emit the macro
3038       // string.
3039       Asm->emitULEB128(this->InfoHolder.getStringPool()
3040                            .getIndexedEntry(*Asm, (Name).str())
3041                            .getIndex());
3042   } else {
3043     Asm->OutStreamer->AddComment(dwarf::MacinfoString(M.getMacinfoType()));
3044     Asm->emitULEB128(M.getMacinfoType());
3045     Asm->OutStreamer->AddComment("Line Number");
3046     Asm->emitULEB128(M.getLine());
3047     Asm->OutStreamer->AddComment("Macro String");
3048     Asm->OutStreamer->emitBytes(Name);
3049     if (!Value.empty()) {
3050       // There should be one space between macro name and macro value.
3051       Asm->emitInt8(' ');
3052       Asm->OutStreamer->AddComment("Macro Value=");
3053       Asm->OutStreamer->emitBytes(Value);
3054     }
3055     Asm->emitInt8('\0');
3056   }
3057 }
3058 
3059 void DwarfDebug::emitMacroFileImpl(
3060     DIMacroFile &F, DwarfCompileUnit &U, unsigned StartFile, unsigned EndFile,
3061     StringRef (*MacroFormToString)(unsigned Form)) {
3062 
3063   Asm->OutStreamer->AddComment(MacroFormToString(StartFile));
3064   Asm->emitULEB128(StartFile);
3065   Asm->OutStreamer->AddComment("Line Number");
3066   Asm->emitULEB128(F.getLine());
3067   Asm->OutStreamer->AddComment("File Number");
3068   Asm->emitULEB128(U.getOrCreateSourceID(F.getFile()));
3069   handleMacroNodes(F.getElements(), U);
3070   Asm->OutStreamer->AddComment(MacroFormToString(EndFile));
3071   Asm->emitULEB128(EndFile);
3072 }
3073 
3074 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
3075   // DWARFv5 macro and DWARFv4 macinfo share some common encodings,
3076   // so for readibility/uniformity, We are explicitly emitting those.
3077   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
3078   bool UseMacro = getDwarfVersion() >= 5;
3079   if (UseMacro)
3080     emitMacroFileImpl(F, U, dwarf::DW_MACRO_start_file,
3081                       dwarf::DW_MACRO_end_file, dwarf::MacroString);
3082   else
3083     emitMacroFileImpl(F, U, dwarf::DW_MACINFO_start_file,
3084                       dwarf::DW_MACINFO_end_file, dwarf::MacinfoString);
3085 }
3086 
3087 void DwarfDebug::emitDebugMacinfoImpl(MCSection *Section) {
3088   for (const auto &P : CUMap) {
3089     auto &TheCU = *P.second;
3090     auto *SkCU = TheCU.getSkeleton();
3091     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
3092     auto *CUNode = cast<DICompileUnit>(P.first);
3093     DIMacroNodeArray Macros = CUNode->getMacros();
3094     if (Macros.empty())
3095       continue;
3096     Asm->OutStreamer->SwitchSection(Section);
3097     Asm->OutStreamer->emitLabel(U.getMacroLabelBegin());
3098     if (getDwarfVersion() >= 5)
3099       emitMacroHeader(Asm, *this, U);
3100     handleMacroNodes(Macros, U);
3101     Asm->OutStreamer->AddComment("End Of Macro List Mark");
3102     Asm->emitInt8(0);
3103   }
3104 }
3105 
3106 /// Emit macros into a debug macinfo/macro section.
3107 void DwarfDebug::emitDebugMacinfo() {
3108   auto &ObjLower = Asm->getObjFileLowering();
3109   emitDebugMacinfoImpl(getDwarfVersion() >= 5
3110                            ? ObjLower.getDwarfMacroSection()
3111                            : ObjLower.getDwarfMacinfoSection());
3112 }
3113 
3114 void DwarfDebug::emitDebugMacinfoDWO() {
3115   auto &ObjLower = Asm->getObjFileLowering();
3116   emitDebugMacinfoImpl(getDwarfVersion() >= 5
3117                            ? ObjLower.getDwarfMacroDWOSection()
3118                            : ObjLower.getDwarfMacinfoDWOSection());
3119 }
3120 
3121 // DWARF5 Experimental Separate Dwarf emitters.
3122 
3123 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
3124                                   std::unique_ptr<DwarfCompileUnit> NewU) {
3125 
3126   if (!CompilationDir.empty())
3127     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
3128   addGnuPubAttributes(*NewU, Die);
3129 
3130   SkeletonHolder.addUnit(std::move(NewU));
3131 }
3132 
3133 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
3134 
3135   auto OwnedUnit = std::make_unique<DwarfCompileUnit>(
3136       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder,
3137       UnitKind::Skeleton);
3138   DwarfCompileUnit &NewCU = *OwnedUnit;
3139   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
3140 
3141   NewCU.initStmtList();
3142 
3143   if (useSegmentedStringOffsetsTable())
3144     NewCU.addStringOffsetsStart();
3145 
3146   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
3147 
3148   return NewCU;
3149 }
3150 
3151 // Emit the .debug_info.dwo section for separated dwarf. This contains the
3152 // compile units that would normally be in debug_info.
3153 void DwarfDebug::emitDebugInfoDWO() {
3154   assert(useSplitDwarf() && "No split dwarf debug info?");
3155   // Don't emit relocations into the dwo file.
3156   InfoHolder.emitUnits(/* UseOffsets */ true);
3157 }
3158 
3159 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
3160 // abbreviations for the .debug_info.dwo section.
3161 void DwarfDebug::emitDebugAbbrevDWO() {
3162   assert(useSplitDwarf() && "No split dwarf?");
3163   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
3164 }
3165 
3166 void DwarfDebug::emitDebugLineDWO() {
3167   assert(useSplitDwarf() && "No split dwarf?");
3168   SplitTypeUnitFileTable.Emit(
3169       *Asm->OutStreamer, MCDwarfLineTableParams(),
3170       Asm->getObjFileLowering().getDwarfLineDWOSection());
3171 }
3172 
3173 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
3174   assert(useSplitDwarf() && "No split dwarf?");
3175   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
3176       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
3177       InfoHolder.getStringOffsetsStartSym());
3178 }
3179 
3180 // Emit the .debug_str.dwo section for separated dwarf. This contains the
3181 // string section and is identical in format to traditional .debug_str
3182 // sections.
3183 void DwarfDebug::emitDebugStrDWO() {
3184   if (useSegmentedStringOffsetsTable())
3185     emitStringOffsetsTableHeaderDWO();
3186   assert(useSplitDwarf() && "No split dwarf?");
3187   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
3188   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
3189                          OffSec, /* UseRelativeOffsets = */ false);
3190 }
3191 
3192 // Emit address pool.
3193 void DwarfDebug::emitDebugAddr() {
3194   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
3195 }
3196 
3197 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
3198   if (!useSplitDwarf())
3199     return nullptr;
3200   const DICompileUnit *DIUnit = CU.getCUNode();
3201   SplitTypeUnitFileTable.maybeSetRootFile(
3202       DIUnit->getDirectory(), DIUnit->getFilename(),
3203       CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
3204   return &SplitTypeUnitFileTable;
3205 }
3206 
3207 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
3208   MD5 Hash;
3209   Hash.update(Identifier);
3210   // ... take the least significant 8 bytes and return those. Our MD5
3211   // implementation always returns its results in little endian, so we actually
3212   // need the "high" word.
3213   MD5::MD5Result Result;
3214   Hash.final(Result);
3215   return Result.high();
3216 }
3217 
3218 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
3219                                       StringRef Identifier, DIE &RefDie,
3220                                       const DICompositeType *CTy) {
3221   // Fast path if we're building some type units and one has already used the
3222   // address pool we know we're going to throw away all this work anyway, so
3223   // don't bother building dependent types.
3224   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
3225     return;
3226 
3227   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
3228   if (!Ins.second) {
3229     CU.addDIETypeSignature(RefDie, Ins.first->second);
3230     return;
3231   }
3232 
3233   bool TopLevelType = TypeUnitsUnderConstruction.empty();
3234   AddrPool.resetUsedFlag();
3235 
3236   auto OwnedUnit = std::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
3237                                                     getDwoLineTable(CU));
3238   DwarfTypeUnit &NewTU = *OwnedUnit;
3239   DIE &UnitDie = NewTU.getUnitDie();
3240   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
3241 
3242   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
3243                 CU.getLanguage());
3244 
3245   uint64_t Signature = makeTypeSignature(Identifier);
3246   NewTU.setTypeSignature(Signature);
3247   Ins.first->second = Signature;
3248 
3249   if (useSplitDwarf()) {
3250     MCSection *Section =
3251         getDwarfVersion() <= 4
3252             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
3253             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
3254     NewTU.setSection(Section);
3255   } else {
3256     MCSection *Section =
3257         getDwarfVersion() <= 4
3258             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
3259             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
3260     NewTU.setSection(Section);
3261     // Non-split type units reuse the compile unit's line table.
3262     CU.applyStmtList(UnitDie);
3263   }
3264 
3265   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
3266   // units.
3267   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
3268     NewTU.addStringOffsetsStart();
3269 
3270   NewTU.setType(NewTU.createTypeDIE(CTy));
3271 
3272   if (TopLevelType) {
3273     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
3274     TypeUnitsUnderConstruction.clear();
3275 
3276     // Types referencing entries in the address table cannot be placed in type
3277     // units.
3278     if (AddrPool.hasBeenUsed()) {
3279 
3280       // Remove all the types built while building this type.
3281       // This is pessimistic as some of these types might not be dependent on
3282       // the type that used an address.
3283       for (const auto &TU : TypeUnitsToAdd)
3284         TypeSignatures.erase(TU.second);
3285 
3286       // Construct this type in the CU directly.
3287       // This is inefficient because all the dependent types will be rebuilt
3288       // from scratch, including building them in type units, discovering that
3289       // they depend on addresses, throwing them out and rebuilding them.
3290       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
3291       return;
3292     }
3293 
3294     // If the type wasn't dependent on fission addresses, finish adding the type
3295     // and all its dependent types.
3296     for (auto &TU : TypeUnitsToAdd) {
3297       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
3298       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
3299     }
3300   }
3301   CU.addDIETypeSignature(RefDie, Signature);
3302 }
3303 
3304 DwarfDebug::NonTypeUnitContext::NonTypeUnitContext(DwarfDebug *DD)
3305     : DD(DD),
3306       TypeUnitsUnderConstruction(std::move(DD->TypeUnitsUnderConstruction)) {
3307   DD->TypeUnitsUnderConstruction.clear();
3308   assert(TypeUnitsUnderConstruction.empty() || !DD->AddrPool.hasBeenUsed());
3309 }
3310 
3311 DwarfDebug::NonTypeUnitContext::~NonTypeUnitContext() {
3312   DD->TypeUnitsUnderConstruction = std::move(TypeUnitsUnderConstruction);
3313   DD->AddrPool.resetUsedFlag();
3314 }
3315 
3316 DwarfDebug::NonTypeUnitContext DwarfDebug::enterNonTypeUnitContext() {
3317   return NonTypeUnitContext(this);
3318 }
3319 
3320 // Add the Name along with its companion DIE to the appropriate accelerator
3321 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
3322 // AccelTableKind::Apple, we use the table we got as an argument). If
3323 // accelerator tables are disabled, this function does nothing.
3324 template <typename DataT>
3325 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
3326                                   AccelTable<DataT> &AppleAccel, StringRef Name,
3327                                   const DIE &Die) {
3328   if (getAccelTableKind() == AccelTableKind::None)
3329     return;
3330 
3331   if (getAccelTableKind() != AccelTableKind::Apple &&
3332       CU.getNameTableKind() != DICompileUnit::DebugNameTableKind::Default)
3333     return;
3334 
3335   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
3336   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
3337 
3338   switch (getAccelTableKind()) {
3339   case AccelTableKind::Apple:
3340     AppleAccel.addName(Ref, Die);
3341     break;
3342   case AccelTableKind::Dwarf:
3343     AccelDebugNames.addName(Ref, Die);
3344     break;
3345   case AccelTableKind::Default:
3346     llvm_unreachable("Default should have already been resolved.");
3347   case AccelTableKind::None:
3348     llvm_unreachable("None handled above");
3349   }
3350 }
3351 
3352 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
3353                               const DIE &Die) {
3354   addAccelNameImpl(CU, AccelNames, Name, Die);
3355 }
3356 
3357 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
3358                               const DIE &Die) {
3359   // ObjC names go only into the Apple accelerator tables.
3360   if (getAccelTableKind() == AccelTableKind::Apple)
3361     addAccelNameImpl(CU, AccelObjC, Name, Die);
3362 }
3363 
3364 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
3365                                    const DIE &Die) {
3366   addAccelNameImpl(CU, AccelNamespace, Name, Die);
3367 }
3368 
3369 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
3370                               const DIE &Die, char Flags) {
3371   addAccelNameImpl(CU, AccelTypes, Name, Die);
3372 }
3373 
3374 uint16_t DwarfDebug::getDwarfVersion() const {
3375   return Asm->OutStreamer->getContext().getDwarfVersion();
3376 }
3377 
3378 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
3379   return SectionLabels.find(S)->second;
3380 }
3381 void DwarfDebug::insertSectionLabel(const MCSymbol *S) {
3382   if (SectionLabels.insert(std::make_pair(&S->getSection(), S)).second)
3383     if (useSplitDwarf() || getDwarfVersion() >= 5)
3384       AddrPool.getIndex(S);
3385 }
3386