1 //===- llvm/CodeGen/DwarfDebug.cpp - Dwarf Debug Framework ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for writing dwarf debug info into asm files.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "DwarfDebug.h"
15 #include "ByteStreamer.h"
16 #include "DIEHash.h"
17 #include "DebugLocEntry.h"
18 #include "DebugLocStream.h"
19 #include "DwarfCompileUnit.h"
20 #include "DwarfExpression.h"
21 #include "DwarfFile.h"
22 #include "DwarfUnit.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringRef.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/TargetLoweringObjectFile.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCContext.h"
53 #include "llvm/MC/MCDwarf.h"
54 #include "llvm/MC/MCSection.h"
55 #include "llvm/MC/MCStreamer.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/MC/MCTargetOptions.h"
58 #include "llvm/MC/MachineLocation.h"
59 #include "llvm/MC/SectionKind.h"
60 #include "llvm/Pass.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/MD5.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Timer.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetMachine.h"
70 #include "llvm/Target/TargetOptions.h"
71 #include <algorithm>
72 #include <cassert>
73 #include <cstddef>
74 #include <cstdint>
75 #include <iterator>
76 #include <string>
77 #include <utility>
78 #include <vector>
79 
80 using namespace llvm;
81 
82 #define DEBUG_TYPE "dwarfdebug"
83 
84 static cl::opt<bool>
85 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
86                          cl::desc("Disable debug info printing"));
87 
88 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
89     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
90     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
91 
92 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
93                                            cl::Hidden,
94                                            cl::desc("Generate dwarf aranges"),
95                                            cl::init(false));
96 
97 static cl::opt<bool> SplitDwarfCrossCuReferences(
98     "split-dwarf-cross-cu-references", cl::Hidden,
99     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
100 
101 enum DefaultOnOff { Default, Enable, Disable };
102 
103 static cl::opt<DefaultOnOff> UnknownLocations(
104     "use-unknown-locations", cl::Hidden,
105     cl::desc("Make an absence of debug location information explicit."),
106     cl::values(clEnumVal(Default, "At top of block or after label"),
107                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
108     cl::init(Default));
109 
110 static cl::opt<DefaultOnOff>
111 DwarfAccelTables("dwarf-accel-tables", cl::Hidden,
112                  cl::desc("Output prototype dwarf accelerator tables."),
113                  cl::values(clEnumVal(Default, "Default for platform"),
114                             clEnumVal(Enable, "Enabled"),
115                             clEnumVal(Disable, "Disabled")),
116                  cl::init(Default));
117 
118 enum LinkageNameOption {
119   DefaultLinkageNames,
120   AllLinkageNames,
121   AbstractLinkageNames
122 };
123 
124 static cl::opt<LinkageNameOption>
125     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
126                       cl::desc("Which DWARF linkage-name attributes to emit."),
127                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
128                                             "Default for platform"),
129                                  clEnumValN(AllLinkageNames, "All", "All"),
130                                  clEnumValN(AbstractLinkageNames, "Abstract",
131                                             "Abstract subprograms")),
132                       cl::init(DefaultLinkageNames));
133 
134 static const char *const DWARFGroupName = "dwarf";
135 static const char *const DWARFGroupDescription = "DWARF Emission";
136 static const char *const DbgTimerName = "writer";
137 static const char *const DbgTimerDescription = "DWARF Debug Writer";
138 
139 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
140   BS.EmitInt8(
141       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
142                   : dwarf::OperationEncodingString(Op));
143 }
144 
145 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
146   BS.EmitSLEB128(Value, Twine(Value));
147 }
148 
149 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
150   BS.EmitULEB128(Value, Twine(Value));
151 }
152 
153 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
154                                               unsigned MachineReg) {
155   // This information is not available while emitting .debug_loc entries.
156   return false;
157 }
158 
159 bool DbgVariable::isBlockByrefVariable() const {
160   assert(Var && "Invalid complex DbgVariable!");
161   return Var->getType().resolve()->isBlockByrefStruct();
162 }
163 
164 const DIType *DbgVariable::getType() const {
165   DIType *Ty = Var->getType().resolve();
166   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
167   // addresses instead.
168   if (Ty->isBlockByrefStruct()) {
169     /* Byref variables, in Blocks, are declared by the programmer as
170        "SomeType VarName;", but the compiler creates a
171        __Block_byref_x_VarName struct, and gives the variable VarName
172        either the struct, or a pointer to the struct, as its type.  This
173        is necessary for various behind-the-scenes things the compiler
174        needs to do with by-reference variables in blocks.
175 
176        However, as far as the original *programmer* is concerned, the
177        variable should still have type 'SomeType', as originally declared.
178 
179        The following function dives into the __Block_byref_x_VarName
180        struct to find the original type of the variable.  This will be
181        passed back to the code generating the type for the Debug
182        Information Entry for the variable 'VarName'.  'VarName' will then
183        have the original type 'SomeType' in its debug information.
184 
185        The original type 'SomeType' will be the type of the field named
186        'VarName' inside the __Block_byref_x_VarName struct.
187 
188        NOTE: In order for this to not completely fail on the debugger
189        side, the Debug Information Entry for the variable VarName needs to
190        have a DW_AT_location that tells the debugger how to unwind through
191        the pointers and __Block_byref_x_VarName struct to find the actual
192        value of the variable.  The function addBlockByrefType does this.  */
193     DIType *subType = Ty;
194     uint16_t tag = Ty->getTag();
195 
196     if (tag == dwarf::DW_TAG_pointer_type)
197       subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
198 
199     auto Elements = cast<DICompositeType>(subType)->getElements();
200     for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
201       auto *DT = cast<DIDerivedType>(Elements[i]);
202       if (getName() == DT->getName())
203         return resolve(DT->getBaseType());
204     }
205   }
206   return Ty;
207 }
208 
209 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
210   if (FrameIndexExprs.size() == 1)
211     return FrameIndexExprs;
212 
213   assert(llvm::all_of(FrameIndexExprs,
214                       [](const FrameIndexExpr &A) {
215                         return A.Expr->isFragment();
216                       }) &&
217          "multiple FI expressions without DW_OP_LLVM_fragment");
218   std::sort(FrameIndexExprs.begin(), FrameIndexExprs.end(),
219             [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
220               return A.Expr->getFragmentInfo()->OffsetInBits <
221                      B.Expr->getFragmentInfo()->OffsetInBits;
222             });
223 
224   return FrameIndexExprs;
225 }
226 
227 void DbgVariable::addMMIEntry(const DbgVariable &V) {
228   assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
229   assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
230   assert(V.Var == Var && "conflicting variable");
231   assert(V.IA == IA && "conflicting inlined-at location");
232 
233   assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
234   assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
235 
236   // FIXME: This logic should not be necessary anymore, as we now have proper
237   // deduplication. However, without it, we currently run into the assertion
238   // below, which means that we are likely dealing with broken input, i.e. two
239   // non-fragment entries for the same variable at different frame indices.
240   if (FrameIndexExprs.size()) {
241     auto *Expr = FrameIndexExprs.back().Expr;
242     if (!Expr || !Expr->isFragment())
243       return;
244   }
245 
246   for (const auto &FIE : V.FrameIndexExprs)
247     // Ignore duplicate entries.
248     if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
249           return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
250         }))
251       FrameIndexExprs.push_back(FIE);
252 
253   assert((FrameIndexExprs.size() == 1 ||
254           llvm::all_of(FrameIndexExprs,
255                        [](FrameIndexExpr &FIE) {
256                          return FIE.Expr && FIE.Expr->isFragment();
257                        })) &&
258          "conflicting locations for variable");
259 }
260 
261 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
262     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
263       InfoHolder(A, "info_string", DIEValueAllocator),
264       SkeletonHolder(A, "skel_string", DIEValueAllocator),
265       IsDarwin(A->TM.getTargetTriple().isOSDarwin()), AccelNames(), AccelObjC(),
266       AccelNamespace(), AccelTypes() {
267   const Triple &TT = Asm->TM.getTargetTriple();
268 
269   // Make sure we know our "debugger tuning."  The target option takes
270   // precedence; fall back to triple-based defaults.
271   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
272     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
273   else if (IsDarwin)
274     DebuggerTuning = DebuggerKind::LLDB;
275   else if (TT.isPS4CPU())
276     DebuggerTuning = DebuggerKind::SCE;
277   else
278     DebuggerTuning = DebuggerKind::GDB;
279 
280   // Turn on accelerator tables by default, if tuning for LLDB and the target is
281   // supported.
282   if (DwarfAccelTables == Default)
283     HasDwarfAccelTables =
284         tuneForLLDB() && A->TM.getTargetTriple().isOSBinFormatMachO();
285   else
286     HasDwarfAccelTables = DwarfAccelTables == Enable;
287 
288   HasAppleExtensionAttributes = tuneForLLDB();
289 
290   // Handle split DWARF.
291   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
292 
293   // SCE defaults to linkage names only for abstract subprograms.
294   if (DwarfLinkageNames == DefaultLinkageNames)
295     UseAllLinkageNames = !tuneForSCE();
296   else
297     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
298 
299   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
300   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
301                                     : MMI->getModule()->getDwarfVersion();
302   // Use dwarf 4 by default if nothing is requested.
303   DwarfVersion = DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION;
304 
305   // Work around a GDB bug. GDB doesn't support the standard opcode;
306   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
307   // is defined as of DWARF 3.
308   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
309   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
310   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
311 
312   // GDB does not fully support the DWARF 4 representation for bitfields.
313   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
314 
315   // The DWARF v5 string offsets table has - possibly shared - contributions
316   // from each compile and type unit each preceded by a header. The string
317   // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
318   // a monolithic string offsets table without any header.
319   UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
320 
321   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
322 }
323 
324 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
325 DwarfDebug::~DwarfDebug() = default;
326 
327 static bool isObjCClass(StringRef Name) {
328   return Name.startswith("+") || Name.startswith("-");
329 }
330 
331 static bool hasObjCCategory(StringRef Name) {
332   if (!isObjCClass(Name))
333     return false;
334 
335   return Name.find(") ") != StringRef::npos;
336 }
337 
338 static void getObjCClassCategory(StringRef In, StringRef &Class,
339                                  StringRef &Category) {
340   if (!hasObjCCategory(In)) {
341     Class = In.slice(In.find('[') + 1, In.find(' '));
342     Category = "";
343     return;
344   }
345 
346   Class = In.slice(In.find('[') + 1, In.find('('));
347   Category = In.slice(In.find('[') + 1, In.find(' '));
348 }
349 
350 static StringRef getObjCMethodName(StringRef In) {
351   return In.slice(In.find(' ') + 1, In.find(']'));
352 }
353 
354 // Add the various names to the Dwarf accelerator table names.
355 // TODO: Determine whether or not we should add names for programs
356 // that do not have a DW_AT_name or DW_AT_linkage_name field - this
357 // is only slightly different than the lookup of non-standard ObjC names.
358 void DwarfDebug::addSubprogramNames(const DISubprogram *SP, DIE &Die) {
359   if (!SP->isDefinition())
360     return;
361   addAccelName(SP->getName(), Die);
362 
363   // If the linkage name is different than the name, go ahead and output
364   // that as well into the name table.
365   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName())
366     addAccelName(SP->getLinkageName(), Die);
367 
368   // If this is an Objective-C selector name add it to the ObjC accelerator
369   // too.
370   if (isObjCClass(SP->getName())) {
371     StringRef Class, Category;
372     getObjCClassCategory(SP->getName(), Class, Category);
373     addAccelObjC(Class, Die);
374     if (Category != "")
375       addAccelObjC(Category, Die);
376     // Also add the base method name to the name table.
377     addAccelName(getObjCMethodName(SP->getName()), Die);
378   }
379 }
380 
381 /// Check whether we should create a DIE for the given Scope, return true
382 /// if we don't create a DIE (the corresponding DIE is null).
383 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
384   if (Scope->isAbstractScope())
385     return false;
386 
387   // We don't create a DIE if there is no Range.
388   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
389   if (Ranges.empty())
390     return true;
391 
392   if (Ranges.size() > 1)
393     return false;
394 
395   // We don't create a DIE if we have a single Range and the end label
396   // is null.
397   return !getLabelAfterInsn(Ranges.front().second);
398 }
399 
400 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
401   F(CU);
402   if (auto *SkelCU = CU.getSkeleton())
403     if (CU.getCUNode()->getSplitDebugInlining())
404       F(*SkelCU);
405 }
406 
407 bool DwarfDebug::shareAcrossDWOCUs() const {
408   return SplitDwarfCrossCuReferences;
409 }
410 
411 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
412                                                      LexicalScope *Scope) {
413   assert(Scope && Scope->getScopeNode());
414   assert(Scope->isAbstractScope());
415   assert(!Scope->getInlinedAt());
416 
417   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
418 
419   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
420   // was inlined from another compile unit.
421   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
422     // Avoid building the original CU if it won't be used
423     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
424   else {
425     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
426     if (auto *SkelCU = CU.getSkeleton()) {
427       (shareAcrossDWOCUs() ? CU : SrcCU)
428           .constructAbstractSubprogramScopeDIE(Scope);
429       if (CU.getCUNode()->getSplitDebugInlining())
430         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
431     } else
432       CU.constructAbstractSubprogramScopeDIE(Scope);
433   }
434 }
435 
436 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
437   if (!U.hasDwarfPubSections())
438     return;
439 
440   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
441 }
442 
443 // Create new DwarfCompileUnit for the given metadata node with tag
444 // DW_TAG_compile_unit.
445 DwarfCompileUnit &
446 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
447   if (auto *CU = CUMap.lookup(DIUnit))
448     return *CU;
449   StringRef FN = DIUnit->getFilename();
450   CompilationDir = DIUnit->getDirectory();
451 
452   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
453       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
454   DwarfCompileUnit &NewCU = *OwnedUnit;
455   DIE &Die = NewCU.getUnitDie();
456   InfoHolder.addUnit(std::move(OwnedUnit));
457   if (useSplitDwarf()) {
458     NewCU.setSkeleton(constructSkeletonCU(NewCU));
459     NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
460                   Asm->TM.Options.MCOptions.SplitDwarfFile);
461   }
462 
463   for (auto *IE : DIUnit->getImportedEntities())
464     NewCU.addImportedEntity(IE);
465 
466   // LTO with assembly output shares a single line table amongst multiple CUs.
467   // To avoid the compilation directory being ambiguous, let the line table
468   // explicitly describe the directory of all files, never relying on the
469   // compilation directory.
470   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
471     Asm->OutStreamer->getContext().setMCLineTableCompilationDir(
472         NewCU.getUniqueID(), CompilationDir);
473 
474   StringRef Producer = DIUnit->getProducer();
475   StringRef Flags = DIUnit->getFlags();
476   if (!Flags.empty()) {
477     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
478     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
479   } else
480     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
481 
482   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
483                 DIUnit->getSourceLanguage());
484   NewCU.addString(Die, dwarf::DW_AT_name, FN);
485 
486   // Add DW_str_offsets_base to the unit DIE, except for split units.
487   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
488     NewCU.addStringOffsetsStart();
489 
490   if (!useSplitDwarf()) {
491     NewCU.initStmtList();
492 
493     // If we're using split dwarf the compilation dir is going to be in the
494     // skeleton CU and so we don't need to duplicate it here.
495     if (!CompilationDir.empty())
496       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
497 
498     addGnuPubAttributes(NewCU, Die);
499   }
500 
501   if (useAppleExtensionAttributes()) {
502     if (DIUnit->isOptimized())
503       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
504 
505     StringRef Flags = DIUnit->getFlags();
506     if (!Flags.empty())
507       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
508 
509     if (unsigned RVer = DIUnit->getRuntimeVersion())
510       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
511                     dwarf::DW_FORM_data1, RVer);
512   }
513 
514   if (useSplitDwarf())
515     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
516   else
517     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
518 
519   if (DIUnit->getDWOId()) {
520     // This CU is either a clang module DWO or a skeleton CU.
521     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
522                   DIUnit->getDWOId());
523     if (!DIUnit->getSplitDebugFilename().empty())
524       // This is a prefabricated skeleton CU.
525       NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
526                       DIUnit->getSplitDebugFilename());
527   }
528 
529   CUMap.insert({DIUnit, &NewCU});
530   CUDieMap.insert({&Die, &NewCU});
531   return NewCU;
532 }
533 
534 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
535                                                   const DIImportedEntity *N) {
536   if (isa<DILocalScope>(N->getScope()))
537     return;
538   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
539     D->addChild(TheCU.constructImportedEntityDIE(N));
540 }
541 
542 /// Sort and unique GVEs by comparing their fragment offset.
543 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
544 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
545   std::sort(GVEs.begin(), GVEs.end(),
546             [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
547               // Sort order: first null exprs, then exprs without fragment
548               // info, then sort by fragment offset in bits.
549               // FIXME: Come up with a more comprehensive comparator so
550               // the sorting isn't non-deterministic, and so the following
551               // std::unique call works correctly.
552               if (!A.Expr || !B.Expr)
553                 return !!B.Expr;
554               auto FragmentA = A.Expr->getFragmentInfo();
555               auto FragmentB = B.Expr->getFragmentInfo();
556               if (!FragmentA || !FragmentB)
557                 return !!FragmentB;
558               return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
559             });
560   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
561                          [](DwarfCompileUnit::GlobalExpr A,
562                             DwarfCompileUnit::GlobalExpr B) {
563                            return A.Expr == B.Expr;
564                          }),
565              GVEs.end());
566   return GVEs;
567 }
568 
569 // Emit all Dwarf sections that should come prior to the content. Create
570 // global DIEs and emit initial debug info sections. This is invoked by
571 // the target AsmPrinter.
572 void DwarfDebug::beginModule() {
573   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
574                      DWARFGroupDescription, TimePassesIsEnabled);
575   if (DisableDebugInfoPrinting)
576     return;
577 
578   const Module *M = MMI->getModule();
579 
580   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
581                                        M->debug_compile_units_end());
582   // Tell MMI whether we have debug info.
583   MMI->setDebugInfoAvailability(NumDebugCUs > 0);
584   SingleCU = NumDebugCUs == 1;
585   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
586       GVMap;
587   for (const GlobalVariable &Global : M->globals()) {
588     SmallVector<DIGlobalVariableExpression *, 1> GVs;
589     Global.getDebugInfo(GVs);
590     for (auto *GVE : GVs)
591       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
592   }
593 
594   // Create the symbol that designates the start of the unit's contribution
595   // to the string offsets table. In a split DWARF scenario, only the skeleton
596   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
597   if (useSegmentedStringOffsetsTable())
598     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
599         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
600 
601   for (DICompileUnit *CUNode : M->debug_compile_units()) {
602     // FIXME: Move local imported entities into a list attached to the
603     // subprogram, then this search won't be needed and a
604     // getImportedEntities().empty() test should go below with the rest.
605     bool HasNonLocalImportedEntities = llvm::any_of(
606         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
607           return !isa<DILocalScope>(IE->getScope());
608         });
609 
610     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
611         CUNode->getRetainedTypes().empty() &&
612         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
613       continue;
614 
615     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
616 
617     // Global Variables.
618     for (auto *GVE : CUNode->getGlobalVariables()) {
619       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
620       // already know about the variable and it isn't adding a constant
621       // expression.
622       auto &GVMapEntry = GVMap[GVE->getVariable()];
623       auto *Expr = GVE->getExpression();
624       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
625         GVMapEntry.push_back({nullptr, Expr});
626     }
627     DenseSet<DIGlobalVariable *> Processed;
628     for (auto *GVE : CUNode->getGlobalVariables()) {
629       DIGlobalVariable *GV = GVE->getVariable();
630       if (Processed.insert(GV).second)
631         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
632     }
633 
634     for (auto *Ty : CUNode->getEnumTypes()) {
635       // The enum types array by design contains pointers to
636       // MDNodes rather than DIRefs. Unique them here.
637       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
638     }
639     for (auto *Ty : CUNode->getRetainedTypes()) {
640       // The retained types array by design contains pointers to
641       // MDNodes rather than DIRefs. Unique them here.
642       if (DIType *RT = dyn_cast<DIType>(Ty))
643           // There is no point in force-emitting a forward declaration.
644           CU.getOrCreateTypeDIE(RT);
645     }
646     // Emit imported_modules last so that the relevant context is already
647     // available.
648     for (auto *IE : CUNode->getImportedEntities())
649       constructAndAddImportedEntityDIE(CU, IE);
650   }
651 }
652 
653 void DwarfDebug::finishVariableDefinitions() {
654   for (const auto &Var : ConcreteVariables) {
655     DIE *VariableDie = Var->getDIE();
656     assert(VariableDie);
657     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
658     // in the ConcreteVariables list, rather than looking it up again here.
659     // DIE::getUnit isn't simple - it walks parent pointers, etc.
660     DwarfCompileUnit *Unit = CUDieMap.lookup(VariableDie->getUnitDie());
661     assert(Unit);
662     Unit->finishVariableDefinition(*Var);
663   }
664 }
665 
666 void DwarfDebug::finishSubprogramDefinitions() {
667   for (const DISubprogram *SP : ProcessedSPNodes) {
668     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
669     forBothCUs(
670         getOrCreateDwarfCompileUnit(SP->getUnit()),
671         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
672   }
673 }
674 
675 void DwarfDebug::finalizeModuleInfo() {
676   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
677 
678   finishSubprogramDefinitions();
679 
680   finishVariableDefinitions();
681 
682   // Include the DWO file name in the hash if there's more than one CU.
683   // This handles ThinLTO's situation where imported CUs may very easily be
684   // duplicate with the same CU partially imported into another ThinLTO unit.
685   StringRef DWOName;
686   if (CUMap.size() > 1)
687     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
688 
689   // Handle anything that needs to be done on a per-unit basis after
690   // all other generation.
691   for (const auto &P : CUMap) {
692     auto &TheCU = *P.second;
693     // Emit DW_AT_containing_type attribute to connect types with their
694     // vtable holding type.
695     TheCU.constructContainingTypeDIEs();
696 
697     // Add CU specific attributes if we need to add any.
698     // If we're splitting the dwarf out now that we've got the entire
699     // CU then add the dwo id to it.
700     auto *SkCU = TheCU.getSkeleton();
701     if (useSplitDwarf()) {
702       // Emit a unique identifier for this CU.
703       uint64_t ID =
704           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
705       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
706                     dwarf::DW_FORM_data8, ID);
707       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
708                     dwarf::DW_FORM_data8, ID);
709 
710       // We don't keep track of which addresses are used in which CU so this
711       // is a bit pessimistic under LTO.
712       if (!AddrPool.isEmpty()) {
713         const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
714         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
715                               Sym, Sym);
716       }
717       if (!SkCU->getRangeLists().empty()) {
718         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
719         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
720                               Sym, Sym);
721       }
722     }
723 
724     // If we have code split among multiple sections or non-contiguous
725     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
726     // remain in the .o file, otherwise add a DW_AT_low_pc.
727     // FIXME: We should use ranges allow reordering of code ala
728     // .subsections_via_symbols in mach-o. This would mean turning on
729     // ranges for all subprogram DIEs for mach-o.
730     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
731     if (unsigned NumRanges = TheCU.getRanges().size()) {
732       if (NumRanges > 1)
733         // A DW_AT_low_pc attribute may also be specified in combination with
734         // DW_AT_ranges to specify the default base address for use in
735         // location lists (see Section 2.6.2) and range lists (see Section
736         // 2.17.3).
737         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
738       else
739         U.setBaseAddress(TheCU.getRanges().front().getStart());
740       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
741     }
742 
743     auto *CUNode = cast<DICompileUnit>(P.first);
744     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
745     if (CUNode->getMacros())
746       U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
747                         U.getMacroLabelBegin(),
748                         TLOF.getDwarfMacinfoSection()->getBeginSymbol());
749   }
750 
751   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
752   for (auto *CUNode : MMI->getModule()->debug_compile_units())
753     if (CUNode->getDWOId())
754       getOrCreateDwarfCompileUnit(CUNode);
755 
756   // Compute DIE offsets and sizes.
757   InfoHolder.computeSizeAndOffsets();
758   if (useSplitDwarf())
759     SkeletonHolder.computeSizeAndOffsets();
760 }
761 
762 // Emit all Dwarf sections that should come after the content.
763 void DwarfDebug::endModule() {
764   assert(CurFn == nullptr);
765   assert(CurMI == nullptr);
766 
767   // If we aren't actually generating debug info (check beginModule -
768   // conditionalized on !DisableDebugInfoPrinting and the presence of the
769   // llvm.dbg.cu metadata node)
770   if (!MMI->hasDebugInfo())
771     return;
772 
773   // Finalize the debug info for the module.
774   finalizeModuleInfo();
775 
776   emitDebugStr();
777 
778   if (useSplitDwarf())
779     emitDebugLocDWO();
780   else
781     // Emit info into a debug loc section.
782     emitDebugLoc();
783 
784   // Corresponding abbreviations into a abbrev section.
785   emitAbbreviations();
786 
787   // Emit all the DIEs into a debug info section.
788   emitDebugInfo();
789 
790   // Emit info into a debug aranges section.
791   if (GenerateARangeSection)
792     emitDebugARanges();
793 
794   // Emit info into a debug ranges section.
795   emitDebugRanges();
796 
797   // Emit info into a debug macinfo section.
798   emitDebugMacinfo();
799 
800   if (useSplitDwarf()) {
801     emitDebugStrDWO();
802     emitDebugInfoDWO();
803     emitDebugAbbrevDWO();
804     emitDebugLineDWO();
805     // Emit DWO addresses.
806     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
807   }
808 
809   // Emit info into the dwarf accelerator table sections.
810   if (useDwarfAccelTables()) {
811     emitAccelNames();
812     emitAccelObjC();
813     emitAccelNamespaces();
814     emitAccelTypes();
815   }
816 
817   // Emit the pubnames and pubtypes sections if requested.
818   emitDebugPubSections();
819 
820   // clean up.
821   // FIXME: AbstractVariables.clear();
822 }
823 
824 void DwarfDebug::ensureAbstractVariableIsCreated(DwarfCompileUnit &CU, InlinedVariable IV,
825                                                  const MDNode *ScopeNode) {
826   const DILocalVariable *Cleansed = nullptr;
827   if (CU.getExistingAbstractVariable(IV, Cleansed))
828     return;
829 
830   CU.createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(
831                                        cast<DILocalScope>(ScopeNode)));
832 }
833 
834 void DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(DwarfCompileUnit &CU,
835     InlinedVariable IV, const MDNode *ScopeNode) {
836   const DILocalVariable *Cleansed = nullptr;
837   if (CU.getExistingAbstractVariable(IV, Cleansed))
838     return;
839 
840   if (LexicalScope *Scope =
841           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
842     CU.createAbstractVariable(Cleansed, Scope);
843 }
844 
845 // Collect variable information from side table maintained by MF.
846 void DwarfDebug::collectVariableInfoFromMFTable(
847     DwarfCompileUnit &TheCU, DenseSet<InlinedVariable> &Processed) {
848   SmallDenseMap<InlinedVariable, DbgVariable *> MFVars;
849   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
850     if (!VI.Var)
851       continue;
852     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
853            "Expected inlined-at fields to agree");
854 
855     InlinedVariable Var(VI.Var, VI.Loc->getInlinedAt());
856     Processed.insert(Var);
857     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
858 
859     // If variable scope is not found then skip this variable.
860     if (!Scope)
861       continue;
862 
863     ensureAbstractVariableIsCreatedIfScoped(TheCU, Var, Scope->getScopeNode());
864     auto RegVar = llvm::make_unique<DbgVariable>(Var.first, Var.second);
865     RegVar->initializeMMI(VI.Expr, VI.Slot);
866     if (DbgVariable *DbgVar = MFVars.lookup(Var))
867       DbgVar->addMMIEntry(*RegVar);
868     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
869       MFVars.insert({Var, RegVar.get()});
870       ConcreteVariables.push_back(std::move(RegVar));
871     }
872   }
873 }
874 
875 // Get .debug_loc entry for the instruction range starting at MI.
876 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
877   const DIExpression *Expr = MI->getDebugExpression();
878   assert(MI->getNumOperands() == 4);
879   if (MI->getOperand(0).isReg()) {
880     auto RegOp = MI->getOperand(0);
881     auto Op1 = MI->getOperand(1);
882     // If the second operand is an immediate, this is a
883     // register-indirect address.
884     assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
885     MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
886     return DebugLocEntry::Value(Expr, MLoc);
887   }
888   if (MI->getOperand(0).isImm())
889     return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
890   if (MI->getOperand(0).isFPImm())
891     return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
892   if (MI->getOperand(0).isCImm())
893     return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
894 
895   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
896 }
897 
898 /// \brief If this and Next are describing different fragments of the same
899 /// variable, merge them by appending Next's values to the current
900 /// list of values.
901 /// Return true if the merge was successful.
902 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
903   if (Begin == Next.Begin) {
904     auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
905     auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
906     if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
907       return false;
908 
909     // We can only merge entries if none of the fragments overlap any others.
910     // In doing so, we can take advantage of the fact that both lists are
911     // sorted.
912     for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
913       for (; j < Next.Values.size(); ++j) {
914         int res = DebugHandlerBase::fragmentCmp(
915             cast<DIExpression>(Values[i].Expression),
916             cast<DIExpression>(Next.Values[j].Expression));
917         if (res == 0) // The two expressions overlap, we can't merge.
918           return false;
919         // Values[i] is entirely before Next.Values[j],
920         // so go back to the next entry of Values.
921         else if (res == -1)
922           break;
923         // Next.Values[j] is entirely before Values[i], so go on to the
924         // next entry of Next.Values.
925       }
926     }
927 
928     addValues(Next.Values);
929     End = Next.End;
930     return true;
931   }
932   return false;
933 }
934 
935 /// Build the location list for all DBG_VALUEs in the function that
936 /// describe the same variable.  If the ranges of several independent
937 /// fragments of the same variable overlap partially, split them up and
938 /// combine the ranges. The resulting DebugLocEntries are will have
939 /// strict monotonically increasing begin addresses and will never
940 /// overlap.
941 //
942 // Input:
943 //
944 //   Ranges History [var, loc, fragment ofs size]
945 // 0 |      [x, (reg0, fragment 0, 32)]
946 // 1 | |    [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
947 // 2 | |    ...
948 // 3   |    [clobber reg0]
949 // 4        [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
950 //                                     x.
951 //
952 // Output:
953 //
954 // [0-1]    [x, (reg0, fragment  0, 32)]
955 // [1-3]    [x, (reg0, fragment  0, 32), (reg1, fragment 32, 32)]
956 // [3-4]    [x, (reg1, fragment 32, 32)]
957 // [4- ]    [x, (mem,  fragment  0, 64)]
958 void
959 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
960                               const DbgValueHistoryMap::InstrRanges &Ranges) {
961   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
962 
963   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
964     const MachineInstr *Begin = I->first;
965     const MachineInstr *End = I->second;
966     assert(Begin->isDebugValue() && "Invalid History entry");
967 
968     // Check if a variable is inaccessible in this range.
969     if (Begin->getNumOperands() > 1 &&
970         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
971       OpenRanges.clear();
972       continue;
973     }
974 
975     // If this fragment overlaps with any open ranges, truncate them.
976     const DIExpression *DIExpr = Begin->getDebugExpression();
977     auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
978       return fragmentsOverlap(DIExpr, R.getExpression());
979     });
980     OpenRanges.erase(Last, OpenRanges.end());
981 
982     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
983     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
984 
985     const MCSymbol *EndLabel;
986     if (End != nullptr)
987       EndLabel = getLabelAfterInsn(End);
988     else if (std::next(I) == Ranges.end())
989       EndLabel = Asm->getFunctionEnd();
990     else
991       EndLabel = getLabelBeforeInsn(std::next(I)->first);
992     assert(EndLabel && "Forgot label after instruction ending a range!");
993 
994     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
995 
996     auto Value = getDebugLocValue(Begin);
997     DebugLocEntry Loc(StartLabel, EndLabel, Value);
998     bool couldMerge = false;
999 
1000     // If this is a fragment, it may belong to the current DebugLocEntry.
1001     if (DIExpr->isFragment()) {
1002       // Add this value to the list of open ranges.
1003       OpenRanges.push_back(Value);
1004 
1005       // Attempt to add the fragment to the last entry.
1006       if (!DebugLoc.empty())
1007         if (DebugLoc.back().MergeValues(Loc))
1008           couldMerge = true;
1009     }
1010 
1011     if (!couldMerge) {
1012       // Need to add a new DebugLocEntry. Add all values from still
1013       // valid non-overlapping fragments.
1014       if (OpenRanges.size())
1015         Loc.addValues(OpenRanges);
1016 
1017       DebugLoc.push_back(std::move(Loc));
1018     }
1019 
1020     // Attempt to coalesce the ranges of two otherwise identical
1021     // DebugLocEntries.
1022     auto CurEntry = DebugLoc.rbegin();
1023     DEBUG({
1024       dbgs() << CurEntry->getValues().size() << " Values:\n";
1025       for (auto &Value : CurEntry->getValues())
1026         Value.dump();
1027       dbgs() << "-----\n";
1028     });
1029 
1030     auto PrevEntry = std::next(CurEntry);
1031     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1032       DebugLoc.pop_back();
1033   }
1034 }
1035 
1036 DbgVariable *DwarfDebug::createConcreteVariable(DwarfCompileUnit &TheCU,
1037                                                 LexicalScope &Scope,
1038                                                 InlinedVariable IV) {
1039   ensureAbstractVariableIsCreatedIfScoped(TheCU, IV, Scope.getScopeNode());
1040   ConcreteVariables.push_back(
1041       llvm::make_unique<DbgVariable>(IV.first, IV.second));
1042   InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
1043   return ConcreteVariables.back().get();
1044 }
1045 
1046 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1047 /// enclosing lexical scope. The check ensures there are no other instructions
1048 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1049 /// either open or otherwise rolls off the end of the scope.
1050 static bool validThroughout(LexicalScopes &LScopes,
1051                             const MachineInstr *DbgValue,
1052                             const MachineInstr *RangeEnd) {
1053   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1054   auto MBB = DbgValue->getParent();
1055   auto DL = DbgValue->getDebugLoc();
1056   auto *LScope = LScopes.findLexicalScope(DL);
1057   // Scope doesn't exist; this is a dead DBG_VALUE.
1058   if (!LScope)
1059     return false;
1060   auto &LSRange = LScope->getRanges();
1061   if (LSRange.size() == 0)
1062     return false;
1063 
1064   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1065   const MachineInstr *LScopeBegin = LSRange.front().first;
1066   // Early exit if the lexical scope begins outside of the current block.
1067   if (LScopeBegin->getParent() != MBB)
1068     return false;
1069   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1070   for (++Pred; Pred != MBB->rend(); ++Pred) {
1071     if (Pred->getFlag(MachineInstr::FrameSetup))
1072       break;
1073     auto PredDL = Pred->getDebugLoc();
1074     if (!PredDL || Pred->isMetaInstruction())
1075       continue;
1076     // Check whether the instruction preceding the DBG_VALUE is in the same
1077     // (sub)scope as the DBG_VALUE.
1078     if (DL->getScope() == PredDL->getScope())
1079       return false;
1080     auto *PredScope = LScopes.findLexicalScope(PredDL);
1081     if (!PredScope || LScope->dominates(PredScope))
1082       return false;
1083   }
1084 
1085   // If the range of the DBG_VALUE is open-ended, report success.
1086   if (!RangeEnd)
1087     return true;
1088 
1089   // Fail if there are instructions belonging to our scope in another block.
1090   const MachineInstr *LScopeEnd = LSRange.back().second;
1091   if (LScopeEnd->getParent() != MBB)
1092     return false;
1093 
1094   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1095   // throughout the function. This is a hack, presumably for DWARF v2 and not
1096   // necessarily correct. It would be much better to use a dbg.declare instead
1097   // if we know the constant is live throughout the scope.
1098   if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1099     return true;
1100 
1101   return false;
1102 }
1103 
1104 // Find variables for each lexical scope.
1105 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
1106                                      const DISubprogram *SP,
1107                                      DenseSet<InlinedVariable> &Processed) {
1108   // Grab the variable info that was squirreled away in the MMI side-table.
1109   collectVariableInfoFromMFTable(TheCU, Processed);
1110 
1111   for (const auto &I : DbgValues) {
1112     InlinedVariable IV = I.first;
1113     if (Processed.count(IV))
1114       continue;
1115 
1116     // Instruction ranges, specifying where IV is accessible.
1117     const auto &Ranges = I.second;
1118     if (Ranges.empty())
1119       continue;
1120 
1121     LexicalScope *Scope = nullptr;
1122     if (const DILocation *IA = IV.second)
1123       Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
1124     else
1125       Scope = LScopes.findLexicalScope(IV.first->getScope());
1126     // If variable scope is not found then skip this variable.
1127     if (!Scope)
1128       continue;
1129 
1130     Processed.insert(IV);
1131     DbgVariable *RegVar = createConcreteVariable(TheCU, *Scope, IV);
1132 
1133     const MachineInstr *MInsn = Ranges.front().first;
1134     assert(MInsn->isDebugValue() && "History must begin with debug value");
1135 
1136     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1137     if (Ranges.size() == 1 &&
1138         validThroughout(LScopes, MInsn, Ranges.front().second)) {
1139       RegVar->initializeDbgValue(MInsn);
1140       continue;
1141     }
1142 
1143     // Handle multiple DBG_VALUE instructions describing one variable.
1144     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1145 
1146     // Build the location list for this variable.
1147     SmallVector<DebugLocEntry, 8> Entries;
1148     buildLocationList(Entries, Ranges);
1149 
1150     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1151     // unique identifiers, so don't bother resolving the type with the
1152     // identifier map.
1153     const DIBasicType *BT = dyn_cast<DIBasicType>(
1154         static_cast<const Metadata *>(IV.first->getType()));
1155 
1156     // Finalize the entry by lowering it into a DWARF bytestream.
1157     for (auto &Entry : Entries)
1158       Entry.finalize(*Asm, List, BT);
1159   }
1160 
1161   // Collect info for variables that were optimized out.
1162   for (const DILocalVariable *DV : SP->getVariables()) {
1163     if (Processed.insert(InlinedVariable(DV, nullptr)).second)
1164       if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
1165         createConcreteVariable(TheCU, *Scope, InlinedVariable(DV, nullptr));
1166   }
1167 }
1168 
1169 // Process beginning of an instruction.
1170 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1171   DebugHandlerBase::beginInstruction(MI);
1172   assert(CurMI);
1173 
1174   const auto *SP = MI->getMF()->getFunction().getSubprogram();
1175   if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1176     return;
1177 
1178   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1179   // If the instruction is part of the function frame setup code, do not emit
1180   // any line record, as there is no correspondence with any user code.
1181   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1182     return;
1183   const DebugLoc &DL = MI->getDebugLoc();
1184   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1185   // the last line number actually emitted, to see if it was line 0.
1186   unsigned LastAsmLine =
1187       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1188 
1189   if (DL == PrevInstLoc) {
1190     // If we have an ongoing unspecified location, nothing to do here.
1191     if (!DL)
1192       return;
1193     // We have an explicit location, same as the previous location.
1194     // But we might be coming back to it after a line 0 record.
1195     if (LastAsmLine == 0 && DL.getLine() != 0) {
1196       // Reinstate the source location but not marked as a statement.
1197       const MDNode *Scope = DL.getScope();
1198       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1199     }
1200     return;
1201   }
1202 
1203   if (!DL) {
1204     // We have an unspecified location, which might want to be line 0.
1205     // If we have already emitted a line-0 record, don't repeat it.
1206     if (LastAsmLine == 0)
1207       return;
1208     // If user said Don't Do That, don't do that.
1209     if (UnknownLocations == Disable)
1210       return;
1211     // See if we have a reason to emit a line-0 record now.
1212     // Reasons to emit a line-0 record include:
1213     // - User asked for it (UnknownLocations).
1214     // - Instruction has a label, so it's referenced from somewhere else,
1215     //   possibly debug information; we want it to have a source location.
1216     // - Instruction is at the top of a block; we don't want to inherit the
1217     //   location from the physically previous (maybe unrelated) block.
1218     if (UnknownLocations == Enable || PrevLabel ||
1219         (PrevInstBB && PrevInstBB != MI->getParent())) {
1220       // Preserve the file and column numbers, if we can, to save space in
1221       // the encoded line table.
1222       // Do not update PrevInstLoc, it remembers the last non-0 line.
1223       const MDNode *Scope = nullptr;
1224       unsigned Column = 0;
1225       if (PrevInstLoc) {
1226         Scope = PrevInstLoc.getScope();
1227         Column = PrevInstLoc.getCol();
1228       }
1229       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1230     }
1231     return;
1232   }
1233 
1234   // We have an explicit location, different from the previous location.
1235   // Don't repeat a line-0 record, but otherwise emit the new location.
1236   // (The new location might be an explicit line 0, which we do emit.)
1237   if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1238     return;
1239   unsigned Flags = 0;
1240   if (DL == PrologEndLoc) {
1241     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1242     PrologEndLoc = DebugLoc();
1243   }
1244   // If the line changed, we call that a new statement; unless we went to
1245   // line 0 and came back, in which case it is not a new statement.
1246   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1247   if (DL.getLine() && DL.getLine() != OldLine)
1248     Flags |= DWARF2_FLAG_IS_STMT;
1249 
1250   const MDNode *Scope = DL.getScope();
1251   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1252 
1253   // If we're not at line 0, remember this location.
1254   if (DL.getLine())
1255     PrevInstLoc = DL;
1256 }
1257 
1258 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1259   // First known non-DBG_VALUE and non-frame setup location marks
1260   // the beginning of the function body.
1261   for (const auto &MBB : *MF)
1262     for (const auto &MI : MBB)
1263       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1264           MI.getDebugLoc())
1265         return MI.getDebugLoc();
1266   return DebugLoc();
1267 }
1268 
1269 // Gather pre-function debug information.  Assumes being called immediately
1270 // after the function entry point has been emitted.
1271 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1272   CurFn = MF;
1273 
1274   auto *SP = MF->getFunction().getSubprogram();
1275   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1276   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1277     return;
1278 
1279   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1280 
1281   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1282   // belongs to so that we add to the correct per-cu line table in the
1283   // non-asm case.
1284   if (Asm->OutStreamer->hasRawTextSupport())
1285     // Use a single line table if we are generating assembly.
1286     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1287   else
1288     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1289 
1290   // Record beginning of function.
1291   PrologEndLoc = findPrologueEndLoc(MF);
1292   if (PrologEndLoc) {
1293     // We'd like to list the prologue as "not statements" but GDB behaves
1294     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1295     auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1296     recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1297   }
1298 }
1299 
1300 void DwarfDebug::skippedNonDebugFunction() {
1301   // If we don't have a subprogram for this function then there will be a hole
1302   // in the range information. Keep note of this by setting the previously used
1303   // section to nullptr.
1304   PrevCU = nullptr;
1305   CurFn = nullptr;
1306 }
1307 
1308 // Gather and emit post-function debug information.
1309 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1310   const DISubprogram *SP = MF->getFunction().getSubprogram();
1311 
1312   assert(CurFn == MF &&
1313       "endFunction should be called with the same function as beginFunction");
1314 
1315   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1316   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1317 
1318   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1319   assert(!FnScope || SP == FnScope->getScopeNode());
1320   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1321 
1322   DenseSet<InlinedVariable> ProcessedVars;
1323   collectVariableInfo(TheCU, SP, ProcessedVars);
1324 
1325   // Add the range of this function to the list of ranges for the CU.
1326   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1327 
1328   // Under -gmlt, skip building the subprogram if there are no inlined
1329   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1330   // is still needed as we need its source location.
1331   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1332       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1333       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1334     assert(InfoHolder.getScopeVariables().empty());
1335     PrevLabel = nullptr;
1336     CurFn = nullptr;
1337     return;
1338   }
1339 
1340 #ifndef NDEBUG
1341   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1342 #endif
1343   // Construct abstract scopes.
1344   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1345     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1346     // Collect info for variables that were optimized out.
1347     for (const DILocalVariable *DV : SP->getVariables()) {
1348       if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1349         continue;
1350       ensureAbstractVariableIsCreated(TheCU, InlinedVariable(DV, nullptr),
1351                                       DV->getScope());
1352       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1353              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1354     }
1355     constructAbstractSubprogramScopeDIE(TheCU, AScope);
1356   }
1357 
1358   ProcessedSPNodes.insert(SP);
1359   TheCU.constructSubprogramScopeDIE(SP, FnScope);
1360   if (auto *SkelCU = TheCU.getSkeleton())
1361     if (!LScopes.getAbstractScopesList().empty() &&
1362         TheCU.getCUNode()->getSplitDebugInlining())
1363       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1364 
1365   // Clear debug info
1366   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1367   // DbgVariables except those that are also in AbstractVariables (since they
1368   // can be used cross-function)
1369   InfoHolder.getScopeVariables().clear();
1370   PrevLabel = nullptr;
1371   CurFn = nullptr;
1372 }
1373 
1374 // Register a source line with debug info. Returns the  unique label that was
1375 // emitted and which provides correspondence to the source line list.
1376 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1377                                   unsigned Flags) {
1378   StringRef Fn;
1379   unsigned Src = 1;
1380   unsigned Discriminator = 0;
1381   if (auto *Scope = cast_or_null<DIScope>(S)) {
1382     Fn = Scope->getFilename();
1383     if (Line != 0 && getDwarfVersion() >= 4)
1384       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1385         Discriminator = LBF->getDiscriminator();
1386 
1387     unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1388     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1389               .getOrCreateSourceID(Scope->getFile());
1390   }
1391   Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1392                                           Discriminator, Fn);
1393 }
1394 
1395 //===----------------------------------------------------------------------===//
1396 // Emit Methods
1397 //===----------------------------------------------------------------------===//
1398 
1399 // Emit the debug info section.
1400 void DwarfDebug::emitDebugInfo() {
1401   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1402   Holder.emitUnits(/* UseOffsets */ false);
1403 }
1404 
1405 // Emit the abbreviation section.
1406 void DwarfDebug::emitAbbreviations() {
1407   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1408 
1409   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1410 }
1411 
1412 void DwarfDebug::emitStringOffsetsTableHeader() {
1413   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1414   Holder.emitStringOffsetsTableHeader(
1415       Asm->getObjFileLowering().getDwarfStrOffSection());
1416 }
1417 
1418 template <typename AccelTableT>
1419 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1420                            StringRef TableName) {
1421   Accel.finalizeTable(Asm, TableName);
1422   Asm->OutStreamer->SwitchSection(Section);
1423 
1424   // Emit the full data.
1425   Accel.emit(Asm, Section->getBeginSymbol());
1426 }
1427 
1428 // Emit visible names into a hashed accelerator table section.
1429 void DwarfDebug::emitAccelNames() {
1430   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1431             "Names");
1432 }
1433 
1434 // Emit objective C classes and categories into a hashed accelerator table
1435 // section.
1436 void DwarfDebug::emitAccelObjC() {
1437   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1438             "ObjC");
1439 }
1440 
1441 // Emit namespace dies into a hashed accelerator table.
1442 void DwarfDebug::emitAccelNamespaces() {
1443   emitAccel(AccelNamespace,
1444             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1445             "namespac");
1446 }
1447 
1448 // Emit type dies into a hashed accelerator table.
1449 void DwarfDebug::emitAccelTypes() {
1450   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1451             "types");
1452 }
1453 
1454 // Public name handling.
1455 // The format for the various pubnames:
1456 //
1457 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1458 // for the DIE that is named.
1459 //
1460 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1461 // into the CU and the index value is computed according to the type of value
1462 // for the DIE that is named.
1463 //
1464 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1465 // it's the offset within the debug_info/debug_types dwo section, however, the
1466 // reference in the pubname header doesn't change.
1467 
1468 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1469 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1470                                                         const DIE *Die) {
1471   // Entities that ended up only in a Type Unit reference the CU instead (since
1472   // the pub entry has offsets within the CU there's no real offset that can be
1473   // provided anyway). As it happens all such entities (namespaces and types,
1474   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1475   // not to be true it would be necessary to persist this information from the
1476   // point at which the entry is added to the index data structure - since by
1477   // the time the index is built from that, the original type/namespace DIE in a
1478   // type unit has already been destroyed so it can't be queried for properties
1479   // like tag, etc.
1480   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1481     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1482                                           dwarf::GIEL_EXTERNAL);
1483   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1484 
1485   // We could have a specification DIE that has our most of our knowledge,
1486   // look for that now.
1487   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1488     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1489     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1490       Linkage = dwarf::GIEL_EXTERNAL;
1491   } else if (Die->findAttribute(dwarf::DW_AT_external))
1492     Linkage = dwarf::GIEL_EXTERNAL;
1493 
1494   switch (Die->getTag()) {
1495   case dwarf::DW_TAG_class_type:
1496   case dwarf::DW_TAG_structure_type:
1497   case dwarf::DW_TAG_union_type:
1498   case dwarf::DW_TAG_enumeration_type:
1499     return dwarf::PubIndexEntryDescriptor(
1500         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1501                               ? dwarf::GIEL_STATIC
1502                               : dwarf::GIEL_EXTERNAL);
1503   case dwarf::DW_TAG_typedef:
1504   case dwarf::DW_TAG_base_type:
1505   case dwarf::DW_TAG_subrange_type:
1506     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1507   case dwarf::DW_TAG_namespace:
1508     return dwarf::GIEK_TYPE;
1509   case dwarf::DW_TAG_subprogram:
1510     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1511   case dwarf::DW_TAG_variable:
1512     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1513   case dwarf::DW_TAG_enumerator:
1514     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1515                                           dwarf::GIEL_STATIC);
1516   default:
1517     return dwarf::GIEK_NONE;
1518   }
1519 }
1520 
1521 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
1522 /// pubtypes sections.
1523 void DwarfDebug::emitDebugPubSections() {
1524   for (const auto &NU : CUMap) {
1525     DwarfCompileUnit *TheU = NU.second;
1526     if (!TheU->hasDwarfPubSections())
1527       continue;
1528 
1529     bool GnuStyle = TheU->getCUNode()->getGnuPubnames();
1530 
1531     Asm->OutStreamer->SwitchSection(
1532         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1533                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
1534     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1535 
1536     Asm->OutStreamer->SwitchSection(
1537         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1538                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
1539     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1540   }
1541 }
1542 
1543 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1544                                      DwarfCompileUnit *TheU,
1545                                      const StringMap<const DIE *> &Globals) {
1546   if (auto *Skeleton = TheU->getSkeleton())
1547     TheU = Skeleton;
1548 
1549   // Emit the header.
1550   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1551   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1552   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1553   Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1554 
1555   Asm->OutStreamer->EmitLabel(BeginLabel);
1556 
1557   Asm->OutStreamer->AddComment("DWARF Version");
1558   Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1559 
1560   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1561   Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1562 
1563   Asm->OutStreamer->AddComment("Compilation Unit Length");
1564   Asm->EmitInt32(TheU->getLength());
1565 
1566   // Emit the pubnames for this compilation unit.
1567   for (const auto &GI : Globals) {
1568     const char *Name = GI.getKeyData();
1569     const DIE *Entity = GI.second;
1570 
1571     Asm->OutStreamer->AddComment("DIE offset");
1572     Asm->EmitInt32(Entity->getOffset());
1573 
1574     if (GnuStyle) {
1575       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1576       Asm->OutStreamer->AddComment(
1577           Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1578           dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1579       Asm->EmitInt8(Desc.toBits());
1580     }
1581 
1582     Asm->OutStreamer->AddComment("External Name");
1583     Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1584   }
1585 
1586   Asm->OutStreamer->AddComment("End Mark");
1587   Asm->EmitInt32(0);
1588   Asm->OutStreamer->EmitLabel(EndLabel);
1589 }
1590 
1591 /// Emit null-terminated strings into a debug str section.
1592 void DwarfDebug::emitDebugStr() {
1593   MCSection *StringOffsetsSection = nullptr;
1594   if (useSegmentedStringOffsetsTable()) {
1595     emitStringOffsetsTableHeader();
1596     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1597   }
1598   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1599   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1600                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
1601 }
1602 
1603 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1604                                    const DebugLocStream::Entry &Entry) {
1605   auto &&Comments = DebugLocs.getComments(Entry);
1606   auto Comment = Comments.begin();
1607   auto End = Comments.end();
1608   for (uint8_t Byte : DebugLocs.getBytes(Entry))
1609     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1610 }
1611 
1612 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1613                               ByteStreamer &Streamer,
1614                               const DebugLocEntry::Value &Value,
1615                               DwarfExpression &DwarfExpr) {
1616   auto *DIExpr = Value.getExpression();
1617   DIExpressionCursor ExprCursor(DIExpr);
1618   DwarfExpr.addFragmentOffset(DIExpr);
1619   // Regular entry.
1620   if (Value.isInt()) {
1621     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1622                BT->getEncoding() == dwarf::DW_ATE_signed_char))
1623       DwarfExpr.addSignedConstant(Value.getInt());
1624     else
1625       DwarfExpr.addUnsignedConstant(Value.getInt());
1626   } else if (Value.isLocation()) {
1627     MachineLocation Location = Value.getLoc();
1628     if (Location.isIndirect())
1629       DwarfExpr.setMemoryLocationKind();
1630     DIExpressionCursor Cursor(DIExpr);
1631     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1632     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1633       return;
1634     return DwarfExpr.addExpression(std::move(Cursor));
1635   } else if (Value.isConstantFP()) {
1636     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1637     DwarfExpr.addUnsignedConstant(RawBytes);
1638   }
1639   DwarfExpr.addExpression(std::move(ExprCursor));
1640 }
1641 
1642 void DebugLocEntry::finalize(const AsmPrinter &AP,
1643                              DebugLocStream::ListBuilder &List,
1644                              const DIBasicType *BT) {
1645   DebugLocStream::EntryBuilder Entry(List, Begin, End);
1646   BufferByteStreamer Streamer = Entry.getStreamer();
1647   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
1648   const DebugLocEntry::Value &Value = Values[0];
1649   if (Value.isFragment()) {
1650     // Emit all fragments that belong to the same variable and range.
1651     assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
1652           return P.isFragment();
1653         }) && "all values are expected to be fragments");
1654     assert(std::is_sorted(Values.begin(), Values.end()) &&
1655            "fragments are expected to be sorted");
1656 
1657     for (auto Fragment : Values)
1658       emitDebugLocValue(AP, BT, Streamer, Fragment, DwarfExpr);
1659 
1660   } else {
1661     assert(Values.size() == 1 && "only fragments may have >1 value");
1662     emitDebugLocValue(AP, BT, Streamer, Value, DwarfExpr);
1663   }
1664   DwarfExpr.finalize();
1665 }
1666 
1667 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1668   // Emit the size.
1669   Asm->OutStreamer->AddComment("Loc expr size");
1670   Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1671 
1672   // Emit the entry.
1673   APByteStreamer Streamer(*Asm);
1674   emitDebugLocEntry(Streamer, Entry);
1675 }
1676 
1677 // Emit locations into the debug loc section.
1678 void DwarfDebug::emitDebugLoc() {
1679   if (DebugLocs.getLists().empty())
1680     return;
1681 
1682   // Start the dwarf loc section.
1683   Asm->OutStreamer->SwitchSection(
1684       Asm->getObjFileLowering().getDwarfLocSection());
1685   unsigned char Size = Asm->MAI->getCodePointerSize();
1686   for (const auto &List : DebugLocs.getLists()) {
1687     Asm->OutStreamer->EmitLabel(List.Label);
1688     const DwarfCompileUnit *CU = List.CU;
1689     for (const auto &Entry : DebugLocs.getEntries(List)) {
1690       // Set up the range. This range is relative to the entry point of the
1691       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1692       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1693       if (auto *Base = CU->getBaseAddress()) {
1694         Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1695         Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1696       } else {
1697         Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1698         Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1699       }
1700 
1701       emitDebugLocEntryLocation(Entry);
1702     }
1703     Asm->OutStreamer->EmitIntValue(0, Size);
1704     Asm->OutStreamer->EmitIntValue(0, Size);
1705   }
1706 }
1707 
1708 void DwarfDebug::emitDebugLocDWO() {
1709   Asm->OutStreamer->SwitchSection(
1710       Asm->getObjFileLowering().getDwarfLocDWOSection());
1711   for (const auto &List : DebugLocs.getLists()) {
1712     Asm->OutStreamer->EmitLabel(List.Label);
1713     for (const auto &Entry : DebugLocs.getEntries(List)) {
1714       // Just always use start_length for now - at least that's one address
1715       // rather than two. We could get fancier and try to, say, reuse an
1716       // address we know we've emitted elsewhere (the start of the function?
1717       // The start of the CU or CU subrange that encloses this range?)
1718       Asm->EmitInt8(dwarf::DW_LLE_startx_length);
1719       unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1720       Asm->EmitULEB128(idx);
1721       Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1722 
1723       emitDebugLocEntryLocation(Entry);
1724     }
1725     Asm->EmitInt8(dwarf::DW_LLE_end_of_list);
1726   }
1727 }
1728 
1729 struct ArangeSpan {
1730   const MCSymbol *Start, *End;
1731 };
1732 
1733 // Emit a debug aranges section, containing a CU lookup for any
1734 // address we can tie back to a CU.
1735 void DwarfDebug::emitDebugARanges() {
1736   // Provides a unique id per text section.
1737   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1738 
1739   // Filter labels by section.
1740   for (const SymbolCU &SCU : ArangeLabels) {
1741     if (SCU.Sym->isInSection()) {
1742       // Make a note of this symbol and it's section.
1743       MCSection *Section = &SCU.Sym->getSection();
1744       if (!Section->getKind().isMetadata())
1745         SectionMap[Section].push_back(SCU);
1746     } else {
1747       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1748       // appear in the output. This sucks as we rely on sections to build
1749       // arange spans. We can do it without, but it's icky.
1750       SectionMap[nullptr].push_back(SCU);
1751     }
1752   }
1753 
1754   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1755 
1756   for (auto &I : SectionMap) {
1757     MCSection *Section = I.first;
1758     SmallVector<SymbolCU, 8> &List = I.second;
1759     if (List.size() < 1)
1760       continue;
1761 
1762     // If we have no section (e.g. common), just write out
1763     // individual spans for each symbol.
1764     if (!Section) {
1765       for (const SymbolCU &Cur : List) {
1766         ArangeSpan Span;
1767         Span.Start = Cur.Sym;
1768         Span.End = nullptr;
1769         assert(Cur.CU);
1770         Spans[Cur.CU].push_back(Span);
1771       }
1772       continue;
1773     }
1774 
1775     // Sort the symbols by offset within the section.
1776     std::sort(
1777         List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
1778           unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1779           unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1780 
1781           // Symbols with no order assigned should be placed at the end.
1782           // (e.g. section end labels)
1783           if (IA == 0)
1784             return false;
1785           if (IB == 0)
1786             return true;
1787           return IA < IB;
1788         });
1789 
1790     // Insert a final terminator.
1791     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
1792 
1793     // Build spans between each label.
1794     const MCSymbol *StartSym = List[0].Sym;
1795     for (size_t n = 1, e = List.size(); n < e; n++) {
1796       const SymbolCU &Prev = List[n - 1];
1797       const SymbolCU &Cur = List[n];
1798 
1799       // Try and build the longest span we can within the same CU.
1800       if (Cur.CU != Prev.CU) {
1801         ArangeSpan Span;
1802         Span.Start = StartSym;
1803         Span.End = Cur.Sym;
1804         assert(Prev.CU);
1805         Spans[Prev.CU].push_back(Span);
1806         StartSym = Cur.Sym;
1807       }
1808     }
1809   }
1810 
1811   // Start the dwarf aranges section.
1812   Asm->OutStreamer->SwitchSection(
1813       Asm->getObjFileLowering().getDwarfARangesSection());
1814 
1815   unsigned PtrSize = Asm->MAI->getCodePointerSize();
1816 
1817   // Build a list of CUs used.
1818   std::vector<DwarfCompileUnit *> CUs;
1819   for (const auto &it : Spans) {
1820     DwarfCompileUnit *CU = it.first;
1821     CUs.push_back(CU);
1822   }
1823 
1824   // Sort the CU list (again, to ensure consistent output order).
1825   std::sort(CUs.begin(), CUs.end(),
1826             [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1827               return A->getUniqueID() < B->getUniqueID();
1828             });
1829 
1830   // Emit an arange table for each CU we used.
1831   for (DwarfCompileUnit *CU : CUs) {
1832     std::vector<ArangeSpan> &List = Spans[CU];
1833 
1834     // Describe the skeleton CU's offset and length, not the dwo file's.
1835     if (auto *Skel = CU->getSkeleton())
1836       CU = Skel;
1837 
1838     // Emit size of content not including length itself.
1839     unsigned ContentSize =
1840         sizeof(int16_t) + // DWARF ARange version number
1841         sizeof(int32_t) + // Offset of CU in the .debug_info section
1842         sizeof(int8_t) +  // Pointer Size (in bytes)
1843         sizeof(int8_t);   // Segment Size (in bytes)
1844 
1845     unsigned TupleSize = PtrSize * 2;
1846 
1847     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1848     unsigned Padding =
1849         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1850 
1851     ContentSize += Padding;
1852     ContentSize += (List.size() + 1) * TupleSize;
1853 
1854     // For each compile unit, write the list of spans it covers.
1855     Asm->OutStreamer->AddComment("Length of ARange Set");
1856     Asm->EmitInt32(ContentSize);
1857     Asm->OutStreamer->AddComment("DWARF Arange version number");
1858     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1859     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1860     Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1861     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1862     Asm->EmitInt8(PtrSize);
1863     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1864     Asm->EmitInt8(0);
1865 
1866     Asm->OutStreamer->emitFill(Padding, 0xff);
1867 
1868     for (const ArangeSpan &Span : List) {
1869       Asm->EmitLabelReference(Span.Start, PtrSize);
1870 
1871       // Calculate the size as being from the span start to it's end.
1872       if (Span.End) {
1873         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1874       } else {
1875         // For symbols without an end marker (e.g. common), we
1876         // write a single arange entry containing just that one symbol.
1877         uint64_t Size = SymSize[Span.Start];
1878         if (Size == 0)
1879           Size = 1;
1880 
1881         Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1882       }
1883     }
1884 
1885     Asm->OutStreamer->AddComment("ARange terminator");
1886     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1887     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1888   }
1889 }
1890 
1891 /// Emit address ranges into a debug ranges section.
1892 void DwarfDebug::emitDebugRanges() {
1893   if (CUMap.empty())
1894     return;
1895 
1896   // Start the dwarf ranges section.
1897   Asm->OutStreamer->SwitchSection(
1898       Asm->getObjFileLowering().getDwarfRangesSection());
1899 
1900   // Size for our labels.
1901   unsigned char Size = Asm->MAI->getCodePointerSize();
1902 
1903   // Grab the specific ranges for the compile units in the module.
1904   for (const auto &I : CUMap) {
1905     DwarfCompileUnit *TheCU = I.second;
1906 
1907     if (auto *Skel = TheCU->getSkeleton())
1908       TheCU = Skel;
1909 
1910     // Iterate over the misc ranges for the compile units in the module.
1911     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1912       // Emit our symbol so we can find the beginning of the range.
1913       Asm->OutStreamer->EmitLabel(List.getSym());
1914 
1915       // Gather all the ranges that apply to the same section so they can share
1916       // a base address entry.
1917       MapVector<const MCSection *, std::vector<const RangeSpan *>> MV;
1918       for (const RangeSpan &Range : List.getRanges()) {
1919         MV[&Range.getStart()->getSection()].push_back(&Range);
1920       }
1921 
1922       auto *CUBase = TheCU->getBaseAddress();
1923       bool BaseIsSet = false;
1924       for (const auto &P : MV) {
1925         // Don't bother with a base address entry if there's only one range in
1926         // this section in this range list - for example ranges for a CU will
1927         // usually consist of single regions from each of many sections
1928         // (-ffunction-sections, or just C++ inline functions) except under LTO
1929         // or optnone where there may be holes in a single CU's section
1930         // contrubutions.
1931         auto *Base = CUBase;
1932         if (!Base && P.second.size() > 1 &&
1933             UseDwarfRangesBaseAddressSpecifier) {
1934           BaseIsSet = true;
1935           // FIXME/use care: This may not be a useful base address if it's not
1936           // the lowest address/range in this object.
1937           Base = P.second.front()->getStart();
1938           Asm->OutStreamer->EmitIntValue(-1, Size);
1939           Asm->OutStreamer->EmitSymbolValue(Base, Size);
1940         } else if (BaseIsSet) {
1941           BaseIsSet = false;
1942           Asm->OutStreamer->EmitIntValue(-1, Size);
1943           Asm->OutStreamer->EmitIntValue(0, Size);
1944         }
1945 
1946         for (const auto *RS : P.second) {
1947           const MCSymbol *Begin = RS->getStart();
1948           const MCSymbol *End = RS->getEnd();
1949           assert(Begin && "Range without a begin symbol?");
1950           assert(End && "Range without an end symbol?");
1951           if (Base) {
1952             Asm->EmitLabelDifference(Begin, Base, Size);
1953             Asm->EmitLabelDifference(End, Base, Size);
1954           } else {
1955             Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1956             Asm->OutStreamer->EmitSymbolValue(End, Size);
1957           }
1958         }
1959       }
1960 
1961       // And terminate the list with two 0 values.
1962       Asm->OutStreamer->EmitIntValue(0, Size);
1963       Asm->OutStreamer->EmitIntValue(0, Size);
1964     }
1965   }
1966 }
1967 
1968 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
1969   for (auto *MN : Nodes) {
1970     if (auto *M = dyn_cast<DIMacro>(MN))
1971       emitMacro(*M);
1972     else if (auto *F = dyn_cast<DIMacroFile>(MN))
1973       emitMacroFile(*F, U);
1974     else
1975       llvm_unreachable("Unexpected DI type!");
1976   }
1977 }
1978 
1979 void DwarfDebug::emitMacro(DIMacro &M) {
1980   Asm->EmitULEB128(M.getMacinfoType());
1981   Asm->EmitULEB128(M.getLine());
1982   StringRef Name = M.getName();
1983   StringRef Value = M.getValue();
1984   Asm->OutStreamer->EmitBytes(Name);
1985   if (!Value.empty()) {
1986     // There should be one space between macro name and macro value.
1987     Asm->EmitInt8(' ');
1988     Asm->OutStreamer->EmitBytes(Value);
1989   }
1990   Asm->EmitInt8('\0');
1991 }
1992 
1993 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
1994   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
1995   Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
1996   Asm->EmitULEB128(F.getLine());
1997   Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
1998   handleMacroNodes(F.getElements(), U);
1999   Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2000 }
2001 
2002 /// Emit macros into a debug macinfo section.
2003 void DwarfDebug::emitDebugMacinfo() {
2004   if (CUMap.empty())
2005     return;
2006 
2007   // Start the dwarf macinfo section.
2008   Asm->OutStreamer->SwitchSection(
2009       Asm->getObjFileLowering().getDwarfMacinfoSection());
2010 
2011   for (const auto &P : CUMap) {
2012     auto &TheCU = *P.second;
2013     auto *SkCU = TheCU.getSkeleton();
2014     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2015     auto *CUNode = cast<DICompileUnit>(P.first);
2016     Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2017     handleMacroNodes(CUNode->getMacros(), U);
2018   }
2019   Asm->OutStreamer->AddComment("End Of Macro List Mark");
2020   Asm->EmitInt8(0);
2021 }
2022 
2023 // DWARF5 Experimental Separate Dwarf emitters.
2024 
2025 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2026                                   std::unique_ptr<DwarfCompileUnit> NewU) {
2027   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
2028                   Asm->TM.Options.MCOptions.SplitDwarfFile);
2029 
2030   if (!CompilationDir.empty())
2031     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2032 
2033   addGnuPubAttributes(*NewU, Die);
2034 
2035   SkeletonHolder.addUnit(std::move(NewU));
2036 }
2037 
2038 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2039 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2040 // DW_AT_addr_base, DW_AT_ranges_base.
2041 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2042 
2043   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2044       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2045   DwarfCompileUnit &NewCU = *OwnedUnit;
2046   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2047 
2048   NewCU.initStmtList();
2049 
2050   if (useSegmentedStringOffsetsTable())
2051     NewCU.addStringOffsetsStart();
2052 
2053   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2054 
2055   return NewCU;
2056 }
2057 
2058 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2059 // compile units that would normally be in debug_info.
2060 void DwarfDebug::emitDebugInfoDWO() {
2061   assert(useSplitDwarf() && "No split dwarf debug info?");
2062   // Don't emit relocations into the dwo file.
2063   InfoHolder.emitUnits(/* UseOffsets */ true);
2064 }
2065 
2066 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2067 // abbreviations for the .debug_info.dwo section.
2068 void DwarfDebug::emitDebugAbbrevDWO() {
2069   assert(useSplitDwarf() && "No split dwarf?");
2070   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2071 }
2072 
2073 void DwarfDebug::emitDebugLineDWO() {
2074   assert(useSplitDwarf() && "No split dwarf?");
2075   Asm->OutStreamer->SwitchSection(
2076       Asm->getObjFileLowering().getDwarfLineDWOSection());
2077   SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
2078 }
2079 
2080 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2081   assert(useSplitDwarf() && "No split dwarf?");
2082   InfoHolder.emitStringOffsetsTableHeader(
2083       Asm->getObjFileLowering().getDwarfStrOffDWOSection());
2084 }
2085 
2086 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2087 // string section and is identical in format to traditional .debug_str
2088 // sections.
2089 void DwarfDebug::emitDebugStrDWO() {
2090   if (useSegmentedStringOffsetsTable())
2091     emitStringOffsetsTableHeaderDWO();
2092   assert(useSplitDwarf() && "No split dwarf?");
2093   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2094   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2095                          OffSec, /* UseRelativeOffsets = */ false);
2096 }
2097 
2098 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2099   if (!useSplitDwarf())
2100     return nullptr;
2101   if (SingleCU)
2102     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
2103   return &SplitTypeUnitFileTable;
2104 }
2105 
2106 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2107   MD5 Hash;
2108   Hash.update(Identifier);
2109   // ... take the least significant 8 bytes and return those. Our MD5
2110   // implementation always returns its results in little endian, so we actually
2111   // need the "high" word.
2112   MD5::MD5Result Result;
2113   Hash.final(Result);
2114   return Result.high();
2115 }
2116 
2117 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2118                                       StringRef Identifier, DIE &RefDie,
2119                                       const DICompositeType *CTy) {
2120   // Fast path if we're building some type units and one has already used the
2121   // address pool we know we're going to throw away all this work anyway, so
2122   // don't bother building dependent types.
2123   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2124     return;
2125 
2126   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2127   if (!Ins.second) {
2128     CU.addDIETypeSignature(RefDie, Ins.first->second);
2129     return;
2130   }
2131 
2132   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2133   AddrPool.resetUsedFlag();
2134 
2135   auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2136                                                     getDwoLineTable(CU));
2137   DwarfTypeUnit &NewTU = *OwnedUnit;
2138   DIE &UnitDie = NewTU.getUnitDie();
2139   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2140 
2141   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2142                 CU.getLanguage());
2143 
2144   uint64_t Signature = makeTypeSignature(Identifier);
2145   NewTU.setTypeSignature(Signature);
2146   Ins.first->second = Signature;
2147 
2148   if (useSplitDwarf())
2149     NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
2150   else {
2151     CU.applyStmtList(UnitDie);
2152     NewTU.setSection(Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2153   }
2154 
2155   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2156   // units.
2157   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2158     NewTU.addStringOffsetsStart();
2159 
2160   NewTU.setType(NewTU.createTypeDIE(CTy));
2161 
2162   if (TopLevelType) {
2163     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2164     TypeUnitsUnderConstruction.clear();
2165 
2166     // Types referencing entries in the address table cannot be placed in type
2167     // units.
2168     if (AddrPool.hasBeenUsed()) {
2169 
2170       // Remove all the types built while building this type.
2171       // This is pessimistic as some of these types might not be dependent on
2172       // the type that used an address.
2173       for (const auto &TU : TypeUnitsToAdd)
2174         TypeSignatures.erase(TU.second);
2175 
2176       // Construct this type in the CU directly.
2177       // This is inefficient because all the dependent types will be rebuilt
2178       // from scratch, including building them in type units, discovering that
2179       // they depend on addresses, throwing them out and rebuilding them.
2180       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2181       return;
2182     }
2183 
2184     // If the type wasn't dependent on fission addresses, finish adding the type
2185     // and all its dependent types.
2186     for (auto &TU : TypeUnitsToAdd) {
2187       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2188       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2189     }
2190   }
2191   CU.addDIETypeSignature(RefDie, Signature);
2192 }
2193 
2194 // Accelerator table mutators - add each name along with its companion
2195 // DIE to the proper table while ensuring that the name that we're going
2196 // to reference is in the string table. We do this since the names we
2197 // add may not only be identical to the names in the DIE.
2198 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2199   if (!useDwarfAccelTables())
2200     return;
2201   AccelNames.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2202 }
2203 
2204 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2205   if (!useDwarfAccelTables())
2206     return;
2207   AccelObjC.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2208 }
2209 
2210 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2211   if (!useDwarfAccelTables())
2212     return;
2213   AccelNamespace.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2214 }
2215 
2216 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2217   if (!useDwarfAccelTables())
2218     return;
2219   AccelTypes.addName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2220 }
2221 
2222 uint16_t DwarfDebug::getDwarfVersion() const {
2223   return Asm->OutStreamer->getContext().getDwarfVersion();
2224 }
2225