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