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