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