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