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