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