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