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