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