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