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