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 enum LinkageNameOption {
109   DefaultLinkageNames,
110   AllLinkageNames,
111   AbstractLinkageNames
112 };
113 static cl::opt<LinkageNameOption>
114     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
115                       cl::desc("Which DWARF linkage-name attributes to emit."),
116                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
117                                             "Default for platform"),
118                                  clEnumValN(AllLinkageNames, "All", "All"),
119                                  clEnumValN(AbstractLinkageNames, "Abstract",
120                                             "Abstract subprograms"),
121                                  clEnumValEnd),
122                       cl::init(DefaultLinkageNames));
123 
124 static const char *const DWARFGroupName = "DWARF Emission";
125 static const char *const DbgTimerName = "DWARF Debug Writer";
126 
127 void DebugLocDwarfExpression::EmitOp(uint8_t Op, const char *Comment) {
128   BS.EmitInt8(
129       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
130                   : dwarf::OperationEncodingString(Op));
131 }
132 
133 void DebugLocDwarfExpression::EmitSigned(int64_t Value) {
134   BS.EmitSLEB128(Value, Twine(Value));
135 }
136 
137 void DebugLocDwarfExpression::EmitUnsigned(uint64_t Value) {
138   BS.EmitULEB128(Value, Twine(Value));
139 }
140 
141 bool DebugLocDwarfExpression::isFrameRegister(unsigned MachineReg) {
142   // This information is not available while emitting .debug_loc entries.
143   return false;
144 }
145 
146 //===----------------------------------------------------------------------===//
147 
148 bool DbgVariable::isBlockByrefVariable() const {
149   assert(Var && "Invalid complex DbgVariable!");
150   return Var->getType().resolve()->isBlockByrefStruct();
151 }
152 
153 const DIType *DbgVariable::getType() const {
154   DIType *Ty = Var->getType().resolve();
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 defaults to linkage names only for abstract subprograms.
249   if (DwarfLinkageNames == DefaultLinkageNames)
250     UseAllLinkageNames = !tuneForSCE();
251   else
252     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
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 = *CUMap.lookup(cast<DISubprogram>(SP)->getUnit());
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 bool DwarfDebug::collectLocalScopedNode(DIScope *S, const DINode *N,
461                                         DwarfCompileUnit &CU) {
462   if (auto LS = dyn_cast_or_null<DILocalScope>(S)) {
463     getLocalScopes(LS->getSubprogram()).insert(LS);
464     CU.addLocalDeclNode(N, LS);
465     return true;
466   }
467   return false;
468 }
469 
470 // Emit all Dwarf sections that should come prior to the content. Create
471 // global DIEs and emit initial debug info sections. This is invoked by
472 // the target AsmPrinter.
473 void DwarfDebug::beginModule() {
474   if (DisableDebugInfoPrinting)
475     return;
476 
477   const Module *M = MMI->getModule();
478 
479   unsigned NumDebugCUs = 0;
480   for (DICompileUnit *CUNode : M->debug_compile_units()) {
481     (void)CUNode;
482     ++NumDebugCUs;
483   }
484 
485   // Tell MMI whether we have debug info.
486   MMI->setDebugInfoAvailability(NumDebugCUs > 0);
487   SingleCU = NumDebugCUs == 1;
488 
489   for (DICompileUnit *CUNode : M->debug_compile_units()) {
490     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
491     for (auto *GV : CUNode->getGlobalVariables())
492       if (!collectLocalScopedNode(GV->getScope(), GV, CU))
493         CU.getOrCreateGlobalVariableDIE(GV);
494     for (auto *Ty : CUNode->getEnumTypes()) {
495       // The enum types array by design contains pointers to
496       // MDNodes rather than DIRefs. Unique them here.
497       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
498     }
499     for (auto *Ty : CUNode->getRetainedTypes()) {
500       // The retained types array by design contains pointers to
501       // MDNodes rather than DIRefs. Unique them here.
502       if (DIType *RT = dyn_cast<DIType>(Ty)) {
503         if (RT->isExternalTypeRef())
504           // There is no point in force-emitting a forward declaration.
505           continue;
506         if (!collectLocalScopedNode(resolve(Ty->getScope()), RT, CU))
507           CU.getOrCreateTypeDIE(RT);
508       }
509     }
510     // Emit imported_modules last so that the relevant context is already
511     // available.
512     for (auto *IE : CUNode->getImportedEntities())
513       if (!collectLocalScopedNode(IE->getScope(), IE, CU))
514         constructAndAddImportedEntityDIE(CU, IE);
515   }
516 }
517 
518 void DwarfDebug::finishVariableDefinitions() {
519   for (const auto &Var : ConcreteVariables) {
520     DIE *VariableDie = Var->getDIE();
521     assert(VariableDie);
522     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
523     // in the ConcreteVariables list, rather than looking it up again here.
524     // DIE::getUnit isn't simple - it walks parent pointers, etc.
525     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
526     assert(Unit);
527     DbgVariable *AbsVar = getExistingAbstractVariable(
528         InlinedVariable(Var->getVariable(), Var->getInlinedAt()));
529     if (AbsVar && AbsVar->getDIE()) {
530       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
531                         *AbsVar->getDIE());
532     } else
533       Unit->applyVariableAttributes(*Var, *VariableDie);
534   }
535 }
536 
537 void DwarfDebug::finishSubprogramDefinitions() {
538   for (auto &F : MMI->getModule()->functions())
539     if (auto *SP = F.getSubprogram())
540       if (ProcessedSPNodes.count(SP) &&
541           SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug)
542         forBothCUs(*CUMap.lookup(SP->getUnit()), [&](DwarfCompileUnit &CU) {
543           CU.finishSubprogramDefinition(SP);
544         });
545   for (auto *AbsScope : LScopes.getAbstractScopesList())
546     if (auto *SP = dyn_cast<DISubprogram>(AbsScope->getScopeNode()))
547       if (ProcessedSPNodes.count(SP) &&
548           SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug)
549         forBothCUs(*CUMap.lookup(SP->getUnit()), [&](DwarfCompileUnit &CU) {
550           CU.finishSubprogramDefinition(SP);
551         });
552 }
553 
554 void DwarfDebug::finishLocalScopeDefinitions() {
555   for (const auto &I : CUMap)
556     I.second->finishLocalScopeDefinitions();
557 }
558 
559 void DwarfDebug::finalizeModuleInfo() {
560   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
561 
562   finishSubprogramDefinitions();
563 
564   finishLocalScopeDefinitions();
565 
566   finishVariableDefinitions();
567 
568   // Handle anything that needs to be done on a per-unit basis after
569   // all other generation.
570   for (const auto &P : CUMap) {
571     auto &TheCU = *P.second;
572     // Emit DW_AT_containing_type attribute to connect types with their
573     // vtable holding type.
574     TheCU.constructContainingTypeDIEs();
575 
576     // Add CU specific attributes if we need to add any.
577     // If we're splitting the dwarf out now that we've got the entire
578     // CU then add the dwo id to it.
579     auto *SkCU = TheCU.getSkeleton();
580     if (useSplitDwarf()) {
581       // Emit a unique identifier for this CU.
582       uint64_t ID = DIEHash(Asm).computeCUSignature(TheCU.getUnitDie());
583       TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
584                     dwarf::DW_FORM_data8, ID);
585       SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
586                     dwarf::DW_FORM_data8, ID);
587 
588       // We don't keep track of which addresses are used in which CU so this
589       // is a bit pessimistic under LTO.
590       if (!AddrPool.isEmpty()) {
591         const MCSymbol *Sym = TLOF.getDwarfAddrSection()->getBeginSymbol();
592         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_addr_base,
593                               Sym, Sym);
594       }
595       if (!SkCU->getRangeLists().empty()) {
596         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
597         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
598                               Sym, Sym);
599       }
600     }
601 
602     // If we have code split among multiple sections or non-contiguous
603     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
604     // remain in the .o file, otherwise add a DW_AT_low_pc.
605     // FIXME: We should use ranges allow reordering of code ala
606     // .subsections_via_symbols in mach-o. This would mean turning on
607     // ranges for all subprogram DIEs for mach-o.
608     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
609     if (unsigned NumRanges = TheCU.getRanges().size()) {
610       if (NumRanges > 1)
611         // A DW_AT_low_pc attribute may also be specified in combination with
612         // DW_AT_ranges to specify the default base address for use in
613         // location lists (see Section 2.6.2) and range lists (see Section
614         // 2.17.3).
615         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
616       else
617         U.setBaseAddress(TheCU.getRanges().front().getStart());
618       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
619     }
620 
621     auto *CUNode = cast<DICompileUnit>(P.first);
622     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
623     if (CUNode->getMacros())
624       U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
625                         U.getMacroLabelBegin(),
626                         TLOF.getDwarfMacinfoSection()->getBeginSymbol());
627   }
628 
629   // Compute DIE offsets and sizes.
630   InfoHolder.computeSizeAndOffsets();
631   if (useSplitDwarf())
632     SkeletonHolder.computeSizeAndOffsets();
633 }
634 
635 // Emit all Dwarf sections that should come after the content.
636 void DwarfDebug::endModule() {
637   assert(CurFn == nullptr);
638   assert(CurMI == nullptr);
639 
640   // If we aren't actually generating debug info (check beginModule -
641   // conditionalized on !DisableDebugInfoPrinting and the presence of the
642   // llvm.dbg.cu metadata node)
643   if (!MMI->hasDebugInfo())
644     return;
645 
646   // Finalize the debug info for the module.
647   finalizeModuleInfo();
648 
649   emitDebugStr();
650 
651   if (useSplitDwarf())
652     emitDebugLocDWO();
653   else
654     // Emit info into a debug loc section.
655     emitDebugLoc();
656 
657   // Corresponding abbreviations into a abbrev section.
658   emitAbbreviations();
659 
660   // Emit all the DIEs into a debug info section.
661   emitDebugInfo();
662 
663   // Emit info into a debug aranges section.
664   if (GenerateARangeSection)
665     emitDebugARanges();
666 
667   // Emit info into a debug ranges section.
668   emitDebugRanges();
669 
670   // Emit info into a debug macinfo section.
671   emitDebugMacinfo();
672 
673   if (useSplitDwarf()) {
674     emitDebugStrDWO();
675     emitDebugInfoDWO();
676     emitDebugAbbrevDWO();
677     emitDebugLineDWO();
678     // Emit DWO addresses.
679     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
680   }
681 
682   // Emit info into the dwarf accelerator table sections.
683   if (useDwarfAccelTables()) {
684     emitAccelNames();
685     emitAccelObjC();
686     emitAccelNamespaces();
687     emitAccelTypes();
688   }
689 
690   // Emit the pubnames and pubtypes sections if requested.
691   if (HasDwarfPubSections) {
692     emitDebugPubNames(GenerateGnuPubSections);
693     emitDebugPubTypes(GenerateGnuPubSections);
694   }
695 
696   // clean up.
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);
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);
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(make_unique<DbgVariable>(IV.first, IV.second));
938   InfoHolder.addScopeVariable(&Scope, ConcreteVariables.back().get());
939   return ConcreteVariables.back().get();
940 }
941 
942 // Determine whether this DBG_VALUE is valid at the beginning of the function.
943 static bool validAtEntry(const MachineInstr *MInsn) {
944   auto MBB = MInsn->getParent();
945   // Is it in the entry basic block?
946   if (!MBB->pred_empty())
947     return false;
948   for (MachineBasicBlock::const_reverse_iterator I(MInsn); I != MBB->rend(); ++I)
949     if (!(I->isDebugValue() || I->getFlag(MachineInstr::FrameSetup)))
950       return false;
951   return true;
952 }
953 
954 // Find variables for each lexical scope.
955 void DwarfDebug::collectVariableInfo(DwarfCompileUnit &TheCU,
956                                      const DISubprogram *SP,
957                                      DenseSet<InlinedVariable> &Processed) {
958   // Grab the variable info that was squirreled away in the MMI side-table.
959   collectVariableInfoFromMMITable(Processed);
960 
961   for (const auto &I : DbgValues) {
962     InlinedVariable IV = I.first;
963     if (Processed.count(IV))
964       continue;
965 
966     // Instruction ranges, specifying where IV is accessible.
967     const auto &Ranges = I.second;
968     if (Ranges.empty())
969       continue;
970 
971     LexicalScope *Scope = nullptr;
972     if (const DILocation *IA = IV.second)
973       Scope = LScopes.findInlinedScope(IV.first->getScope(), IA);
974     else
975       Scope = LScopes.findLexicalScope(IV.first->getScope());
976     // If variable scope is not found then skip this variable.
977     if (!Scope)
978       continue;
979 
980     Processed.insert(IV);
981     DbgVariable *RegVar = createConcreteVariable(*Scope, IV);
982 
983     const MachineInstr *MInsn = Ranges.front().first;
984     assert(MInsn->isDebugValue() && "History must begin with debug value");
985 
986     // Check if there is a single DBG_VALUE, valid throughout the function.
987     // A single constant is also considered valid for the entire function.
988     if (Ranges.size() == 1 &&
989         (MInsn->getOperand(0).isImm() ||
990          (validAtEntry(MInsn) && Ranges.front().second == nullptr))) {
991       RegVar->initializeDbgValue(MInsn);
992       continue;
993     }
994 
995     // Handle multiple DBG_VALUE instructions describing one variable.
996     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
997 
998     // Build the location list for this variable.
999     SmallVector<DebugLocEntry, 8> Entries;
1000     buildLocationList(Entries, Ranges);
1001 
1002     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1003     // unique identifiers, so don't bother resolving the type with the
1004     // identifier map.
1005     const DIBasicType *BT = dyn_cast<DIBasicType>(
1006         static_cast<const Metadata *>(IV.first->getType()));
1007 
1008     // Finalize the entry by lowering it into a DWARF bytestream.
1009     for (auto &Entry : Entries)
1010       Entry.finalize(*Asm, List, BT);
1011   }
1012 
1013   // Collect info for variables that were optimized out.
1014   for (const DILocalVariable *DV : SP->getVariables()) {
1015     if (Processed.insert(InlinedVariable(DV, nullptr)).second)
1016       if (LexicalScope *Scope = LScopes.findLexicalScope(DV->getScope()))
1017         createConcreteVariable(*Scope, InlinedVariable(DV, nullptr));
1018   }
1019 }
1020 
1021 // Process beginning of an instruction.
1022 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1023   DebugHandlerBase::beginInstruction(MI);
1024   assert(CurMI);
1025 
1026   // Check if source location changes, but ignore DBG_VALUE locations.
1027   if (!MI->isDebugValue()) {
1028     DebugLoc DL = MI->getDebugLoc();
1029     if (DL != PrevInstLoc) {
1030       if (DL) {
1031         unsigned Flags = 0;
1032         PrevInstLoc = DL;
1033         if (DL == PrologEndLoc) {
1034           Flags |= DWARF2_FLAG_PROLOGUE_END;
1035           PrologEndLoc = DebugLoc();
1036           Flags |= DWARF2_FLAG_IS_STMT;
1037         }
1038         if (DL.getLine() !=
1039             Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine())
1040           Flags |= DWARF2_FLAG_IS_STMT;
1041 
1042         const MDNode *Scope = DL.getScope();
1043         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1044       } else if (UnknownLocations) {
1045         PrevInstLoc = DL;
1046         recordSourceLine(0, 0, nullptr, 0);
1047       }
1048     }
1049   }
1050 }
1051 
1052 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1053   // First known non-DBG_VALUE and non-frame setup location marks
1054   // the beginning of the function body.
1055   for (const auto &MBB : *MF)
1056     for (const auto &MI : MBB)
1057       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1058           MI.getDebugLoc())
1059         return MI.getDebugLoc();
1060   return DebugLoc();
1061 }
1062 
1063 // Gather pre-function debug information.  Assumes being called immediately
1064 // after the function entry point has been emitted.
1065 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1066   CurFn = MF;
1067 
1068   // If there's no debug info for the function we're not going to do anything.
1069   if (!MMI->hasDebugInfo())
1070     return;
1071 
1072   auto DI = MF->getFunction()->getSubprogram();
1073   if (!DI)
1074     return;
1075 
1076   // Grab the lexical scopes for the function, if we don't have any of those
1077   // then we're not going to be able to do anything.
1078   DebugHandlerBase::beginFunction(MF);
1079   if (LScopes.empty())
1080     return;
1081 
1082   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1083   // belongs to so that we add to the correct per-cu line table in the
1084   // non-asm case.
1085   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1086   // FnScope->getScopeNode() and DI->second should represent the same function,
1087   // though they may not be the same MDNode due to inline functions merged in
1088   // LTO where the debug info metadata still differs (either due to distinct
1089   // written differences - two versions of a linkonce_odr function
1090   // written/copied into two separate files, or some sub-optimal metadata that
1091   // isn't structurally identical (see: file path/name info from clang, which
1092   // includes the directory of the cpp file being built, even when the file name
1093   // is absolute (such as an <> lookup header)))
1094   auto *SP = cast<DISubprogram>(FnScope->getScopeNode());
1095   DwarfCompileUnit *TheCU = CUMap.lookup(SP->getUnit());
1096   if (!TheCU) {
1097     assert(SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug &&
1098            "DICompileUnit missing from llvm.dbg.cu?");
1099     return;
1100   }
1101   if (Asm->OutStreamer->hasRawTextSupport())
1102     // Use a single line table if we are generating assembly.
1103     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1104   else
1105     Asm->OutStreamer->getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1106 
1107   // Record beginning of function.
1108   PrologEndLoc = findPrologueEndLoc(MF);
1109   if (DILocation *L = PrologEndLoc) {
1110     // We'd like to list the prologue as "not statements" but GDB behaves
1111     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1112     auto *SP = L->getInlinedAtScope()->getSubprogram();
1113     recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1114   }
1115 }
1116 
1117 // Gather and emit post-function debug information.
1118 void DwarfDebug::endFunction(const MachineFunction *MF) {
1119   assert(CurFn == MF &&
1120       "endFunction should be called with the same function as beginFunction");
1121 
1122   const DISubprogram *SP = MF->getFunction()->getSubprogram();
1123   if (!MMI->hasDebugInfo() || LScopes.empty() || !SP ||
1124       SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug) {
1125     // If we don't have a lexical scope for this function then there will
1126     // be a hole in the range information. Keep note of this by setting the
1127     // previously used section to nullptr.
1128     PrevCU = nullptr;
1129     CurFn = nullptr;
1130     DebugHandlerBase::endFunction(MF);
1131     // Mark functions with no debug info on any instructions, but a
1132     // valid DISubprogram as processed.
1133     if (SP)
1134       ProcessedSPNodes.insert(SP);
1135     return;
1136   }
1137 
1138   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1139   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1140 
1141   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1142   SP = cast<DISubprogram>(FnScope->getScopeNode());
1143   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1144 
1145   DenseSet<InlinedVariable> ProcessedVars;
1146   collectVariableInfo(TheCU, SP, ProcessedVars);
1147 
1148   // Add the range of this function to the list of ranges for the CU.
1149   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1150 
1151   // Under -gmlt, skip building the subprogram if there are no inlined
1152   // subroutines inside it.
1153   if (TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1154       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1155     assert(InfoHolder.getScopeVariables().empty());
1156     assert(DbgValues.empty());
1157     // FIXME: This wouldn't be true in LTO with a -g (with inlining) CU followed
1158     // by a -gmlt CU. Add a test and remove this assertion.
1159     assert(AbstractVariables.empty());
1160     PrevLabel = nullptr;
1161     CurFn = nullptr;
1162     DebugHandlerBase::endFunction(MF);
1163     return;
1164   }
1165 
1166 #ifndef NDEBUG
1167   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1168 #endif
1169   // Construct abstract scopes.
1170   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1171     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1172     // Collect info for variables that were optimized out.
1173     for (const DILocalVariable *DV : SP->getVariables()) {
1174       if (!ProcessedVars.insert(InlinedVariable(DV, nullptr)).second)
1175         continue;
1176       ensureAbstractVariableIsCreated(InlinedVariable(DV, nullptr),
1177                                       DV->getScope());
1178       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1179              && "ensureAbstractVariableIsCreated inserted abstract scopes");
1180     }
1181     // Assure abstract local scope created for each one contains local DIEs.
1182     for (const DILocalScope *LS : getLocalScopes(SP))
1183       LScopes.getOrCreateAbstractScope(LS);
1184     constructAbstractSubprogramScopeDIE(AScope);
1185   }
1186 
1187   TheCU.constructSubprogramScopeDIE(FnScope);
1188   if (auto *SkelCU = TheCU.getSkeleton())
1189     if (!LScopes.getAbstractScopesList().empty())
1190       SkelCU->constructSubprogramScopeDIE(FnScope);
1191 
1192   // Clear debug info
1193   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1194   // DbgVariables except those that are also in AbstractVariables (since they
1195   // can be used cross-function)
1196   InfoHolder.getScopeVariables().clear();
1197   PrevLabel = nullptr;
1198   CurFn = nullptr;
1199   DebugHandlerBase::endFunction(MF);
1200 }
1201 
1202 // Register a source line with debug info. Returns the  unique label that was
1203 // emitted and which provides correspondence to the source line list.
1204 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1205                                   unsigned Flags) {
1206   StringRef Fn;
1207   StringRef Dir;
1208   unsigned Src = 1;
1209   unsigned Discriminator = 0;
1210   if (auto *Scope = cast_or_null<DIScope>(S)) {
1211     Fn = Scope->getFilename();
1212     Dir = Scope->getDirectory();
1213     if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1214       Discriminator = LBF->getDiscriminator();
1215 
1216     unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1217     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1218               .getOrCreateSourceID(Fn, Dir);
1219   }
1220   Asm->OutStreamer->EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1221                                           Discriminator, Fn);
1222 }
1223 
1224 //===----------------------------------------------------------------------===//
1225 // Emit Methods
1226 //===----------------------------------------------------------------------===//
1227 
1228 // Emit the debug info section.
1229 void DwarfDebug::emitDebugInfo() {
1230   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1231   Holder.emitUnits(/* UseOffsets */ false);
1232 }
1233 
1234 // Emit the abbreviation section.
1235 void DwarfDebug::emitAbbreviations() {
1236   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1237 
1238   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1239 }
1240 
1241 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, MCSection *Section,
1242                            StringRef TableName) {
1243   Accel.FinalizeTable(Asm, TableName);
1244   Asm->OutStreamer->SwitchSection(Section);
1245 
1246   // Emit the full data.
1247   Accel.emit(Asm, Section->getBeginSymbol(), this);
1248 }
1249 
1250 // Emit visible names into a hashed accelerator table section.
1251 void DwarfDebug::emitAccelNames() {
1252   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1253             "Names");
1254 }
1255 
1256 // Emit objective C classes and categories into a hashed accelerator table
1257 // section.
1258 void DwarfDebug::emitAccelObjC() {
1259   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1260             "ObjC");
1261 }
1262 
1263 // Emit namespace dies into a hashed accelerator table.
1264 void DwarfDebug::emitAccelNamespaces() {
1265   emitAccel(AccelNamespace,
1266             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1267             "namespac");
1268 }
1269 
1270 // Emit type dies into a hashed accelerator table.
1271 void DwarfDebug::emitAccelTypes() {
1272   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1273             "types");
1274 }
1275 
1276 // Public name handling.
1277 // The format for the various pubnames:
1278 //
1279 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1280 // for the DIE that is named.
1281 //
1282 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1283 // into the CU and the index value is computed according to the type of value
1284 // for the DIE that is named.
1285 //
1286 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1287 // it's the offset within the debug_info/debug_types dwo section, however, the
1288 // reference in the pubname header doesn't change.
1289 
1290 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1291 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1292                                                         const DIE *Die) {
1293   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1294 
1295   // We could have a specification DIE that has our most of our knowledge,
1296   // look for that now.
1297   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1298     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1299     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1300       Linkage = dwarf::GIEL_EXTERNAL;
1301   } else if (Die->findAttribute(dwarf::DW_AT_external))
1302     Linkage = dwarf::GIEL_EXTERNAL;
1303 
1304   switch (Die->getTag()) {
1305   case dwarf::DW_TAG_class_type:
1306   case dwarf::DW_TAG_structure_type:
1307   case dwarf::DW_TAG_union_type:
1308   case dwarf::DW_TAG_enumeration_type:
1309     return dwarf::PubIndexEntryDescriptor(
1310         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1311                               ? dwarf::GIEL_STATIC
1312                               : dwarf::GIEL_EXTERNAL);
1313   case dwarf::DW_TAG_typedef:
1314   case dwarf::DW_TAG_base_type:
1315   case dwarf::DW_TAG_subrange_type:
1316     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1317   case dwarf::DW_TAG_namespace:
1318     return dwarf::GIEK_TYPE;
1319   case dwarf::DW_TAG_subprogram:
1320     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1321   case dwarf::DW_TAG_variable:
1322     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1323   case dwarf::DW_TAG_enumerator:
1324     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1325                                           dwarf::GIEL_STATIC);
1326   default:
1327     return dwarf::GIEK_NONE;
1328   }
1329 }
1330 
1331 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1332 ///
1333 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1334   MCSection *PSec = GnuStyle
1335                         ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1336                         : Asm->getObjFileLowering().getDwarfPubNamesSection();
1337 
1338   emitDebugPubSection(GnuStyle, PSec, "Names",
1339                       &DwarfCompileUnit::getGlobalNames);
1340 }
1341 
1342 void DwarfDebug::emitDebugPubSection(
1343     bool GnuStyle, MCSection *PSec, StringRef Name,
1344     const StringMap<const DIE *> &(DwarfCompileUnit::*Accessor)() const) {
1345   for (const auto &NU : CUMap) {
1346     DwarfCompileUnit *TheU = NU.second;
1347 
1348     const auto &Globals = (TheU->*Accessor)();
1349 
1350     if (Globals.empty())
1351       continue;
1352 
1353     if (auto *Skeleton = TheU->getSkeleton())
1354       TheU = Skeleton;
1355 
1356     // Start the dwarf pubnames section.
1357     Asm->OutStreamer->SwitchSection(PSec);
1358 
1359     // Emit the header.
1360     Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1361     MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1362     MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1363     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1364 
1365     Asm->OutStreamer->EmitLabel(BeginLabel);
1366 
1367     Asm->OutStreamer->AddComment("DWARF Version");
1368     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1369 
1370     Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1371     Asm->emitDwarfSymbolReference(TheU->getLabelBegin());
1372 
1373     Asm->OutStreamer->AddComment("Compilation Unit Length");
1374     Asm->EmitInt32(TheU->getLength());
1375 
1376     // Emit the pubnames for this compilation unit.
1377     for (const auto &GI : Globals) {
1378       const char *Name = GI.getKeyData();
1379       const DIE *Entity = GI.second;
1380 
1381       Asm->OutStreamer->AddComment("DIE offset");
1382       Asm->EmitInt32(Entity->getOffset());
1383 
1384       if (GnuStyle) {
1385         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1386         Asm->OutStreamer->AddComment(
1387             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
1388             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1389         Asm->EmitInt8(Desc.toBits());
1390       }
1391 
1392       Asm->OutStreamer->AddComment("External Name");
1393       Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1394     }
1395 
1396     Asm->OutStreamer->AddComment("End Mark");
1397     Asm->EmitInt32(0);
1398     Asm->OutStreamer->EmitLabel(EndLabel);
1399   }
1400 }
1401 
1402 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
1403   MCSection *PSec = GnuStyle
1404                         ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1405                         : Asm->getObjFileLowering().getDwarfPubTypesSection();
1406 
1407   emitDebugPubSection(GnuStyle, PSec, "Types",
1408                       &DwarfCompileUnit::getGlobalTypes);
1409 }
1410 
1411 /// Emit null-terminated strings into a debug str section.
1412 void DwarfDebug::emitDebugStr() {
1413   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1414   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
1415 }
1416 
1417 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1418                                    const DebugLocStream::Entry &Entry) {
1419   auto &&Comments = DebugLocs.getComments(Entry);
1420   auto Comment = Comments.begin();
1421   auto End = Comments.end();
1422   for (uint8_t Byte : DebugLocs.getBytes(Entry))
1423     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1424 }
1425 
1426 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1427                               ByteStreamer &Streamer,
1428                               const DebugLocEntry::Value &Value,
1429                               unsigned PieceOffsetInBits) {
1430   DebugLocDwarfExpression DwarfExpr(*AP.MF->getSubtarget().getRegisterInfo(),
1431                                     AP.getDwarfDebug()->getDwarfVersion(),
1432                                     Streamer);
1433   // Regular entry.
1434   if (Value.isInt()) {
1435     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1436                BT->getEncoding() == dwarf::DW_ATE_signed_char))
1437       DwarfExpr.AddSignedConstant(Value.getInt());
1438     else
1439       DwarfExpr.AddUnsignedConstant(Value.getInt());
1440   } else if (Value.isLocation()) {
1441     MachineLocation Loc = Value.getLoc();
1442     const DIExpression *Expr = Value.getExpression();
1443     if (!Expr || !Expr->getNumElements())
1444       // Regular entry.
1445       AP.EmitDwarfRegOp(Streamer, Loc);
1446     else {
1447       // Complex address entry.
1448       if (Loc.getOffset()) {
1449         DwarfExpr.AddMachineRegIndirect(Loc.getReg(), Loc.getOffset());
1450         DwarfExpr.AddExpression(Expr->expr_op_begin(), Expr->expr_op_end(),
1451                                 PieceOffsetInBits);
1452       } else
1453         DwarfExpr.AddMachineRegExpression(Expr, Loc.getReg(),
1454                                           PieceOffsetInBits);
1455     }
1456   } else if (Value.isConstantFP()) {
1457     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1458     DwarfExpr.AddUnsignedConstant(RawBytes);
1459   }
1460 }
1461 
1462 void DebugLocEntry::finalize(const AsmPrinter &AP,
1463                              DebugLocStream::ListBuilder &List,
1464                              const DIBasicType *BT) {
1465   DebugLocStream::EntryBuilder Entry(List, Begin, End);
1466   BufferByteStreamer Streamer = Entry.getStreamer();
1467   const DebugLocEntry::Value &Value = Values[0];
1468   if (Value.isBitPiece()) {
1469     // Emit all pieces that belong to the same variable and range.
1470     assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
1471           return P.isBitPiece();
1472         }) && "all values are expected to be pieces");
1473     assert(std::is_sorted(Values.begin(), Values.end()) &&
1474            "pieces are expected to be sorted");
1475 
1476     unsigned Offset = 0;
1477     for (auto Piece : Values) {
1478       const DIExpression *Expr = Piece.getExpression();
1479       unsigned PieceOffset = Expr->getBitPieceOffset();
1480       unsigned PieceSize = Expr->getBitPieceSize();
1481       assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
1482       if (Offset < PieceOffset) {
1483         // The DWARF spec seriously mandates pieces with no locations for gaps.
1484         DebugLocDwarfExpression Expr(*AP.MF->getSubtarget().getRegisterInfo(),
1485                                      AP.getDwarfDebug()->getDwarfVersion(),
1486                                      Streamer);
1487         Expr.AddOpPiece(PieceOffset-Offset, 0);
1488         Offset += PieceOffset-Offset;
1489       }
1490       Offset += PieceSize;
1491 
1492       emitDebugLocValue(AP, BT, Streamer, Piece, PieceOffset);
1493     }
1494   } else {
1495     assert(Values.size() == 1 && "only pieces may have >1 value");
1496     emitDebugLocValue(AP, BT, Streamer, Value, 0);
1497   }
1498 }
1499 
1500 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1501   // Emit the size.
1502   Asm->OutStreamer->AddComment("Loc expr size");
1503   Asm->EmitInt16(DebugLocs.getBytes(Entry).size());
1504 
1505   // Emit the entry.
1506   APByteStreamer Streamer(*Asm);
1507   emitDebugLocEntry(Streamer, Entry);
1508 }
1509 
1510 // Emit locations into the debug loc section.
1511 void DwarfDebug::emitDebugLoc() {
1512   // Start the dwarf loc section.
1513   Asm->OutStreamer->SwitchSection(
1514       Asm->getObjFileLowering().getDwarfLocSection());
1515   unsigned char Size = Asm->getDataLayout().getPointerSize();
1516   for (const auto &List : DebugLocs.getLists()) {
1517     Asm->OutStreamer->EmitLabel(List.Label);
1518     const DwarfCompileUnit *CU = List.CU;
1519     for (const auto &Entry : DebugLocs.getEntries(List)) {
1520       // Set up the range. This range is relative to the entry point of the
1521       // compile unit. This is a hard coded 0 for low_pc when we're emitting
1522       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
1523       if (auto *Base = CU->getBaseAddress()) {
1524         Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
1525         Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
1526       } else {
1527         Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
1528         Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
1529       }
1530 
1531       emitDebugLocEntryLocation(Entry);
1532     }
1533     Asm->OutStreamer->EmitIntValue(0, Size);
1534     Asm->OutStreamer->EmitIntValue(0, Size);
1535   }
1536 }
1537 
1538 void DwarfDebug::emitDebugLocDWO() {
1539   Asm->OutStreamer->SwitchSection(
1540       Asm->getObjFileLowering().getDwarfLocDWOSection());
1541   for (const auto &List : DebugLocs.getLists()) {
1542     Asm->OutStreamer->EmitLabel(List.Label);
1543     for (const auto &Entry : DebugLocs.getEntries(List)) {
1544       // Just always use start_length for now - at least that's one address
1545       // rather than two. We could get fancier and try to, say, reuse an
1546       // address we know we've emitted elsewhere (the start of the function?
1547       // The start of the CU or CU subrange that encloses this range?)
1548       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
1549       unsigned idx = AddrPool.getIndex(Entry.BeginSym);
1550       Asm->EmitULEB128(idx);
1551       Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
1552 
1553       emitDebugLocEntryLocation(Entry);
1554     }
1555     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
1556   }
1557 }
1558 
1559 struct ArangeSpan {
1560   const MCSymbol *Start, *End;
1561 };
1562 
1563 // Emit a debug aranges section, containing a CU lookup for any
1564 // address we can tie back to a CU.
1565 void DwarfDebug::emitDebugARanges() {
1566   // Provides a unique id per text section.
1567   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
1568 
1569   // Filter labels by section.
1570   for (const SymbolCU &SCU : ArangeLabels) {
1571     if (SCU.Sym->isInSection()) {
1572       // Make a note of this symbol and it's section.
1573       MCSection *Section = &SCU.Sym->getSection();
1574       if (!Section->getKind().isMetadata())
1575         SectionMap[Section].push_back(SCU);
1576     } else {
1577       // Some symbols (e.g. common/bss on mach-o) can have no section but still
1578       // appear in the output. This sucks as we rely on sections to build
1579       // arange spans. We can do it without, but it's icky.
1580       SectionMap[nullptr].push_back(SCU);
1581     }
1582   }
1583 
1584   // Add terminating symbols for each section.
1585   for (const auto &I : SectionMap) {
1586     MCSection *Section = I.first;
1587     MCSymbol *Sym = nullptr;
1588 
1589     if (Section)
1590       Sym = Asm->OutStreamer->endSection(Section);
1591 
1592     // Insert a final terminator.
1593     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
1594   }
1595 
1596   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
1597 
1598   for (auto &I : SectionMap) {
1599     const MCSection *Section = I.first;
1600     SmallVector<SymbolCU, 8> &List = I.second;
1601     if (List.size() < 2)
1602       continue;
1603 
1604     // If we have no section (e.g. common), just write out
1605     // individual spans for each symbol.
1606     if (!Section) {
1607       for (const SymbolCU &Cur : List) {
1608         ArangeSpan Span;
1609         Span.Start = Cur.Sym;
1610         Span.End = nullptr;
1611         if (Cur.CU)
1612           Spans[Cur.CU].push_back(Span);
1613       }
1614       continue;
1615     }
1616 
1617     // Sort the symbols by offset within the section.
1618     std::sort(List.begin(), List.end(),
1619               [&](const SymbolCU &A, const SymbolCU &B) {
1620       unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
1621       unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
1622 
1623       // Symbols with no order assigned should be placed at the end.
1624       // (e.g. section end labels)
1625       if (IA == 0)
1626         return false;
1627       if (IB == 0)
1628         return true;
1629       return IA < IB;
1630     });
1631 
1632     // Build spans between each label.
1633     const MCSymbol *StartSym = List[0].Sym;
1634     for (size_t n = 1, e = List.size(); n < e; n++) {
1635       const SymbolCU &Prev = List[n - 1];
1636       const SymbolCU &Cur = List[n];
1637 
1638       // Try and build the longest span we can within the same CU.
1639       if (Cur.CU != Prev.CU) {
1640         ArangeSpan Span;
1641         Span.Start = StartSym;
1642         Span.End = Cur.Sym;
1643         Spans[Prev.CU].push_back(Span);
1644         StartSym = Cur.Sym;
1645       }
1646     }
1647   }
1648 
1649   // Start the dwarf aranges section.
1650   Asm->OutStreamer->SwitchSection(
1651       Asm->getObjFileLowering().getDwarfARangesSection());
1652 
1653   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
1654 
1655   // Build a list of CUs used.
1656   std::vector<DwarfCompileUnit *> CUs;
1657   for (const auto &it : Spans) {
1658     DwarfCompileUnit *CU = it.first;
1659     CUs.push_back(CU);
1660   }
1661 
1662   // Sort the CU list (again, to ensure consistent output order).
1663   std::sort(CUs.begin(), CUs.end(),
1664             [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
1665               return A->getUniqueID() < B->getUniqueID();
1666             });
1667 
1668   // Emit an arange table for each CU we used.
1669   for (DwarfCompileUnit *CU : CUs) {
1670     std::vector<ArangeSpan> &List = Spans[CU];
1671 
1672     // Describe the skeleton CU's offset and length, not the dwo file's.
1673     if (auto *Skel = CU->getSkeleton())
1674       CU = Skel;
1675 
1676     // Emit size of content not including length itself.
1677     unsigned ContentSize =
1678         sizeof(int16_t) + // DWARF ARange version number
1679         sizeof(int32_t) + // Offset of CU in the .debug_info section
1680         sizeof(int8_t) +  // Pointer Size (in bytes)
1681         sizeof(int8_t);   // Segment Size (in bytes)
1682 
1683     unsigned TupleSize = PtrSize * 2;
1684 
1685     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
1686     unsigned Padding =
1687         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
1688 
1689     ContentSize += Padding;
1690     ContentSize += (List.size() + 1) * TupleSize;
1691 
1692     // For each compile unit, write the list of spans it covers.
1693     Asm->OutStreamer->AddComment("Length of ARange Set");
1694     Asm->EmitInt32(ContentSize);
1695     Asm->OutStreamer->AddComment("DWARF Arange version number");
1696     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
1697     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
1698     Asm->emitDwarfSymbolReference(CU->getLabelBegin());
1699     Asm->OutStreamer->AddComment("Address Size (in bytes)");
1700     Asm->EmitInt8(PtrSize);
1701     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
1702     Asm->EmitInt8(0);
1703 
1704     Asm->OutStreamer->EmitFill(Padding, 0xff);
1705 
1706     for (const ArangeSpan &Span : List) {
1707       Asm->EmitLabelReference(Span.Start, PtrSize);
1708 
1709       // Calculate the size as being from the span start to it's end.
1710       if (Span.End) {
1711         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
1712       } else {
1713         // For symbols without an end marker (e.g. common), we
1714         // write a single arange entry containing just that one symbol.
1715         uint64_t Size = SymSize[Span.Start];
1716         if (Size == 0)
1717           Size = 1;
1718 
1719         Asm->OutStreamer->EmitIntValue(Size, PtrSize);
1720       }
1721     }
1722 
1723     Asm->OutStreamer->AddComment("ARange terminator");
1724     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1725     Asm->OutStreamer->EmitIntValue(0, PtrSize);
1726   }
1727 }
1728 
1729 /// Emit address ranges into a debug ranges section.
1730 void DwarfDebug::emitDebugRanges() {
1731   // Start the dwarf ranges section.
1732   Asm->OutStreamer->SwitchSection(
1733       Asm->getObjFileLowering().getDwarfRangesSection());
1734 
1735   // Size for our labels.
1736   unsigned char Size = Asm->getDataLayout().getPointerSize();
1737 
1738   // Grab the specific ranges for the compile units in the module.
1739   for (const auto &I : CUMap) {
1740     DwarfCompileUnit *TheCU = I.second;
1741 
1742     if (auto *Skel = TheCU->getSkeleton())
1743       TheCU = Skel;
1744 
1745     // Iterate over the misc ranges for the compile units in the module.
1746     for (const RangeSpanList &List : TheCU->getRangeLists()) {
1747       // Emit our symbol so we can find the beginning of the range.
1748       Asm->OutStreamer->EmitLabel(List.getSym());
1749 
1750       for (const RangeSpan &Range : List.getRanges()) {
1751         const MCSymbol *Begin = Range.getStart();
1752         const MCSymbol *End = Range.getEnd();
1753         assert(Begin && "Range without a begin symbol?");
1754         assert(End && "Range without an end symbol?");
1755         if (auto *Base = TheCU->getBaseAddress()) {
1756           Asm->EmitLabelDifference(Begin, Base, Size);
1757           Asm->EmitLabelDifference(End, Base, Size);
1758         } else {
1759           Asm->OutStreamer->EmitSymbolValue(Begin, Size);
1760           Asm->OutStreamer->EmitSymbolValue(End, Size);
1761         }
1762       }
1763 
1764       // And terminate the list with two 0 values.
1765       Asm->OutStreamer->EmitIntValue(0, Size);
1766       Asm->OutStreamer->EmitIntValue(0, Size);
1767     }
1768   }
1769 }
1770 
1771 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
1772   for (auto *MN : Nodes) {
1773     if (auto *M = dyn_cast<DIMacro>(MN))
1774       emitMacro(*M);
1775     else if (auto *F = dyn_cast<DIMacroFile>(MN))
1776       emitMacroFile(*F, U);
1777     else
1778       llvm_unreachable("Unexpected DI type!");
1779   }
1780 }
1781 
1782 void DwarfDebug::emitMacro(DIMacro &M) {
1783   Asm->EmitULEB128(M.getMacinfoType());
1784   Asm->EmitULEB128(M.getLine());
1785   StringRef Name = M.getName();
1786   StringRef Value = M.getValue();
1787   Asm->OutStreamer->EmitBytes(Name);
1788   if (!Value.empty()) {
1789     // There should be one space between macro name and macro value.
1790     Asm->EmitInt8(' ');
1791     Asm->OutStreamer->EmitBytes(Value);
1792   }
1793   Asm->EmitInt8('\0');
1794 }
1795 
1796 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
1797   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
1798   Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
1799   Asm->EmitULEB128(F.getLine());
1800   DIFile *File = F.getFile();
1801   unsigned FID =
1802       U.getOrCreateSourceID(File->getFilename(), File->getDirectory());
1803   Asm->EmitULEB128(FID);
1804   handleMacroNodes(F.getElements(), U);
1805   Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
1806 }
1807 
1808 /// Emit macros into a debug macinfo section.
1809 void DwarfDebug::emitDebugMacinfo() {
1810   // Start the dwarf macinfo section.
1811   Asm->OutStreamer->SwitchSection(
1812       Asm->getObjFileLowering().getDwarfMacinfoSection());
1813 
1814   for (const auto &P : CUMap) {
1815     auto &TheCU = *P.second;
1816     auto *SkCU = TheCU.getSkeleton();
1817     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
1818     auto *CUNode = cast<DICompileUnit>(P.first);
1819     Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
1820     handleMacroNodes(CUNode->getMacros(), U);
1821   }
1822   Asm->OutStreamer->AddComment("End Of Macro List Mark");
1823   Asm->EmitInt8(0);
1824 }
1825 
1826 // DWARF5 Experimental Separate Dwarf emitters.
1827 
1828 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
1829                                   std::unique_ptr<DwarfCompileUnit> NewU) {
1830   NewU->addString(Die, dwarf::DW_AT_GNU_dwo_name,
1831                   U.getCUNode()->getSplitDebugFilename());
1832 
1833   if (!CompilationDir.empty())
1834     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
1835 
1836   addGnuPubAttributes(*NewU, Die);
1837 
1838   SkeletonHolder.addUnit(std::move(NewU));
1839 }
1840 
1841 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
1842 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
1843 // DW_AT_addr_base, DW_AT_ranges_base.
1844 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
1845 
1846   auto OwnedUnit = make_unique<DwarfCompileUnit>(
1847       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
1848   DwarfCompileUnit &NewCU = *OwnedUnit;
1849   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection());
1850 
1851   NewCU.initStmtList();
1852 
1853   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
1854 
1855   return NewCU;
1856 }
1857 
1858 // Emit the .debug_info.dwo section for separated dwarf. This contains the
1859 // compile units that would normally be in debug_info.
1860 void DwarfDebug::emitDebugInfoDWO() {
1861   assert(useSplitDwarf() && "No split dwarf debug info?");
1862   // Don't emit relocations into the dwo file.
1863   InfoHolder.emitUnits(/* UseOffsets */ true);
1864 }
1865 
1866 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
1867 // abbreviations for the .debug_info.dwo section.
1868 void DwarfDebug::emitDebugAbbrevDWO() {
1869   assert(useSplitDwarf() && "No split dwarf?");
1870   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
1871 }
1872 
1873 void DwarfDebug::emitDebugLineDWO() {
1874   assert(useSplitDwarf() && "No split dwarf?");
1875   Asm->OutStreamer->SwitchSection(
1876       Asm->getObjFileLowering().getDwarfLineDWOSection());
1877   SplitTypeUnitFileTable.Emit(*Asm->OutStreamer, MCDwarfLineTableParams());
1878 }
1879 
1880 // Emit the .debug_str.dwo section for separated dwarf. This contains the
1881 // string section and is identical in format to traditional .debug_str
1882 // sections.
1883 void DwarfDebug::emitDebugStrDWO() {
1884   assert(useSplitDwarf() && "No split dwarf?");
1885   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
1886   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
1887                          OffSec);
1888 }
1889 
1890 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
1891   if (!useSplitDwarf())
1892     return nullptr;
1893   if (SingleCU)
1894     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode()->getDirectory());
1895   return &SplitTypeUnitFileTable;
1896 }
1897 
1898 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
1899   MD5 Hash;
1900   Hash.update(Identifier);
1901   // ... take the least significant 8 bytes and return those. Our MD5
1902   // implementation always returns its results in little endian, swap bytes
1903   // appropriately.
1904   MD5::MD5Result Result;
1905   Hash.final(Result);
1906   return support::endian::read64le(Result + 8);
1907 }
1908 
1909 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
1910                                       StringRef Identifier, DIE &RefDie,
1911                                       const DICompositeType *CTy) {
1912   // Fast path if we're building some type units and one has already used the
1913   // address pool we know we're going to throw away all this work anyway, so
1914   // don't bother building dependent types.
1915   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
1916     return;
1917 
1918   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
1919   if (!Ins.second) {
1920     CU.addDIETypeSignature(RefDie, Ins.first->second);
1921     return;
1922   }
1923 
1924   bool TopLevelType = TypeUnitsUnderConstruction.empty();
1925   AddrPool.resetUsedFlag();
1926 
1927   auto OwnedUnit = make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
1928                                               getDwoLineTable(CU));
1929   DwarfTypeUnit &NewTU = *OwnedUnit;
1930   DIE &UnitDie = NewTU.getUnitDie();
1931   TypeUnitsUnderConstruction.push_back(
1932       std::make_pair(std::move(OwnedUnit), CTy));
1933 
1934   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
1935                 CU.getLanguage());
1936 
1937   uint64_t Signature = makeTypeSignature(Identifier);
1938   NewTU.setTypeSignature(Signature);
1939   Ins.first->second = Signature;
1940 
1941   if (useSplitDwarf())
1942     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection());
1943   else {
1944     CU.applyStmtList(UnitDie);
1945     NewTU.initSection(
1946         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
1947   }
1948 
1949   NewTU.setType(NewTU.createTypeDIE(CTy));
1950 
1951   if (TopLevelType) {
1952     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
1953     TypeUnitsUnderConstruction.clear();
1954 
1955     // Types referencing entries in the address table cannot be placed in type
1956     // units.
1957     if (AddrPool.hasBeenUsed()) {
1958 
1959       // Remove all the types built while building this type.
1960       // This is pessimistic as some of these types might not be dependent on
1961       // the type that used an address.
1962       for (const auto &TU : TypeUnitsToAdd)
1963         TypeSignatures.erase(TU.second);
1964 
1965       // Construct this type in the CU directly.
1966       // This is inefficient because all the dependent types will be rebuilt
1967       // from scratch, including building them in type units, discovering that
1968       // they depend on addresses, throwing them out and rebuilding them.
1969       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
1970       return;
1971     }
1972 
1973     // If the type wasn't dependent on fission addresses, finish adding the type
1974     // and all its dependent types.
1975     for (auto &TU : TypeUnitsToAdd) {
1976       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
1977       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
1978     }
1979   }
1980   CU.addDIETypeSignature(RefDie, Signature);
1981 }
1982 
1983 // Accelerator table mutators - add each name along with its companion
1984 // DIE to the proper table while ensuring that the name that we're going
1985 // to reference is in the string table. We do this since the names we
1986 // add may not only be identical to the names in the DIE.
1987 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
1988   if (!useDwarfAccelTables())
1989     return;
1990   AccelNames.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
1991 }
1992 
1993 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
1994   if (!useDwarfAccelTables())
1995     return;
1996   AccelObjC.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
1997 }
1998 
1999 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2000   if (!useDwarfAccelTables())
2001     return;
2002   AccelNamespace.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2003 }
2004 
2005 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2006   if (!useDwarfAccelTables())
2007     return;
2008   AccelTypes.AddName(InfoHolder.getStringPool().getEntry(*Asm, Name), &Die);
2009 }
2010