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