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