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