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