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