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