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