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