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 "DebugLocStream.h"
19 #include "DwarfCompileUnit.h"
20 #include "DwarfExpression.h"
21 #include "DwarfFile.h"
22 #include "DwarfUnit.h"
23 #include "llvm/ADT/APInt.h"
24 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/DenseSet.h"
26 #include "llvm/ADT/MapVector.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/ADT/Twine.h"
32 #include "llvm/BinaryFormat/Dwarf.h"
33 #include "llvm/CodeGen/AccelTable.h"
34 #include "llvm/CodeGen/AsmPrinter.h"
35 #include "llvm/CodeGen/DIE.h"
36 #include "llvm/CodeGen/LexicalScopes.h"
37 #include "llvm/CodeGen/MachineBasicBlock.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineModuleInfo.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/TargetInstrInfo.h"
43 #include "llvm/CodeGen/TargetRegisterInfo.h"
44 #include "llvm/CodeGen/TargetSubtargetInfo.h"
45 #include "llvm/IR/Constants.h"
46 #include "llvm/IR/DebugInfoMetadata.h"
47 #include "llvm/IR/DebugLoc.h"
48 #include "llvm/IR/Function.h"
49 #include "llvm/IR/GlobalVariable.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/MC/MCAsmInfo.h"
52 #include "llvm/MC/MCContext.h"
53 #include "llvm/MC/MCDwarf.h"
54 #include "llvm/MC/MCSection.h"
55 #include "llvm/MC/MCStreamer.h"
56 #include "llvm/MC/MCSymbol.h"
57 #include "llvm/MC/MCTargetOptions.h"
58 #include "llvm/MC/MachineLocation.h"
59 #include "llvm/MC/SectionKind.h"
60 #include "llvm/Pass.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CommandLine.h"
63 #include "llvm/Support/Debug.h"
64 #include "llvm/Support/ErrorHandling.h"
65 #include "llvm/Support/MD5.h"
66 #include "llvm/Support/MathExtras.h"
67 #include "llvm/Support/Timer.h"
68 #include "llvm/Support/raw_ostream.h"
69 #include "llvm/Target/TargetLoweringObjectFile.h"
70 #include "llvm/Target/TargetMachine.h"
71 #include "llvm/Target/TargetOptions.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstddef>
75 #include <cstdint>
76 #include <iterator>
77 #include <string>
78 #include <utility>
79 #include <vector>
80 
81 using namespace llvm;
82 
83 #define DEBUG_TYPE "dwarfdebug"
84 
85 static cl::opt<bool>
86 DisableDebugInfoPrinting("disable-debug-info-print", cl::Hidden,
87                          cl::desc("Disable debug info printing"));
88 
89 static cl::opt<bool> UseDwarfRangesBaseAddressSpecifier(
90     "use-dwarf-ranges-base-address-specifier", cl::Hidden,
91     cl::desc("Use base address specifiers in debug_ranges"), cl::init(false));
92 
93 static cl::opt<bool> GenerateARangeSection("generate-arange-section",
94                                            cl::Hidden,
95                                            cl::desc("Generate dwarf aranges"),
96                                            cl::init(false));
97 
98 static cl::opt<bool>
99     GenerateDwarfTypeUnits("generate-type-units", cl::Hidden,
100                            cl::desc("Generate DWARF4 type units."),
101                            cl::init(false));
102 
103 static cl::opt<bool> SplitDwarfCrossCuReferences(
104     "split-dwarf-cross-cu-references", cl::Hidden,
105     cl::desc("Enable cross-cu references in DWO files"), cl::init(false));
106 
107 enum DefaultOnOff { Default, Enable, Disable };
108 
109 static cl::opt<DefaultOnOff> UnknownLocations(
110     "use-unknown-locations", cl::Hidden,
111     cl::desc("Make an absence of debug location information explicit."),
112     cl::values(clEnumVal(Default, "At top of block or after label"),
113                clEnumVal(Enable, "In all cases"), clEnumVal(Disable, "Never")),
114     cl::init(Default));
115 
116 static cl::opt<AccelTableKind> AccelTables(
117     "accel-tables", cl::Hidden, cl::desc("Output dwarf accelerator tables."),
118     cl::values(clEnumValN(AccelTableKind::Default, "Default",
119                           "Default for platform"),
120                clEnumValN(AccelTableKind::None, "Disable", "Disabled."),
121                clEnumValN(AccelTableKind::Apple, "Apple", "Apple"),
122                clEnumValN(AccelTableKind::Dwarf, "Dwarf", "DWARF")),
123     cl::init(AccelTableKind::Default));
124 
125 static cl::opt<DefaultOnOff>
126 DwarfInlinedStrings("dwarf-inlined-strings", cl::Hidden,
127                  cl::desc("Use inlined strings rather than string section."),
128                  cl::values(clEnumVal(Default, "Default for platform"),
129                             clEnumVal(Enable, "Enabled"),
130                             clEnumVal(Disable, "Disabled")),
131                  cl::init(Default));
132 
133 static cl::opt<bool>
134     NoDwarfRangesSection("no-dwarf-ranges-section", cl::Hidden,
135                          cl::desc("Disable emission .debug_ranges section."),
136                          cl::init(false));
137 
138 static cl::opt<DefaultOnOff> DwarfSectionsAsReferences(
139     "dwarf-sections-as-references", cl::Hidden,
140     cl::desc("Use sections+offset as references rather than labels."),
141     cl::values(clEnumVal(Default, "Default for platform"),
142                clEnumVal(Enable, "Enabled"), clEnumVal(Disable, "Disabled")),
143     cl::init(Default));
144 
145 enum LinkageNameOption {
146   DefaultLinkageNames,
147   AllLinkageNames,
148   AbstractLinkageNames
149 };
150 
151 static cl::opt<LinkageNameOption>
152     DwarfLinkageNames("dwarf-linkage-names", cl::Hidden,
153                       cl::desc("Which DWARF linkage-name attributes to emit."),
154                       cl::values(clEnumValN(DefaultLinkageNames, "Default",
155                                             "Default for platform"),
156                                  clEnumValN(AllLinkageNames, "All", "All"),
157                                  clEnumValN(AbstractLinkageNames, "Abstract",
158                                             "Abstract subprograms")),
159                       cl::init(DefaultLinkageNames));
160 
161 static const char *const DWARFGroupName = "dwarf";
162 static const char *const DWARFGroupDescription = "DWARF Emission";
163 static const char *const DbgTimerName = "writer";
164 static const char *const DbgTimerDescription = "DWARF Debug Writer";
165 
166 void DebugLocDwarfExpression::emitOp(uint8_t Op, const char *Comment) {
167   BS.EmitInt8(
168       Op, Comment ? Twine(Comment) + " " + dwarf::OperationEncodingString(Op)
169                   : dwarf::OperationEncodingString(Op));
170 }
171 
172 void DebugLocDwarfExpression::emitSigned(int64_t Value) {
173   BS.EmitSLEB128(Value, Twine(Value));
174 }
175 
176 void DebugLocDwarfExpression::emitUnsigned(uint64_t Value) {
177   BS.EmitULEB128(Value, Twine(Value));
178 }
179 
180 bool DebugLocDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI,
181                                               unsigned MachineReg) {
182   // This information is not available while emitting .debug_loc entries.
183   return false;
184 }
185 
186 bool DbgVariable::isBlockByrefVariable() const {
187   assert(getVariable() && "Invalid complex DbgVariable!");
188   return getVariable()->getType().resolve()->isBlockByrefStruct();
189 }
190 
191 const DIType *DbgVariable::getType() const {
192   DIType *Ty = getVariable()->getType().resolve();
193   // FIXME: isBlockByrefVariable should be reformulated in terms of complex
194   // addresses instead.
195   if (Ty->isBlockByrefStruct()) {
196     /* Byref variables, in Blocks, are declared by the programmer as
197        "SomeType VarName;", but the compiler creates a
198        __Block_byref_x_VarName struct, and gives the variable VarName
199        either the struct, or a pointer to the struct, as its type.  This
200        is necessary for various behind-the-scenes things the compiler
201        needs to do with by-reference variables in blocks.
202 
203        However, as far as the original *programmer* is concerned, the
204        variable should still have type 'SomeType', as originally declared.
205 
206        The following function dives into the __Block_byref_x_VarName
207        struct to find the original type of the variable.  This will be
208        passed back to the code generating the type for the Debug
209        Information Entry for the variable 'VarName'.  'VarName' will then
210        have the original type 'SomeType' in its debug information.
211 
212        The original type 'SomeType' will be the type of the field named
213        'VarName' inside the __Block_byref_x_VarName struct.
214 
215        NOTE: In order for this to not completely fail on the debugger
216        side, the Debug Information Entry for the variable VarName needs to
217        have a DW_AT_location that tells the debugger how to unwind through
218        the pointers and __Block_byref_x_VarName struct to find the actual
219        value of the variable.  The function addBlockByrefType does this.  */
220     DIType *subType = Ty;
221     uint16_t tag = Ty->getTag();
222 
223     if (tag == dwarf::DW_TAG_pointer_type)
224       subType = resolve(cast<DIDerivedType>(Ty)->getBaseType());
225 
226     auto Elements = cast<DICompositeType>(subType)->getElements();
227     for (unsigned i = 0, N = Elements.size(); i < N; ++i) {
228       auto *DT = cast<DIDerivedType>(Elements[i]);
229       if (getName() == DT->getName())
230         return resolve(DT->getBaseType());
231     }
232   }
233   return Ty;
234 }
235 
236 ArrayRef<DbgVariable::FrameIndexExpr> DbgVariable::getFrameIndexExprs() const {
237   if (FrameIndexExprs.size() == 1)
238     return FrameIndexExprs;
239 
240   assert(llvm::all_of(FrameIndexExprs,
241                       [](const FrameIndexExpr &A) {
242                         return A.Expr->isFragment();
243                       }) &&
244          "multiple FI expressions without DW_OP_LLVM_fragment");
245   llvm::sort(FrameIndexExprs,
246              [](const FrameIndexExpr &A, const FrameIndexExpr &B) -> bool {
247                return A.Expr->getFragmentInfo()->OffsetInBits <
248                       B.Expr->getFragmentInfo()->OffsetInBits;
249              });
250 
251   return FrameIndexExprs;
252 }
253 
254 void DbgVariable::addMMIEntry(const DbgVariable &V) {
255   assert(DebugLocListIndex == ~0U && !MInsn && "not an MMI entry");
256   assert(V.DebugLocListIndex == ~0U && !V.MInsn && "not an MMI entry");
257   assert(V.getVariable() == getVariable() && "conflicting variable");
258   assert(V.getInlinedAt() == getInlinedAt() && "conflicting inlined-at location");
259 
260   assert(!FrameIndexExprs.empty() && "Expected an MMI entry");
261   assert(!V.FrameIndexExprs.empty() && "Expected an MMI entry");
262 
263   // FIXME: This logic should not be necessary anymore, as we now have proper
264   // deduplication. However, without it, we currently run into the assertion
265   // below, which means that we are likely dealing with broken input, i.e. two
266   // non-fragment entries for the same variable at different frame indices.
267   if (FrameIndexExprs.size()) {
268     auto *Expr = FrameIndexExprs.back().Expr;
269     if (!Expr || !Expr->isFragment())
270       return;
271   }
272 
273   for (const auto &FIE : V.FrameIndexExprs)
274     // Ignore duplicate entries.
275     if (llvm::none_of(FrameIndexExprs, [&](const FrameIndexExpr &Other) {
276           return FIE.FI == Other.FI && FIE.Expr == Other.Expr;
277         }))
278       FrameIndexExprs.push_back(FIE);
279 
280   assert((FrameIndexExprs.size() == 1 ||
281           llvm::all_of(FrameIndexExprs,
282                        [](FrameIndexExpr &FIE) {
283                          return FIE.Expr && FIE.Expr->isFragment();
284                        })) &&
285          "conflicting locations for variable");
286 }
287 
288 static AccelTableKind computeAccelTableKind(unsigned DwarfVersion,
289                                             bool GenerateTypeUnits,
290                                             DebuggerKind Tuning,
291                                             const Triple &TT) {
292   // Honor an explicit request.
293   if (AccelTables != AccelTableKind::Default)
294     return AccelTables;
295 
296   // Accelerator tables with type units are currently not supported.
297   if (GenerateTypeUnits)
298     return AccelTableKind::None;
299 
300   // Accelerator tables get emitted if targetting DWARF v5 or LLDB.  DWARF v5
301   // always implies debug_names. For lower standard versions we use apple
302   // accelerator tables on apple platforms and debug_names elsewhere.
303   if (DwarfVersion >= 5)
304     return AccelTableKind::Dwarf;
305   if (Tuning == DebuggerKind::LLDB)
306     return TT.isOSBinFormatMachO() ? AccelTableKind::Apple
307                                    : AccelTableKind::Dwarf;
308   return AccelTableKind::None;
309 }
310 
311 DwarfDebug::DwarfDebug(AsmPrinter *A, Module *M)
312     : DebugHandlerBase(A), DebugLocs(A->OutStreamer->isVerboseAsm()),
313       InfoHolder(A, "info_string", DIEValueAllocator),
314       SkeletonHolder(A, "skel_string", DIEValueAllocator),
315       IsDarwin(A->TM.getTargetTriple().isOSDarwin()) {
316   const Triple &TT = Asm->TM.getTargetTriple();
317 
318   // Make sure we know our "debugger tuning."  The target option takes
319   // precedence; fall back to triple-based defaults.
320   if (Asm->TM.Options.DebuggerTuning != DebuggerKind::Default)
321     DebuggerTuning = Asm->TM.Options.DebuggerTuning;
322   else if (IsDarwin)
323     DebuggerTuning = DebuggerKind::LLDB;
324   else if (TT.isPS4CPU())
325     DebuggerTuning = DebuggerKind::SCE;
326   else
327     DebuggerTuning = DebuggerKind::GDB;
328 
329   if (DwarfInlinedStrings == Default)
330     UseInlineStrings = TT.isNVPTX();
331   else
332     UseInlineStrings = DwarfInlinedStrings == Enable;
333 
334   UseLocSection = !TT.isNVPTX();
335 
336   HasAppleExtensionAttributes = tuneForLLDB();
337 
338   // Handle split DWARF.
339   HasSplitDwarf = !Asm->TM.Options.MCOptions.SplitDwarfFile.empty();
340 
341   // SCE defaults to linkage names only for abstract subprograms.
342   if (DwarfLinkageNames == DefaultLinkageNames)
343     UseAllLinkageNames = !tuneForSCE();
344   else
345     UseAllLinkageNames = DwarfLinkageNames == AllLinkageNames;
346 
347   unsigned DwarfVersionNumber = Asm->TM.Options.MCOptions.DwarfVersion;
348   unsigned DwarfVersion = DwarfVersionNumber ? DwarfVersionNumber
349                                     : MMI->getModule()->getDwarfVersion();
350   // Use dwarf 4 by default if nothing is requested. For NVPTX, use dwarf 2.
351   DwarfVersion =
352       TT.isNVPTX() ? 2 : (DwarfVersion ? DwarfVersion : dwarf::DWARF_VERSION);
353 
354   UseRangesSection = !NoDwarfRangesSection && !TT.isNVPTX();
355 
356   // Use sections as references. Force for NVPTX.
357   if (DwarfSectionsAsReferences == Default)
358     UseSectionsAsReferences = TT.isNVPTX();
359   else
360     UseSectionsAsReferences = DwarfSectionsAsReferences == Enable;
361 
362   // Don't generate type units for unsupported object file formats.
363   GenerateTypeUnits =
364       A->TM.getTargetTriple().isOSBinFormatELF() && GenerateDwarfTypeUnits;
365 
366   TheAccelTableKind = computeAccelTableKind(
367       DwarfVersion, GenerateTypeUnits, DebuggerTuning, A->TM.getTargetTriple());
368 
369   // Work around a GDB bug. GDB doesn't support the standard opcode;
370   // SCE doesn't support GNU's; LLDB prefers the standard opcode, which
371   // is defined as of DWARF 3.
372   // See GDB bug 11616 - DW_OP_form_tls_address is unimplemented
373   // https://sourceware.org/bugzilla/show_bug.cgi?id=11616
374   UseGNUTLSOpcode = tuneForGDB() || DwarfVersion < 3;
375 
376   // GDB does not fully support the DWARF 4 representation for bitfields.
377   UseDWARF2Bitfields = (DwarfVersion < 4) || tuneForGDB();
378 
379   // The DWARF v5 string offsets table has - possibly shared - contributions
380   // from each compile and type unit each preceded by a header. The string
381   // offsets table used by the pre-DWARF v5 split-DWARF implementation uses
382   // a monolithic string offsets table without any header.
383   UseSegmentedStringOffsetsTable = DwarfVersion >= 5;
384 
385   Asm->OutStreamer->getContext().setDwarfVersion(DwarfVersion);
386 }
387 
388 // Define out of line so we don't have to include DwarfUnit.h in DwarfDebug.h.
389 DwarfDebug::~DwarfDebug() = default;
390 
391 static bool isObjCClass(StringRef Name) {
392   return Name.startswith("+") || Name.startswith("-");
393 }
394 
395 static bool hasObjCCategory(StringRef Name) {
396   if (!isObjCClass(Name))
397     return false;
398 
399   return Name.find(") ") != StringRef::npos;
400 }
401 
402 static void getObjCClassCategory(StringRef In, StringRef &Class,
403                                  StringRef &Category) {
404   if (!hasObjCCategory(In)) {
405     Class = In.slice(In.find('[') + 1, In.find(' '));
406     Category = "";
407     return;
408   }
409 
410   Class = In.slice(In.find('[') + 1, In.find('('));
411   Category = In.slice(In.find('[') + 1, In.find(' '));
412 }
413 
414 static StringRef getObjCMethodName(StringRef In) {
415   return In.slice(In.find(' ') + 1, In.find(']'));
416 }
417 
418 // Add the various names to the Dwarf accelerator table names.
419 void DwarfDebug::addSubprogramNames(const DICompileUnit &CU,
420                                     const DISubprogram *SP, DIE &Die) {
421   if (getAccelTableKind() != AccelTableKind::Apple &&
422       CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
423     return;
424 
425   if (!SP->isDefinition())
426     return;
427 
428   if (SP->getName() != "")
429     addAccelName(CU, SP->getName(), Die);
430 
431   // If the linkage name is different than the name, go ahead and output that as
432   // well into the name table. Only do that if we are going to actually emit
433   // that name.
434   if (SP->getLinkageName() != "" && SP->getName() != SP->getLinkageName() &&
435       (useAllLinkageNames() || InfoHolder.getAbstractSPDies().lookup(SP)))
436     addAccelName(CU, SP->getLinkageName(), Die);
437 
438   // If this is an Objective-C selector name add it to the ObjC accelerator
439   // too.
440   if (isObjCClass(SP->getName())) {
441     StringRef Class, Category;
442     getObjCClassCategory(SP->getName(), Class, Category);
443     addAccelObjC(CU, Class, Die);
444     if (Category != "")
445       addAccelObjC(CU, Category, Die);
446     // Also add the base method name to the name table.
447     addAccelName(CU, getObjCMethodName(SP->getName()), Die);
448   }
449 }
450 
451 /// Check whether we should create a DIE for the given Scope, return true
452 /// if we don't create a DIE (the corresponding DIE is null).
453 bool DwarfDebug::isLexicalScopeDIENull(LexicalScope *Scope) {
454   if (Scope->isAbstractScope())
455     return false;
456 
457   // We don't create a DIE if there is no Range.
458   const SmallVectorImpl<InsnRange> &Ranges = Scope->getRanges();
459   if (Ranges.empty())
460     return true;
461 
462   if (Ranges.size() > 1)
463     return false;
464 
465   // We don't create a DIE if we have a single Range and the end label
466   // is null.
467   return !getLabelAfterInsn(Ranges.front().second);
468 }
469 
470 template <typename Func> static void forBothCUs(DwarfCompileUnit &CU, Func F) {
471   F(CU);
472   if (auto *SkelCU = CU.getSkeleton())
473     if (CU.getCUNode()->getSplitDebugInlining())
474       F(*SkelCU);
475 }
476 
477 bool DwarfDebug::shareAcrossDWOCUs() const {
478   return SplitDwarfCrossCuReferences;
479 }
480 
481 void DwarfDebug::constructAbstractSubprogramScopeDIE(DwarfCompileUnit &SrcCU,
482                                                      LexicalScope *Scope) {
483   assert(Scope && Scope->getScopeNode());
484   assert(Scope->isAbstractScope());
485   assert(!Scope->getInlinedAt());
486 
487   auto *SP = cast<DISubprogram>(Scope->getScopeNode());
488 
489   // Find the subprogram's DwarfCompileUnit in the SPMap in case the subprogram
490   // was inlined from another compile unit.
491   if (useSplitDwarf() && !shareAcrossDWOCUs() && !SP->getUnit()->getSplitDebugInlining())
492     // Avoid building the original CU if it won't be used
493     SrcCU.constructAbstractSubprogramScopeDIE(Scope);
494   else {
495     auto &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
496     if (auto *SkelCU = CU.getSkeleton()) {
497       (shareAcrossDWOCUs() ? CU : SrcCU)
498           .constructAbstractSubprogramScopeDIE(Scope);
499       if (CU.getCUNode()->getSplitDebugInlining())
500         SkelCU->constructAbstractSubprogramScopeDIE(Scope);
501     } else
502       CU.constructAbstractSubprogramScopeDIE(Scope);
503   }
504 }
505 
506 void DwarfDebug::constructCallSiteEntryDIEs(const DISubprogram &SP,
507                                             DwarfCompileUnit &CU, DIE &ScopeDIE,
508                                             const MachineFunction &MF) {
509   // Add a call site-related attribute (DWARF5, Sec. 3.3.1.3). Do this only if
510   // the subprogram is required to have one.
511   if (!SP.areAllCallsDescribed() || !SP.isDefinition())
512     return;
513 
514   // Use DW_AT_call_all_calls to express that call site entries are present
515   // for both tail and non-tail calls. Don't use DW_AT_call_all_source_calls
516   // because one of its requirements is not met: call site entries for
517   // optimized-out calls are elided.
518   CU.addFlag(ScopeDIE, dwarf::DW_AT_call_all_calls);
519 
520   const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
521   assert(TII && "TargetInstrInfo not found: cannot label tail calls");
522 
523   // Emit call site entries for each call or tail call in the function.
524   for (const MachineBasicBlock &MBB : MF) {
525     for (const MachineInstr &MI : MBB.instrs()) {
526       // Skip instructions which aren't calls. Both calls and tail-calling jump
527       // instructions (e.g TAILJMPd64) are classified correctly here.
528       if (!MI.isCall())
529         continue;
530 
531       // TODO: Add support for targets with delay slots (see: beginInstruction).
532       if (MI.hasDelaySlot())
533         return;
534 
535       // If this is a direct call, find the callee's subprogram.
536       const MachineOperand &CalleeOp = MI.getOperand(0);
537       if (!CalleeOp.isGlobal())
538         continue;
539       const Function *CalleeDecl = dyn_cast<Function>(CalleeOp.getGlobal());
540       if (!CalleeDecl || !CalleeDecl->getSubprogram())
541         continue;
542 
543       // TODO: Omit call site entries for runtime calls (objc_msgSend, etc).
544       // TODO: Add support for indirect calls.
545 
546       bool IsTail = TII->isTailCall(MI);
547 
548       // For tail calls, no return PC information is needed. For regular calls,
549       // the return PC is needed to disambiguate paths in the call graph which
550       // could lead to some target function.
551       const MCExpr *PCOffset =
552           IsTail ? nullptr : getFunctionLocalOffsetAfterInsn(&MI);
553 
554       assert((IsTail || PCOffset) && "Call without return PC information");
555       LLVM_DEBUG(dbgs() << "CallSiteEntry: " << MF.getName() << " -> "
556                         << CalleeDecl->getName() << (IsTail ? " [tail]" : "")
557                         << "\n");
558       CU.constructCallSiteEntryDIE(ScopeDIE, *CalleeDecl->getSubprogram(),
559                                    IsTail, PCOffset);
560     }
561   }
562 }
563 
564 void DwarfDebug::addGnuPubAttributes(DwarfCompileUnit &U, DIE &D) const {
565   if (!U.hasDwarfPubSections())
566     return;
567 
568   U.addFlag(D, dwarf::DW_AT_GNU_pubnames);
569 }
570 
571 void DwarfDebug::finishUnitAttributes(const DICompileUnit *DIUnit,
572                                       DwarfCompileUnit &NewCU) {
573   DIE &Die = NewCU.getUnitDie();
574   StringRef FN = DIUnit->getFilename();
575 
576   StringRef Producer = DIUnit->getProducer();
577   StringRef Flags = DIUnit->getFlags();
578   if (!Flags.empty() && !useAppleExtensionAttributes()) {
579     std::string ProducerWithFlags = Producer.str() + " " + Flags.str();
580     NewCU.addString(Die, dwarf::DW_AT_producer, ProducerWithFlags);
581   } else
582     NewCU.addString(Die, dwarf::DW_AT_producer, Producer);
583 
584   NewCU.addUInt(Die, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
585                 DIUnit->getSourceLanguage());
586   NewCU.addString(Die, dwarf::DW_AT_name, FN);
587 
588   // Add DW_str_offsets_base to the unit DIE, except for split units.
589   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
590     NewCU.addStringOffsetsStart();
591 
592   if (!useSplitDwarf()) {
593     NewCU.initStmtList();
594 
595     // If we're using split dwarf the compilation dir is going to be in the
596     // skeleton CU and so we don't need to duplicate it here.
597     if (!CompilationDir.empty())
598       NewCU.addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
599 
600     addGnuPubAttributes(NewCU, Die);
601   }
602 
603   if (useAppleExtensionAttributes()) {
604     if (DIUnit->isOptimized())
605       NewCU.addFlag(Die, dwarf::DW_AT_APPLE_optimized);
606 
607     StringRef Flags = DIUnit->getFlags();
608     if (!Flags.empty())
609       NewCU.addString(Die, dwarf::DW_AT_APPLE_flags, Flags);
610 
611     if (unsigned RVer = DIUnit->getRuntimeVersion())
612       NewCU.addUInt(Die, dwarf::DW_AT_APPLE_major_runtime_vers,
613                     dwarf::DW_FORM_data1, RVer);
614   }
615 
616   if (DIUnit->getDWOId()) {
617     // This CU is either a clang module DWO or a skeleton CU.
618     NewCU.addUInt(Die, dwarf::DW_AT_GNU_dwo_id, dwarf::DW_FORM_data8,
619                   DIUnit->getDWOId());
620     if (!DIUnit->getSplitDebugFilename().empty())
621       // This is a prefabricated skeleton CU.
622       NewCU.addString(Die, dwarf::DW_AT_GNU_dwo_name,
623                       DIUnit->getSplitDebugFilename());
624   }
625 }
626 // Create new DwarfCompileUnit for the given metadata node with tag
627 // DW_TAG_compile_unit.
628 DwarfCompileUnit &
629 DwarfDebug::getOrCreateDwarfCompileUnit(const DICompileUnit *DIUnit) {
630   if (auto *CU = CUMap.lookup(DIUnit))
631     return *CU;
632 
633   CompilationDir = DIUnit->getDirectory();
634 
635   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
636       InfoHolder.getUnits().size(), DIUnit, Asm, this, &InfoHolder);
637   DwarfCompileUnit &NewCU = *OwnedUnit;
638   InfoHolder.addUnit(std::move(OwnedUnit));
639 
640   for (auto *IE : DIUnit->getImportedEntities())
641     NewCU.addImportedEntity(IE);
642 
643   // LTO with assembly output shares a single line table amongst multiple CUs.
644   // To avoid the compilation directory being ambiguous, let the line table
645   // explicitly describe the directory of all files, never relying on the
646   // compilation directory.
647   if (!Asm->OutStreamer->hasRawTextSupport() || SingleCU)
648     Asm->OutStreamer->emitDwarfFile0Directive(
649         CompilationDir, DIUnit->getFilename(),
650         NewCU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource(),
651         NewCU.getUniqueID());
652 
653   if (useSplitDwarf()) {
654     NewCU.setSkeleton(constructSkeletonCU(NewCU));
655     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoDWOSection());
656   } else {
657     finishUnitAttributes(DIUnit, NewCU);
658     NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
659   }
660 
661   CUMap.insert({DIUnit, &NewCU});
662   CUDieMap.insert({&NewCU.getUnitDie(), &NewCU});
663   return NewCU;
664 }
665 
666 void DwarfDebug::constructAndAddImportedEntityDIE(DwarfCompileUnit &TheCU,
667                                                   const DIImportedEntity *N) {
668   if (isa<DILocalScope>(N->getScope()))
669     return;
670   if (DIE *D = TheCU.getOrCreateContextDIE(N->getScope()))
671     D->addChild(TheCU.constructImportedEntityDIE(N));
672 }
673 
674 /// Sort and unique GVEs by comparing their fragment offset.
675 static SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &
676 sortGlobalExprs(SmallVectorImpl<DwarfCompileUnit::GlobalExpr> &GVEs) {
677   llvm::sort(
678       GVEs, [](DwarfCompileUnit::GlobalExpr A, DwarfCompileUnit::GlobalExpr B) {
679         // Sort order: first null exprs, then exprs without fragment
680         // info, then sort by fragment offset in bits.
681         // FIXME: Come up with a more comprehensive comparator so
682         // the sorting isn't non-deterministic, and so the following
683         // std::unique call works correctly.
684         if (!A.Expr || !B.Expr)
685           return !!B.Expr;
686         auto FragmentA = A.Expr->getFragmentInfo();
687         auto FragmentB = B.Expr->getFragmentInfo();
688         if (!FragmentA || !FragmentB)
689           return !!FragmentB;
690         return FragmentA->OffsetInBits < FragmentB->OffsetInBits;
691       });
692   GVEs.erase(std::unique(GVEs.begin(), GVEs.end(),
693                          [](DwarfCompileUnit::GlobalExpr A,
694                             DwarfCompileUnit::GlobalExpr B) {
695                            return A.Expr == B.Expr;
696                          }),
697              GVEs.end());
698   return GVEs;
699 }
700 
701 // Emit all Dwarf sections that should come prior to the content. Create
702 // global DIEs and emit initial debug info sections. This is invoked by
703 // the target AsmPrinter.
704 void DwarfDebug::beginModule() {
705   NamedRegionTimer T(DbgTimerName, DbgTimerDescription, DWARFGroupName,
706                      DWARFGroupDescription, TimePassesIsEnabled);
707   if (DisableDebugInfoPrinting) {
708     MMI->setDebugInfoAvailability(false);
709     return;
710   }
711 
712   const Module *M = MMI->getModule();
713 
714   unsigned NumDebugCUs = std::distance(M->debug_compile_units_begin(),
715                                        M->debug_compile_units_end());
716   // Tell MMI whether we have debug info.
717   assert(MMI->hasDebugInfo() == (NumDebugCUs > 0) &&
718          "DebugInfoAvailabilty initialized unexpectedly");
719   SingleCU = NumDebugCUs == 1;
720   DenseMap<DIGlobalVariable *, SmallVector<DwarfCompileUnit::GlobalExpr, 1>>
721       GVMap;
722   for (const GlobalVariable &Global : M->globals()) {
723     SmallVector<DIGlobalVariableExpression *, 1> GVs;
724     Global.getDebugInfo(GVs);
725     for (auto *GVE : GVs)
726       GVMap[GVE->getVariable()].push_back({&Global, GVE->getExpression()});
727   }
728 
729   // Create the symbol that designates the start of the unit's contribution
730   // to the string offsets table. In a split DWARF scenario, only the skeleton
731   // unit has the DW_AT_str_offsets_base attribute (and hence needs the symbol).
732   if (useSegmentedStringOffsetsTable())
733     (useSplitDwarf() ? SkeletonHolder : InfoHolder)
734         .setStringOffsetsStartSym(Asm->createTempSymbol("str_offsets_base"));
735 
736 
737   // Create the symbols that designates the start of the DWARF v5 range list
738   // and locations list tables. They are located past the table headers.
739   if (getDwarfVersion() >= 5) {
740     DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
741     Holder.setRnglistsTableBaseSym(
742         Asm->createTempSymbol("rnglists_table_base"));
743     Holder.setLoclistsTableBaseSym(
744         Asm->createTempSymbol("loclists_table_base"));
745 
746     if (useSplitDwarf())
747       InfoHolder.setRnglistsTableBaseSym(
748           Asm->createTempSymbol("rnglists_dwo_table_base"));
749   }
750 
751   // Create the symbol that points to the first entry following the debug
752   // address table (.debug_addr) header.
753   AddrPool.setLabel(Asm->createTempSymbol("addr_table_base"));
754 
755   for (DICompileUnit *CUNode : M->debug_compile_units()) {
756     // FIXME: Move local imported entities into a list attached to the
757     // subprogram, then this search won't be needed and a
758     // getImportedEntities().empty() test should go below with the rest.
759     bool HasNonLocalImportedEntities = llvm::any_of(
760         CUNode->getImportedEntities(), [](const DIImportedEntity *IE) {
761           return !isa<DILocalScope>(IE->getScope());
762         });
763 
764     if (!HasNonLocalImportedEntities && CUNode->getEnumTypes().empty() &&
765         CUNode->getRetainedTypes().empty() &&
766         CUNode->getGlobalVariables().empty() && CUNode->getMacros().empty())
767       continue;
768 
769     DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(CUNode);
770 
771     // Global Variables.
772     for (auto *GVE : CUNode->getGlobalVariables()) {
773       // Don't bother adding DIGlobalVariableExpressions listed in the CU if we
774       // already know about the variable and it isn't adding a constant
775       // expression.
776       auto &GVMapEntry = GVMap[GVE->getVariable()];
777       auto *Expr = GVE->getExpression();
778       if (!GVMapEntry.size() || (Expr && Expr->isConstant()))
779         GVMapEntry.push_back({nullptr, Expr});
780     }
781     DenseSet<DIGlobalVariable *> Processed;
782     for (auto *GVE : CUNode->getGlobalVariables()) {
783       DIGlobalVariable *GV = GVE->getVariable();
784       if (Processed.insert(GV).second)
785         CU.getOrCreateGlobalVariableDIE(GV, sortGlobalExprs(GVMap[GV]));
786     }
787 
788     for (auto *Ty : CUNode->getEnumTypes()) {
789       // The enum types array by design contains pointers to
790       // MDNodes rather than DIRefs. Unique them here.
791       CU.getOrCreateTypeDIE(cast<DIType>(Ty));
792     }
793     for (auto *Ty : CUNode->getRetainedTypes()) {
794       // The retained types array by design contains pointers to
795       // MDNodes rather than DIRefs. Unique them here.
796       if (DIType *RT = dyn_cast<DIType>(Ty))
797           // There is no point in force-emitting a forward declaration.
798           CU.getOrCreateTypeDIE(RT);
799     }
800     // Emit imported_modules last so that the relevant context is already
801     // available.
802     for (auto *IE : CUNode->getImportedEntities())
803       constructAndAddImportedEntityDIE(CU, IE);
804   }
805 }
806 
807 void DwarfDebug::finishEntityDefinitions() {
808   for (const auto &Entity : ConcreteEntities) {
809     DIE *Die = Entity->getDIE();
810     assert(Die);
811     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
812     // in the ConcreteEntities list, rather than looking it up again here.
813     // DIE::getUnit isn't simple - it walks parent pointers, etc.
814     DwarfCompileUnit *Unit = CUDieMap.lookup(Die->getUnitDie());
815     assert(Unit);
816     Unit->finishEntityDefinition(Entity.get());
817   }
818 }
819 
820 void DwarfDebug::finishSubprogramDefinitions() {
821   for (const DISubprogram *SP : ProcessedSPNodes) {
822     assert(SP->getUnit()->getEmissionKind() != DICompileUnit::NoDebug);
823     forBothCUs(
824         getOrCreateDwarfCompileUnit(SP->getUnit()),
825         [&](DwarfCompileUnit &CU) { CU.finishSubprogramDefinition(SP); });
826   }
827 }
828 
829 void DwarfDebug::finalizeModuleInfo() {
830   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
831 
832   finishSubprogramDefinitions();
833 
834   finishEntityDefinitions();
835 
836   // Include the DWO file name in the hash if there's more than one CU.
837   // This handles ThinLTO's situation where imported CUs may very easily be
838   // duplicate with the same CU partially imported into another ThinLTO unit.
839   StringRef DWOName;
840   if (CUMap.size() > 1)
841     DWOName = Asm->TM.Options.MCOptions.SplitDwarfFile;
842 
843   // Handle anything that needs to be done on a per-unit basis after
844   // all other generation.
845   for (const auto &P : CUMap) {
846     auto &TheCU = *P.second;
847     if (TheCU.getCUNode()->isDebugDirectivesOnly())
848       continue;
849     // Emit DW_AT_containing_type attribute to connect types with their
850     // vtable holding type.
851     TheCU.constructContainingTypeDIEs();
852 
853     // Add CU specific attributes if we need to add any.
854     // If we're splitting the dwarf out now that we've got the entire
855     // CU then add the dwo id to it.
856     auto *SkCU = TheCU.getSkeleton();
857     if (useSplitDwarf() && !empty(TheCU.getUnitDie().children())) {
858       finishUnitAttributes(TheCU.getCUNode(), TheCU);
859       TheCU.addString(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
860                       Asm->TM.Options.MCOptions.SplitDwarfFile);
861       SkCU->addString(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_name,
862                       Asm->TM.Options.MCOptions.SplitDwarfFile);
863       // Emit a unique identifier for this CU.
864       uint64_t ID =
865           DIEHash(Asm).computeCUSignature(DWOName, TheCU.getUnitDie());
866       if (getDwarfVersion() >= 5) {
867         TheCU.setDWOId(ID);
868         SkCU->setDWOId(ID);
869       } else {
870         TheCU.addUInt(TheCU.getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
871                       dwarf::DW_FORM_data8, ID);
872         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
873                       dwarf::DW_FORM_data8, ID);
874       }
875 
876       if (getDwarfVersion() < 5 && !SkeletonHolder.getRangeLists().empty()) {
877         const MCSymbol *Sym = TLOF.getDwarfRangesSection()->getBeginSymbol();
878         SkCU->addSectionLabel(SkCU->getUnitDie(), dwarf::DW_AT_GNU_ranges_base,
879                               Sym, Sym);
880       }
881     } else if (SkCU) {
882       finishUnitAttributes(SkCU->getCUNode(), *SkCU);
883     }
884 
885     // If we have code split among multiple sections or non-contiguous
886     // ranges of code then emit a DW_AT_ranges attribute on the unit that will
887     // remain in the .o file, otherwise add a DW_AT_low_pc.
888     // FIXME: We should use ranges allow reordering of code ala
889     // .subsections_via_symbols in mach-o. This would mean turning on
890     // ranges for all subprogram DIEs for mach-o.
891     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
892 
893     // We don't keep track of which addresses are used in which CU so this
894     // is a bit pessimistic under LTO.
895     if (!AddrPool.isEmpty() &&
896         (getDwarfVersion() >= 5 ||
897          (SkCU && !empty(TheCU.getUnitDie().children()))))
898       U.addAddrTableBase();
899 
900     if (unsigned NumRanges = TheCU.getRanges().size()) {
901       if (NumRanges > 1 && useRangesSection())
902         // A DW_AT_low_pc attribute may also be specified in combination with
903         // DW_AT_ranges to specify the default base address for use in
904         // location lists (see Section 2.6.2) and range lists (see Section
905         // 2.17.3).
906         U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr, 0);
907       else
908         U.setBaseAddress(TheCU.getRanges().front().getStart());
909       U.attachRangesOrLowHighPC(U.getUnitDie(), TheCU.takeRanges());
910     }
911 
912     if (getDwarfVersion() >= 5) {
913       if (U.hasRangeLists())
914         U.addRnglistsBase();
915 
916       if (!DebugLocs.getLists().empty() && !useSplitDwarf())
917         U.addLoclistsBase();
918     }
919 
920     auto *CUNode = cast<DICompileUnit>(P.first);
921     // If compile Unit has macros, emit "DW_AT_macro_info" attribute.
922     if (CUNode->getMacros())
923       U.addSectionLabel(U.getUnitDie(), dwarf::DW_AT_macro_info,
924                         U.getMacroLabelBegin(),
925                         TLOF.getDwarfMacinfoSection()->getBeginSymbol());
926   }
927 
928   // Emit all frontend-produced Skeleton CUs, i.e., Clang modules.
929   for (auto *CUNode : MMI->getModule()->debug_compile_units())
930     if (CUNode->getDWOId())
931       getOrCreateDwarfCompileUnit(CUNode);
932 
933   // Compute DIE offsets and sizes.
934   InfoHolder.computeSizeAndOffsets();
935   if (useSplitDwarf())
936     SkeletonHolder.computeSizeAndOffsets();
937 }
938 
939 // Emit all Dwarf sections that should come after the content.
940 void DwarfDebug::endModule() {
941   assert(CurFn == nullptr);
942   assert(CurMI == nullptr);
943 
944   // If we aren't actually generating debug info (check beginModule -
945   // conditionalized on !DisableDebugInfoPrinting and the presence of the
946   // llvm.dbg.cu metadata node)
947   if (!MMI->hasDebugInfo())
948     return;
949 
950   // Finalize the debug info for the module.
951   finalizeModuleInfo();
952 
953   emitDebugStr();
954 
955   if (useSplitDwarf())
956     emitDebugLocDWO();
957   else
958     // Emit info into a debug loc section.
959     emitDebugLoc();
960 
961   // Corresponding abbreviations into a abbrev section.
962   emitAbbreviations();
963 
964   // Emit all the DIEs into a debug info section.
965   emitDebugInfo();
966 
967   // Emit info into a debug aranges section.
968   if (GenerateARangeSection)
969     emitDebugARanges();
970 
971   // Emit info into a debug ranges section.
972   emitDebugRanges();
973 
974   // Emit info into a debug macinfo section.
975   emitDebugMacinfo();
976 
977   if (useSplitDwarf()) {
978     emitDebugStrDWO();
979     emitDebugInfoDWO();
980     emitDebugAbbrevDWO();
981     emitDebugLineDWO();
982     emitDebugRangesDWO();
983   }
984 
985   emitDebugAddr();
986 
987   // Emit info into the dwarf accelerator table sections.
988   switch (getAccelTableKind()) {
989   case AccelTableKind::Apple:
990     emitAccelNames();
991     emitAccelObjC();
992     emitAccelNamespaces();
993     emitAccelTypes();
994     break;
995   case AccelTableKind::Dwarf:
996     emitAccelDebugNames();
997     break;
998   case AccelTableKind::None:
999     break;
1000   case AccelTableKind::Default:
1001     llvm_unreachable("Default should have already been resolved.");
1002   }
1003 
1004   // Emit the pubnames and pubtypes sections if requested.
1005   emitDebugPubSections();
1006 
1007   // clean up.
1008   // FIXME: AbstractVariables.clear();
1009 }
1010 
1011 void DwarfDebug::ensureAbstractEntityIsCreated(DwarfCompileUnit &CU,
1012                                                const DINode *Node,
1013                                                const MDNode *ScopeNode) {
1014   if (CU.getExistingAbstractEntity(Node))
1015     return;
1016 
1017   CU.createAbstractEntity(Node, LScopes.getOrCreateAbstractScope(
1018                                        cast<DILocalScope>(ScopeNode)));
1019 }
1020 
1021 void DwarfDebug::ensureAbstractEntityIsCreatedIfScoped(DwarfCompileUnit &CU,
1022     const DINode *Node, const MDNode *ScopeNode) {
1023   if (CU.getExistingAbstractEntity(Node))
1024     return;
1025 
1026   if (LexicalScope *Scope =
1027           LScopes.findAbstractScope(cast_or_null<DILocalScope>(ScopeNode)))
1028     CU.createAbstractEntity(Node, Scope);
1029 }
1030 
1031 // Collect variable information from side table maintained by MF.
1032 void DwarfDebug::collectVariableInfoFromMFTable(
1033     DwarfCompileUnit &TheCU, DenseSet<InlinedEntity> &Processed) {
1034   SmallDenseMap<InlinedEntity, DbgVariable *> MFVars;
1035   for (const auto &VI : Asm->MF->getVariableDbgInfo()) {
1036     if (!VI.Var)
1037       continue;
1038     assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) &&
1039            "Expected inlined-at fields to agree");
1040 
1041     InlinedEntity Var(VI.Var, VI.Loc->getInlinedAt());
1042     Processed.insert(Var);
1043     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1044 
1045     // If variable scope is not found then skip this variable.
1046     if (!Scope)
1047       continue;
1048 
1049     ensureAbstractEntityIsCreatedIfScoped(TheCU, Var.first, Scope->getScopeNode());
1050     auto RegVar = llvm::make_unique<DbgVariable>(
1051                     cast<DILocalVariable>(Var.first), Var.second);
1052     RegVar->initializeMMI(VI.Expr, VI.Slot);
1053     if (DbgVariable *DbgVar = MFVars.lookup(Var))
1054       DbgVar->addMMIEntry(*RegVar);
1055     else if (InfoHolder.addScopeVariable(Scope, RegVar.get())) {
1056       MFVars.insert({Var, RegVar.get()});
1057       ConcreteEntities.push_back(std::move(RegVar));
1058     }
1059   }
1060 }
1061 
1062 // Get .debug_loc entry for the instruction range starting at MI.
1063 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1064   const DIExpression *Expr = MI->getDebugExpression();
1065   assert(MI->getNumOperands() == 4);
1066   if (MI->getOperand(0).isReg()) {
1067     auto RegOp = MI->getOperand(0);
1068     auto Op1 = MI->getOperand(1);
1069     // If the second operand is an immediate, this is a
1070     // register-indirect address.
1071     assert((!Op1.isImm() || (Op1.getImm() == 0)) && "unexpected offset");
1072     MachineLocation MLoc(RegOp.getReg(), Op1.isImm());
1073     return DebugLocEntry::Value(Expr, MLoc);
1074   }
1075   if (MI->getOperand(0).isImm())
1076     return DebugLocEntry::Value(Expr, MI->getOperand(0).getImm());
1077   if (MI->getOperand(0).isFPImm())
1078     return DebugLocEntry::Value(Expr, MI->getOperand(0).getFPImm());
1079   if (MI->getOperand(0).isCImm())
1080     return DebugLocEntry::Value(Expr, MI->getOperand(0).getCImm());
1081 
1082   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1083 }
1084 
1085 /// If this and Next are describing different fragments of the same
1086 /// variable, merge them by appending Next's values to the current
1087 /// list of values.
1088 /// Return true if the merge was successful.
1089 bool DebugLocEntry::MergeValues(const DebugLocEntry &Next) {
1090   if (Begin == Next.Begin) {
1091     auto *FirstExpr = cast<DIExpression>(Values[0].Expression);
1092     auto *FirstNextExpr = cast<DIExpression>(Next.Values[0].Expression);
1093     if (!FirstExpr->isFragment() || !FirstNextExpr->isFragment())
1094       return false;
1095 
1096     // We can only merge entries if none of the fragments overlap any others.
1097     // In doing so, we can take advantage of the fact that both lists are
1098     // sorted.
1099     for (unsigned i = 0, j = 0; i < Values.size(); ++i) {
1100       for (; j < Next.Values.size(); ++j) {
1101         int res = cast<DIExpression>(Values[i].Expression)->fragmentCmp(
1102             cast<DIExpression>(Next.Values[j].Expression));
1103         if (res == 0) // The two expressions overlap, we can't merge.
1104           return false;
1105         // Values[i] is entirely before Next.Values[j],
1106         // so go back to the next entry of Values.
1107         else if (res == -1)
1108           break;
1109         // Next.Values[j] is entirely before Values[i], so go on to the
1110         // next entry of Next.Values.
1111       }
1112     }
1113 
1114     addValues(Next.Values);
1115     End = Next.End;
1116     return true;
1117   }
1118   return false;
1119 }
1120 
1121 /// Build the location list for all DBG_VALUEs in the function that
1122 /// describe the same variable.  If the ranges of several independent
1123 /// fragments of the same variable overlap partially, split them up and
1124 /// combine the ranges. The resulting DebugLocEntries are will have
1125 /// strict monotonically increasing begin addresses and will never
1126 /// overlap.
1127 //
1128 // Input:
1129 //
1130 //   Ranges History [var, loc, fragment ofs size]
1131 // 0 |      [x, (reg0, fragment 0, 32)]
1132 // 1 | |    [x, (reg1, fragment 32, 32)] <- IsFragmentOfPrevEntry
1133 // 2 | |    ...
1134 // 3   |    [clobber reg0]
1135 // 4        [x, (mem, fragment 0, 64)] <- overlapping with both previous fragments of
1136 //                                     x.
1137 //
1138 // Output:
1139 //
1140 // [0-1]    [x, (reg0, fragment  0, 32)]
1141 // [1-3]    [x, (reg0, fragment  0, 32), (reg1, fragment 32, 32)]
1142 // [3-4]    [x, (reg1, fragment 32, 32)]
1143 // [4- ]    [x, (mem,  fragment  0, 64)]
1144 void
1145 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1146                               const DbgValueHistoryMap::InstrRanges &Ranges) {
1147   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1148 
1149   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1150     const MachineInstr *Begin = I->first;
1151     const MachineInstr *End = I->second;
1152     assert(Begin->isDebugValue() && "Invalid History entry");
1153 
1154     // Check if a variable is inaccessible in this range.
1155     if (Begin->getNumOperands() > 1 &&
1156         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1157       OpenRanges.clear();
1158       continue;
1159     }
1160 
1161     // If this fragment overlaps with any open ranges, truncate them.
1162     const DIExpression *DIExpr = Begin->getDebugExpression();
1163     auto Last = remove_if(OpenRanges, [&](DebugLocEntry::Value R) {
1164       return DIExpr->fragmentsOverlap(R.getExpression());
1165     });
1166     OpenRanges.erase(Last, OpenRanges.end());
1167 
1168     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1169     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1170 
1171     const MCSymbol *EndLabel;
1172     if (End != nullptr)
1173       EndLabel = getLabelAfterInsn(End);
1174     else if (std::next(I) == Ranges.end())
1175       EndLabel = Asm->getFunctionEnd();
1176     else
1177       EndLabel = getLabelBeforeInsn(std::next(I)->first);
1178     assert(EndLabel && "Forgot label after instruction ending a range!");
1179 
1180     LLVM_DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1181 
1182     auto Value = getDebugLocValue(Begin);
1183 
1184     // Omit entries with empty ranges as they do not have any effect in DWARF.
1185     if (StartLabel == EndLabel) {
1186       // If this is a fragment, we must still add the value to the list of
1187       // open ranges, since it may describe non-overlapping parts of the
1188       // variable.
1189       if (DIExpr->isFragment())
1190         OpenRanges.push_back(Value);
1191       LLVM_DEBUG(dbgs() << "Omitting location list entry with empty range.\n");
1192       continue;
1193     }
1194 
1195     DebugLocEntry Loc(StartLabel, EndLabel, Value);
1196     bool couldMerge = false;
1197 
1198     // If this is a fragment, it may belong to the current DebugLocEntry.
1199     if (DIExpr->isFragment()) {
1200       // Add this value to the list of open ranges.
1201       OpenRanges.push_back(Value);
1202 
1203       // Attempt to add the fragment to the last entry.
1204       if (!DebugLoc.empty())
1205         if (DebugLoc.back().MergeValues(Loc))
1206           couldMerge = true;
1207     }
1208 
1209     if (!couldMerge) {
1210       // Need to add a new DebugLocEntry. Add all values from still
1211       // valid non-overlapping fragments.
1212       if (OpenRanges.size())
1213         Loc.addValues(OpenRanges);
1214 
1215       DebugLoc.push_back(std::move(Loc));
1216     }
1217 
1218     // Attempt to coalesce the ranges of two otherwise identical
1219     // DebugLocEntries.
1220     auto CurEntry = DebugLoc.rbegin();
1221     LLVM_DEBUG({
1222       dbgs() << CurEntry->getValues().size() << " Values:\n";
1223       for (auto &Value : CurEntry->getValues())
1224         Value.dump();
1225       dbgs() << "-----\n";
1226     });
1227 
1228     auto PrevEntry = std::next(CurEntry);
1229     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1230       DebugLoc.pop_back();
1231   }
1232 }
1233 
1234 DbgEntity *DwarfDebug::createConcreteEntity(DwarfCompileUnit &TheCU,
1235                                             LexicalScope &Scope,
1236                                             const DINode *Node,
1237                                             const DILocation *Location,
1238                                             const MCSymbol *Sym) {
1239   ensureAbstractEntityIsCreatedIfScoped(TheCU, Node, Scope.getScopeNode());
1240   if (isa<const DILocalVariable>(Node)) {
1241     ConcreteEntities.push_back(
1242         llvm::make_unique<DbgVariable>(cast<const DILocalVariable>(Node),
1243                                        Location));
1244     InfoHolder.addScopeVariable(&Scope,
1245         cast<DbgVariable>(ConcreteEntities.back().get()));
1246   } else if (isa<const DILabel>(Node)) {
1247     ConcreteEntities.push_back(
1248         llvm::make_unique<DbgLabel>(cast<const DILabel>(Node),
1249                                     Location, Sym));
1250     InfoHolder.addScopeLabel(&Scope,
1251         cast<DbgLabel>(ConcreteEntities.back().get()));
1252   }
1253   return ConcreteEntities.back().get();
1254 }
1255 
1256 /// Determine whether a *singular* DBG_VALUE is valid for the entirety of its
1257 /// enclosing lexical scope. The check ensures there are no other instructions
1258 /// in the same lexical scope preceding the DBG_VALUE and that its range is
1259 /// either open or otherwise rolls off the end of the scope.
1260 static bool validThroughout(LexicalScopes &LScopes,
1261                             const MachineInstr *DbgValue,
1262                             const MachineInstr *RangeEnd) {
1263   assert(DbgValue->getDebugLoc() && "DBG_VALUE without a debug location");
1264   auto MBB = DbgValue->getParent();
1265   auto DL = DbgValue->getDebugLoc();
1266   auto *LScope = LScopes.findLexicalScope(DL);
1267   // Scope doesn't exist; this is a dead DBG_VALUE.
1268   if (!LScope)
1269     return false;
1270   auto &LSRange = LScope->getRanges();
1271   if (LSRange.size() == 0)
1272     return false;
1273 
1274   // Determine if the DBG_VALUE is valid at the beginning of its lexical block.
1275   const MachineInstr *LScopeBegin = LSRange.front().first;
1276   // Early exit if the lexical scope begins outside of the current block.
1277   if (LScopeBegin->getParent() != MBB)
1278     return false;
1279   MachineBasicBlock::const_reverse_iterator Pred(DbgValue);
1280   for (++Pred; Pred != MBB->rend(); ++Pred) {
1281     if (Pred->getFlag(MachineInstr::FrameSetup))
1282       break;
1283     auto PredDL = Pred->getDebugLoc();
1284     if (!PredDL || Pred->isMetaInstruction())
1285       continue;
1286     // Check whether the instruction preceding the DBG_VALUE is in the same
1287     // (sub)scope as the DBG_VALUE.
1288     if (DL->getScope() == PredDL->getScope())
1289       return false;
1290     auto *PredScope = LScopes.findLexicalScope(PredDL);
1291     if (!PredScope || LScope->dominates(PredScope))
1292       return false;
1293   }
1294 
1295   // If the range of the DBG_VALUE is open-ended, report success.
1296   if (!RangeEnd)
1297     return true;
1298 
1299   // Fail if there are instructions belonging to our scope in another block.
1300   const MachineInstr *LScopeEnd = LSRange.back().second;
1301   if (LScopeEnd->getParent() != MBB)
1302     return false;
1303 
1304   // Single, constant DBG_VALUEs in the prologue are promoted to be live
1305   // throughout the function. This is a hack, presumably for DWARF v2 and not
1306   // necessarily correct. It would be much better to use a dbg.declare instead
1307   // if we know the constant is live throughout the scope.
1308   if (DbgValue->getOperand(0).isImm() && MBB->pred_empty())
1309     return true;
1310 
1311   return false;
1312 }
1313 
1314 // Find variables for each lexical scope.
1315 void DwarfDebug::collectEntityInfo(DwarfCompileUnit &TheCU,
1316                                    const DISubprogram *SP,
1317                                    DenseSet<InlinedEntity> &Processed) {
1318   // Grab the variable info that was squirreled away in the MMI side-table.
1319   collectVariableInfoFromMFTable(TheCU, Processed);
1320 
1321   for (const auto &I : DbgValues) {
1322     InlinedEntity IV = I.first;
1323     if (Processed.count(IV))
1324       continue;
1325 
1326     // Instruction ranges, specifying where IV is accessible.
1327     const auto &Ranges = I.second;
1328     if (Ranges.empty())
1329       continue;
1330 
1331     LexicalScope *Scope = nullptr;
1332     const DILocalVariable *LocalVar = cast<DILocalVariable>(IV.first);
1333     if (const DILocation *IA = IV.second)
1334       Scope = LScopes.findInlinedScope(LocalVar->getScope(), IA);
1335     else
1336       Scope = LScopes.findLexicalScope(LocalVar->getScope());
1337     // If variable scope is not found then skip this variable.
1338     if (!Scope)
1339       continue;
1340 
1341     Processed.insert(IV);
1342     DbgVariable *RegVar = cast<DbgVariable>(createConcreteEntity(TheCU,
1343                                             *Scope, LocalVar, IV.second));
1344 
1345     const MachineInstr *MInsn = Ranges.front().first;
1346     assert(MInsn->isDebugValue() && "History must begin with debug value");
1347 
1348     // Check if there is a single DBG_VALUE, valid throughout the var's scope.
1349     if (Ranges.size() == 1 &&
1350         validThroughout(LScopes, MInsn, Ranges.front().second)) {
1351       RegVar->initializeDbgValue(MInsn);
1352       continue;
1353     }
1354     // Do not emit location lists if .debug_loc secton is disabled.
1355     if (!useLocSection())
1356       continue;
1357 
1358     // Handle multiple DBG_VALUE instructions describing one variable.
1359     DebugLocStream::ListBuilder List(DebugLocs, TheCU, *Asm, *RegVar, *MInsn);
1360 
1361     // Build the location list for this variable.
1362     SmallVector<DebugLocEntry, 8> Entries;
1363     buildLocationList(Entries, Ranges);
1364 
1365     // If the variable has a DIBasicType, extract it.  Basic types cannot have
1366     // unique identifiers, so don't bother resolving the type with the
1367     // identifier map.
1368     const DIBasicType *BT = dyn_cast<DIBasicType>(
1369         static_cast<const Metadata *>(LocalVar->getType()));
1370 
1371     // Finalize the entry by lowering it into a DWARF bytestream.
1372     for (auto &Entry : Entries)
1373       Entry.finalize(*Asm, List, BT);
1374   }
1375 
1376   // For each InlinedEntity collected from DBG_LABEL instructions, convert to
1377   // DWARF-related DbgLabel.
1378   for (const auto &I : DbgLabels) {
1379     InlinedEntity IL = I.first;
1380     const MachineInstr *MI = I.second;
1381     if (MI == nullptr)
1382       continue;
1383 
1384     LexicalScope *Scope = nullptr;
1385     const DILabel *Label = cast<DILabel>(IL.first);
1386     // Get inlined DILocation if it is inlined label.
1387     if (const DILocation *IA = IL.second)
1388       Scope = LScopes.findInlinedScope(Label->getScope(), IA);
1389     else
1390       Scope = LScopes.findLexicalScope(Label->getScope());
1391     // If label scope is not found then skip this label.
1392     if (!Scope)
1393       continue;
1394 
1395     Processed.insert(IL);
1396     /// At this point, the temporary label is created.
1397     /// Save the temporary label to DbgLabel entity to get the
1398     /// actually address when generating Dwarf DIE.
1399     MCSymbol *Sym = getLabelBeforeInsn(MI);
1400     createConcreteEntity(TheCU, *Scope, Label, IL.second, Sym);
1401   }
1402 
1403   // Collect info for variables/labels that were optimized out.
1404   for (const DINode *DN : SP->getRetainedNodes()) {
1405     if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1406       continue;
1407     LexicalScope *Scope = nullptr;
1408     if (auto *DV = dyn_cast<DILocalVariable>(DN)) {
1409       Scope = LScopes.findLexicalScope(DV->getScope());
1410     } else if (auto *DL = dyn_cast<DILabel>(DN)) {
1411       Scope = LScopes.findLexicalScope(DL->getScope());
1412     }
1413 
1414     if (Scope)
1415       createConcreteEntity(TheCU, *Scope, DN, nullptr);
1416   }
1417 }
1418 
1419 // Process beginning of an instruction.
1420 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1421   DebugHandlerBase::beginInstruction(MI);
1422   assert(CurMI);
1423 
1424   const auto *SP = MI->getMF()->getFunction().getSubprogram();
1425   if (!SP || SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1426     return;
1427 
1428   // Check if source location changes, but ignore DBG_VALUE and CFI locations.
1429   // If the instruction is part of the function frame setup code, do not emit
1430   // any line record, as there is no correspondence with any user code.
1431   if (MI->isMetaInstruction() || MI->getFlag(MachineInstr::FrameSetup))
1432     return;
1433   const DebugLoc &DL = MI->getDebugLoc();
1434   // When we emit a line-0 record, we don't update PrevInstLoc; so look at
1435   // the last line number actually emitted, to see if it was line 0.
1436   unsigned LastAsmLine =
1437       Asm->OutStreamer->getContext().getCurrentDwarfLoc().getLine();
1438 
1439   // Request a label after the call in order to emit AT_return_pc information
1440   // in call site entries. TODO: Add support for targets with delay slots.
1441   if (SP->areAllCallsDescribed() && MI->isCall() && !MI->hasDelaySlot())
1442     requestLabelAfterInsn(MI);
1443 
1444   if (DL == PrevInstLoc) {
1445     // If we have an ongoing unspecified location, nothing to do here.
1446     if (!DL)
1447       return;
1448     // We have an explicit location, same as the previous location.
1449     // But we might be coming back to it after a line 0 record.
1450     if (LastAsmLine == 0 && DL.getLine() != 0) {
1451       // Reinstate the source location but not marked as a statement.
1452       const MDNode *Scope = DL.getScope();
1453       recordSourceLine(DL.getLine(), DL.getCol(), Scope, /*Flags=*/0);
1454     }
1455     return;
1456   }
1457 
1458   if (!DL) {
1459     // We have an unspecified location, which might want to be line 0.
1460     // If we have already emitted a line-0 record, don't repeat it.
1461     if (LastAsmLine == 0)
1462       return;
1463     // If user said Don't Do That, don't do that.
1464     if (UnknownLocations == Disable)
1465       return;
1466     // See if we have a reason to emit a line-0 record now.
1467     // Reasons to emit a line-0 record include:
1468     // - User asked for it (UnknownLocations).
1469     // - Instruction has a label, so it's referenced from somewhere else,
1470     //   possibly debug information; we want it to have a source location.
1471     // - Instruction is at the top of a block; we don't want to inherit the
1472     //   location from the physically previous (maybe unrelated) block.
1473     if (UnknownLocations == Enable || PrevLabel ||
1474         (PrevInstBB && PrevInstBB != MI->getParent())) {
1475       // Preserve the file and column numbers, if we can, to save space in
1476       // the encoded line table.
1477       // Do not update PrevInstLoc, it remembers the last non-0 line.
1478       const MDNode *Scope = nullptr;
1479       unsigned Column = 0;
1480       if (PrevInstLoc) {
1481         Scope = PrevInstLoc.getScope();
1482         Column = PrevInstLoc.getCol();
1483       }
1484       recordSourceLine(/*Line=*/0, Column, Scope, /*Flags=*/0);
1485     }
1486     return;
1487   }
1488 
1489   // We have an explicit location, different from the previous location.
1490   // Don't repeat a line-0 record, but otherwise emit the new location.
1491   // (The new location might be an explicit line 0, which we do emit.)
1492   if (PrevInstLoc && DL.getLine() == 0 && LastAsmLine == 0)
1493     return;
1494   unsigned Flags = 0;
1495   if (DL == PrologEndLoc) {
1496     Flags |= DWARF2_FLAG_PROLOGUE_END | DWARF2_FLAG_IS_STMT;
1497     PrologEndLoc = DebugLoc();
1498   }
1499   // If the line changed, we call that a new statement; unless we went to
1500   // line 0 and came back, in which case it is not a new statement.
1501   unsigned OldLine = PrevInstLoc ? PrevInstLoc.getLine() : LastAsmLine;
1502   if (DL.getLine() && DL.getLine() != OldLine)
1503     Flags |= DWARF2_FLAG_IS_STMT;
1504 
1505   const MDNode *Scope = DL.getScope();
1506   recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1507 
1508   // If we're not at line 0, remember this location.
1509   if (DL.getLine())
1510     PrevInstLoc = DL;
1511 }
1512 
1513 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1514   // First known non-DBG_VALUE and non-frame setup location marks
1515   // the beginning of the function body.
1516   for (const auto &MBB : *MF)
1517     for (const auto &MI : MBB)
1518       if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) &&
1519           MI.getDebugLoc())
1520         return MI.getDebugLoc();
1521   return DebugLoc();
1522 }
1523 
1524 // Gather pre-function debug information.  Assumes being called immediately
1525 // after the function entry point has been emitted.
1526 void DwarfDebug::beginFunctionImpl(const MachineFunction *MF) {
1527   CurFn = MF;
1528 
1529   auto *SP = MF->getFunction().getSubprogram();
1530   assert(LScopes.empty() || SP == LScopes.getCurrentFunctionScope()->getScopeNode());
1531   if (SP->getUnit()->getEmissionKind() == DICompileUnit::NoDebug)
1532     return;
1533 
1534   DwarfCompileUnit &CU = getOrCreateDwarfCompileUnit(SP->getUnit());
1535 
1536   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1537   // belongs to so that we add to the correct per-cu line table in the
1538   // non-asm case.
1539   if (Asm->OutStreamer->hasRawTextSupport())
1540     // Use a single line table if we are generating assembly.
1541     Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1542   else
1543     Asm->OutStreamer->getContext().setDwarfCompileUnitID(CU.getUniqueID());
1544 
1545   // Record beginning of function.
1546   PrologEndLoc = findPrologueEndLoc(MF);
1547   if (PrologEndLoc) {
1548     // We'd like to list the prologue as "not statements" but GDB behaves
1549     // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1550     auto *SP = PrologEndLoc->getInlinedAtScope()->getSubprogram();
1551     recordSourceLine(SP->getScopeLine(), 0, SP, DWARF2_FLAG_IS_STMT);
1552   }
1553 }
1554 
1555 void DwarfDebug::skippedNonDebugFunction() {
1556   // If we don't have a subprogram for this function then there will be a hole
1557   // in the range information. Keep note of this by setting the previously used
1558   // section to nullptr.
1559   PrevCU = nullptr;
1560   CurFn = nullptr;
1561 }
1562 
1563 // Gather and emit post-function debug information.
1564 void DwarfDebug::endFunctionImpl(const MachineFunction *MF) {
1565   const DISubprogram *SP = MF->getFunction().getSubprogram();
1566 
1567   assert(CurFn == MF &&
1568       "endFunction should be called with the same function as beginFunction");
1569 
1570   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1571   Asm->OutStreamer->getContext().setDwarfCompileUnitID(0);
1572 
1573   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1574   assert(!FnScope || SP == FnScope->getScopeNode());
1575   DwarfCompileUnit &TheCU = *CUMap.lookup(SP->getUnit());
1576   if (TheCU.getCUNode()->isDebugDirectivesOnly()) {
1577     PrevLabel = nullptr;
1578     CurFn = nullptr;
1579     return;
1580   }
1581 
1582   DenseSet<InlinedEntity> Processed;
1583   collectEntityInfo(TheCU, SP, Processed);
1584 
1585   // Add the range of this function to the list of ranges for the CU.
1586   TheCU.addRange(RangeSpan(Asm->getFunctionBegin(), Asm->getFunctionEnd()));
1587 
1588   // Under -gmlt, skip building the subprogram if there are no inlined
1589   // subroutines inside it. But with -fdebug-info-for-profiling, the subprogram
1590   // is still needed as we need its source location.
1591   if (!TheCU.getCUNode()->getDebugInfoForProfiling() &&
1592       TheCU.getCUNode()->getEmissionKind() == DICompileUnit::LineTablesOnly &&
1593       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1594     assert(InfoHolder.getScopeVariables().empty());
1595     PrevLabel = nullptr;
1596     CurFn = nullptr;
1597     return;
1598   }
1599 
1600 #ifndef NDEBUG
1601   size_t NumAbstractScopes = LScopes.getAbstractScopesList().size();
1602 #endif
1603   // Construct abstract scopes.
1604   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1605     auto *SP = cast<DISubprogram>(AScope->getScopeNode());
1606     for (const DINode *DN : SP->getRetainedNodes()) {
1607       if (!Processed.insert(InlinedEntity(DN, nullptr)).second)
1608         continue;
1609 
1610       const MDNode *Scope = nullptr;
1611       if (auto *DV = dyn_cast<DILocalVariable>(DN))
1612         Scope = DV->getScope();
1613       else if (auto *DL = dyn_cast<DILabel>(DN))
1614         Scope = DL->getScope();
1615       else
1616         llvm_unreachable("Unexpected DI type!");
1617 
1618       // Collect info for variables/labels that were optimized out.
1619       ensureAbstractEntityIsCreated(TheCU, DN, Scope);
1620       assert(LScopes.getAbstractScopesList().size() == NumAbstractScopes
1621              && "ensureAbstractEntityIsCreated inserted abstract scopes");
1622     }
1623     constructAbstractSubprogramScopeDIE(TheCU, AScope);
1624   }
1625 
1626   ProcessedSPNodes.insert(SP);
1627   DIE &ScopeDIE = TheCU.constructSubprogramScopeDIE(SP, FnScope);
1628   if (auto *SkelCU = TheCU.getSkeleton())
1629     if (!LScopes.getAbstractScopesList().empty() &&
1630         TheCU.getCUNode()->getSplitDebugInlining())
1631       SkelCU->constructSubprogramScopeDIE(SP, FnScope);
1632 
1633   // Construct call site entries.
1634   constructCallSiteEntryDIEs(*SP, TheCU, ScopeDIE, *MF);
1635 
1636   // Clear debug info
1637   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1638   // DbgVariables except those that are also in AbstractVariables (since they
1639   // can be used cross-function)
1640   InfoHolder.getScopeVariables().clear();
1641   InfoHolder.getScopeLabels().clear();
1642   PrevLabel = nullptr;
1643   CurFn = nullptr;
1644 }
1645 
1646 // Register a source line with debug info. Returns the  unique label that was
1647 // emitted and which provides correspondence to the source line list.
1648 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1649                                   unsigned Flags) {
1650   StringRef Fn;
1651   unsigned FileNo = 1;
1652   unsigned Discriminator = 0;
1653   if (auto *Scope = cast_or_null<DIScope>(S)) {
1654     Fn = Scope->getFilename();
1655     if (Line != 0 && getDwarfVersion() >= 4)
1656       if (auto *LBF = dyn_cast<DILexicalBlockFile>(Scope))
1657         Discriminator = LBF->getDiscriminator();
1658 
1659     unsigned CUID = Asm->OutStreamer->getContext().getDwarfCompileUnitID();
1660     FileNo = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1661               .getOrCreateSourceID(Scope->getFile());
1662   }
1663   Asm->OutStreamer->EmitDwarfLocDirective(FileNo, Line, Col, Flags, 0,
1664                                           Discriminator, Fn);
1665 }
1666 
1667 //===----------------------------------------------------------------------===//
1668 // Emit Methods
1669 //===----------------------------------------------------------------------===//
1670 
1671 // Emit the debug info section.
1672 void DwarfDebug::emitDebugInfo() {
1673   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1674   Holder.emitUnits(/* UseOffsets */ false);
1675 }
1676 
1677 // Emit the abbreviation section.
1678 void DwarfDebug::emitAbbreviations() {
1679   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1680 
1681   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1682 }
1683 
1684 void DwarfDebug::emitStringOffsetsTableHeader() {
1685   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1686   Holder.getStringPool().emitStringOffsetsTableHeader(
1687       *Asm, Asm->getObjFileLowering().getDwarfStrOffSection(),
1688       Holder.getStringOffsetsStartSym());
1689 }
1690 
1691 template <typename AccelTableT>
1692 void DwarfDebug::emitAccel(AccelTableT &Accel, MCSection *Section,
1693                            StringRef TableName) {
1694   Asm->OutStreamer->SwitchSection(Section);
1695 
1696   // Emit the full data.
1697   emitAppleAccelTable(Asm, Accel, TableName, Section->getBeginSymbol());
1698 }
1699 
1700 void DwarfDebug::emitAccelDebugNames() {
1701   // Don't emit anything if we have no compilation units to index.
1702   if (getUnits().empty())
1703     return;
1704 
1705   emitDWARF5AccelTable(Asm, AccelDebugNames, *this, getUnits());
1706 }
1707 
1708 // Emit visible names into a hashed accelerator table section.
1709 void DwarfDebug::emitAccelNames() {
1710   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1711             "Names");
1712 }
1713 
1714 // Emit objective C classes and categories into a hashed accelerator table
1715 // section.
1716 void DwarfDebug::emitAccelObjC() {
1717   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1718             "ObjC");
1719 }
1720 
1721 // Emit namespace dies into a hashed accelerator table.
1722 void DwarfDebug::emitAccelNamespaces() {
1723   emitAccel(AccelNamespace,
1724             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1725             "namespac");
1726 }
1727 
1728 // Emit type dies into a hashed accelerator table.
1729 void DwarfDebug::emitAccelTypes() {
1730   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1731             "types");
1732 }
1733 
1734 // Public name handling.
1735 // The format for the various pubnames:
1736 //
1737 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1738 // for the DIE that is named.
1739 //
1740 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1741 // into the CU and the index value is computed according to the type of value
1742 // for the DIE that is named.
1743 //
1744 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1745 // it's the offset within the debug_info/debug_types dwo section, however, the
1746 // reference in the pubname header doesn't change.
1747 
1748 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1749 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1750                                                         const DIE *Die) {
1751   // Entities that ended up only in a Type Unit reference the CU instead (since
1752   // the pub entry has offsets within the CU there's no real offset that can be
1753   // provided anyway). As it happens all such entities (namespaces and types,
1754   // types only in C++ at that) are rendered as TYPE+EXTERNAL. If this turns out
1755   // not to be true it would be necessary to persist this information from the
1756   // point at which the entry is added to the index data structure - since by
1757   // the time the index is built from that, the original type/namespace DIE in a
1758   // type unit has already been destroyed so it can't be queried for properties
1759   // like tag, etc.
1760   if (Die->getTag() == dwarf::DW_TAG_compile_unit)
1761     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE,
1762                                           dwarf::GIEL_EXTERNAL);
1763   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1764 
1765   // We could have a specification DIE that has our most of our knowledge,
1766   // look for that now.
1767   if (DIEValue SpecVal = Die->findAttribute(dwarf::DW_AT_specification)) {
1768     DIE &SpecDIE = SpecVal.getDIEEntry().getEntry();
1769     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1770       Linkage = dwarf::GIEL_EXTERNAL;
1771   } else if (Die->findAttribute(dwarf::DW_AT_external))
1772     Linkage = dwarf::GIEL_EXTERNAL;
1773 
1774   switch (Die->getTag()) {
1775   case dwarf::DW_TAG_class_type:
1776   case dwarf::DW_TAG_structure_type:
1777   case dwarf::DW_TAG_union_type:
1778   case dwarf::DW_TAG_enumeration_type:
1779     return dwarf::PubIndexEntryDescriptor(
1780         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1781                               ? dwarf::GIEL_STATIC
1782                               : dwarf::GIEL_EXTERNAL);
1783   case dwarf::DW_TAG_typedef:
1784   case dwarf::DW_TAG_base_type:
1785   case dwarf::DW_TAG_subrange_type:
1786     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1787   case dwarf::DW_TAG_namespace:
1788     return dwarf::GIEK_TYPE;
1789   case dwarf::DW_TAG_subprogram:
1790     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1791   case dwarf::DW_TAG_variable:
1792     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1793   case dwarf::DW_TAG_enumerator:
1794     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1795                                           dwarf::GIEL_STATIC);
1796   default:
1797     return dwarf::GIEK_NONE;
1798   }
1799 }
1800 
1801 /// emitDebugPubSections - Emit visible names and types into debug pubnames and
1802 /// pubtypes sections.
1803 void DwarfDebug::emitDebugPubSections() {
1804   for (const auto &NU : CUMap) {
1805     DwarfCompileUnit *TheU = NU.second;
1806     if (!TheU->hasDwarfPubSections())
1807       continue;
1808 
1809     bool GnuStyle = TheU->getCUNode()->getNameTableKind() ==
1810                     DICompileUnit::DebugNameTableKind::GNU;
1811 
1812     Asm->OutStreamer->SwitchSection(
1813         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1814                  : Asm->getObjFileLowering().getDwarfPubNamesSection());
1815     emitDebugPubSection(GnuStyle, "Names", TheU, TheU->getGlobalNames());
1816 
1817     Asm->OutStreamer->SwitchSection(
1818         GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
1819                  : Asm->getObjFileLowering().getDwarfPubTypesSection());
1820     emitDebugPubSection(GnuStyle, "Types", TheU, TheU->getGlobalTypes());
1821   }
1822 }
1823 
1824 void DwarfDebug::emitSectionReference(const DwarfCompileUnit &CU) {
1825   if (useSectionsAsReferences())
1826     Asm->EmitDwarfOffset(CU.getSection()->getBeginSymbol(),
1827                          CU.getDebugSectionOffset());
1828   else
1829     Asm->emitDwarfSymbolReference(CU.getLabelBegin());
1830 }
1831 
1832 void DwarfDebug::emitDebugPubSection(bool GnuStyle, StringRef Name,
1833                                      DwarfCompileUnit *TheU,
1834                                      const StringMap<const DIE *> &Globals) {
1835   if (auto *Skeleton = TheU->getSkeleton())
1836     TheU = Skeleton;
1837 
1838   // Emit the header.
1839   Asm->OutStreamer->AddComment("Length of Public " + Name + " Info");
1840   MCSymbol *BeginLabel = Asm->createTempSymbol("pub" + Name + "_begin");
1841   MCSymbol *EndLabel = Asm->createTempSymbol("pub" + Name + "_end");
1842   Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1843 
1844   Asm->OutStreamer->EmitLabel(BeginLabel);
1845 
1846   Asm->OutStreamer->AddComment("DWARF Version");
1847   Asm->emitInt16(dwarf::DW_PUBNAMES_VERSION);
1848 
1849   Asm->OutStreamer->AddComment("Offset of Compilation Unit Info");
1850   emitSectionReference(*TheU);
1851 
1852   Asm->OutStreamer->AddComment("Compilation Unit Length");
1853   Asm->emitInt32(TheU->getLength());
1854 
1855   // Emit the pubnames for this compilation unit.
1856   for (const auto &GI : Globals) {
1857     const char *Name = GI.getKeyData();
1858     const DIE *Entity = GI.second;
1859 
1860     Asm->OutStreamer->AddComment("DIE offset");
1861     Asm->emitInt32(Entity->getOffset());
1862 
1863     if (GnuStyle) {
1864       dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
1865       Asm->OutStreamer->AddComment(
1866           Twine("Attributes: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) +
1867           ", " + dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
1868       Asm->emitInt8(Desc.toBits());
1869     }
1870 
1871     Asm->OutStreamer->AddComment("External Name");
1872     Asm->OutStreamer->EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
1873   }
1874 
1875   Asm->OutStreamer->AddComment("End Mark");
1876   Asm->emitInt32(0);
1877   Asm->OutStreamer->EmitLabel(EndLabel);
1878 }
1879 
1880 /// Emit null-terminated strings into a debug str section.
1881 void DwarfDebug::emitDebugStr() {
1882   MCSection *StringOffsetsSection = nullptr;
1883   if (useSegmentedStringOffsetsTable()) {
1884     emitStringOffsetsTableHeader();
1885     StringOffsetsSection = Asm->getObjFileLowering().getDwarfStrOffSection();
1886   }
1887   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1888   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection(),
1889                      StringOffsetsSection, /* UseRelativeOffsets = */ true);
1890 }
1891 
1892 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
1893                                    const DebugLocStream::Entry &Entry) {
1894   auto &&Comments = DebugLocs.getComments(Entry);
1895   auto Comment = Comments.begin();
1896   auto End = Comments.end();
1897   for (uint8_t Byte : DebugLocs.getBytes(Entry))
1898     Streamer.EmitInt8(Byte, Comment != End ? *(Comment++) : "");
1899 }
1900 
1901 static void emitDebugLocValue(const AsmPrinter &AP, const DIBasicType *BT,
1902                               const DebugLocEntry::Value &Value,
1903                               DwarfExpression &DwarfExpr) {
1904   auto *DIExpr = Value.getExpression();
1905   DIExpressionCursor ExprCursor(DIExpr);
1906   DwarfExpr.addFragmentOffset(DIExpr);
1907   // Regular entry.
1908   if (Value.isInt()) {
1909     if (BT && (BT->getEncoding() == dwarf::DW_ATE_signed ||
1910                BT->getEncoding() == dwarf::DW_ATE_signed_char))
1911       DwarfExpr.addSignedConstant(Value.getInt());
1912     else
1913       DwarfExpr.addUnsignedConstant(Value.getInt());
1914   } else if (Value.isLocation()) {
1915     MachineLocation Location = Value.getLoc();
1916     if (Location.isIndirect())
1917       DwarfExpr.setMemoryLocationKind();
1918     DIExpressionCursor Cursor(DIExpr);
1919     const TargetRegisterInfo &TRI = *AP.MF->getSubtarget().getRegisterInfo();
1920     if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg()))
1921       return;
1922     return DwarfExpr.addExpression(std::move(Cursor));
1923   } else if (Value.isConstantFP()) {
1924     APInt RawBytes = Value.getConstantFP()->getValueAPF().bitcastToAPInt();
1925     DwarfExpr.addUnsignedConstant(RawBytes);
1926   }
1927   DwarfExpr.addExpression(std::move(ExprCursor));
1928 }
1929 
1930 void DebugLocEntry::finalize(const AsmPrinter &AP,
1931                              DebugLocStream::ListBuilder &List,
1932                              const DIBasicType *BT) {
1933   assert(Begin != End && "unexpected location list entry with empty range");
1934   DebugLocStream::EntryBuilder Entry(List, Begin, End);
1935   BufferByteStreamer Streamer = Entry.getStreamer();
1936   DebugLocDwarfExpression DwarfExpr(AP.getDwarfVersion(), Streamer);
1937   const DebugLocEntry::Value &Value = Values[0];
1938   if (Value.isFragment()) {
1939     // Emit all fragments that belong to the same variable and range.
1940     assert(llvm::all_of(Values, [](DebugLocEntry::Value P) {
1941           return P.isFragment();
1942         }) && "all values are expected to be fragments");
1943     assert(std::is_sorted(Values.begin(), Values.end()) &&
1944            "fragments are expected to be sorted");
1945 
1946     for (auto Fragment : Values)
1947       emitDebugLocValue(AP, BT, Fragment, DwarfExpr);
1948 
1949   } else {
1950     assert(Values.size() == 1 && "only fragments may have >1 value");
1951     emitDebugLocValue(AP, BT, Value, DwarfExpr);
1952   }
1953   DwarfExpr.finalize();
1954 }
1955 
1956 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocStream::Entry &Entry) {
1957   // Emit the size.
1958   Asm->OutStreamer->AddComment("Loc expr size");
1959   Asm->emitInt16(DebugLocs.getBytes(Entry).size());
1960 
1961   // Emit the entry.
1962   APByteStreamer Streamer(*Asm);
1963   emitDebugLocEntry(Streamer, Entry);
1964 }
1965 
1966 // Emit the common part of the DWARF 5 range/locations list tables header.
1967 static void emitListsTableHeaderStart(AsmPrinter *Asm, const DwarfFile &Holder,
1968                                       MCSymbol *TableStart,
1969                                       MCSymbol *TableEnd) {
1970   // Build the table header, which starts with the length field.
1971   Asm->OutStreamer->AddComment("Length");
1972   Asm->EmitLabelDifference(TableEnd, TableStart, 4);
1973   Asm->OutStreamer->EmitLabel(TableStart);
1974   // Version number (DWARF v5 and later).
1975   Asm->OutStreamer->AddComment("Version");
1976   Asm->emitInt16(Asm->OutStreamer->getContext().getDwarfVersion());
1977   // Address size.
1978   Asm->OutStreamer->AddComment("Address size");
1979   Asm->emitInt8(Asm->MAI->getCodePointerSize());
1980   // Segment selector size.
1981   Asm->OutStreamer->AddComment("Segment selector size");
1982   Asm->emitInt8(0);
1983 }
1984 
1985 // Emit the header of a DWARF 5 range list table list table. Returns the symbol
1986 // that designates the end of the table for the caller to emit when the table is
1987 // complete.
1988 static MCSymbol *emitRnglistsTableHeader(AsmPrinter *Asm,
1989                                          const DwarfFile &Holder) {
1990   MCSymbol *TableStart = Asm->createTempSymbol("debug_rnglist_table_start");
1991   MCSymbol *TableEnd = Asm->createTempSymbol("debug_rnglist_table_end");
1992   emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
1993 
1994   Asm->OutStreamer->AddComment("Offset entry count");
1995   Asm->emitInt32(Holder.getRangeLists().size());
1996   Asm->OutStreamer->EmitLabel(Holder.getRnglistsTableBaseSym());
1997 
1998   for (const RangeSpanList &List : Holder.getRangeLists())
1999     Asm->EmitLabelDifference(List.getSym(), Holder.getRnglistsTableBaseSym(),
2000                              4);
2001 
2002   return TableEnd;
2003 }
2004 
2005 // Emit the header of a DWARF 5 locations list table. Returns the symbol that
2006 // designates the end of the table for the caller to emit when the table is
2007 // complete.
2008 static MCSymbol *emitLoclistsTableHeader(AsmPrinter *Asm,
2009                                          const DwarfFile &Holder) {
2010   MCSymbol *TableStart = Asm->createTempSymbol("debug_loclist_table_start");
2011   MCSymbol *TableEnd = Asm->createTempSymbol("debug_loclist_table_end");
2012   emitListsTableHeaderStart(Asm, Holder, TableStart, TableEnd);
2013 
2014   // FIXME: Generate the offsets table and use DW_FORM_loclistx with the
2015   // DW_AT_loclists_base attribute. Until then set the number of offsets to 0.
2016   Asm->OutStreamer->AddComment("Offset entry count");
2017   Asm->emitInt32(0);
2018   Asm->OutStreamer->EmitLabel(Holder.getLoclistsTableBaseSym());
2019 
2020   return TableEnd;
2021 }
2022 
2023 // Emit locations into the .debug_loc/.debug_rnglists section.
2024 void DwarfDebug::emitDebugLoc() {
2025   if (DebugLocs.getLists().empty())
2026     return;
2027 
2028   bool IsLocLists = getDwarfVersion() >= 5;
2029   MCSymbol *TableEnd = nullptr;
2030   if (IsLocLists) {
2031     Asm->OutStreamer->SwitchSection(
2032         Asm->getObjFileLowering().getDwarfLoclistsSection());
2033     TableEnd = emitLoclistsTableHeader(Asm, useSplitDwarf() ? SkeletonHolder
2034                                                             : InfoHolder);
2035   } else {
2036     Asm->OutStreamer->SwitchSection(
2037         Asm->getObjFileLowering().getDwarfLocSection());
2038   }
2039 
2040   unsigned char Size = Asm->MAI->getCodePointerSize();
2041   for (const auto &List : DebugLocs.getLists()) {
2042     Asm->OutStreamer->EmitLabel(List.Label);
2043 
2044     const DwarfCompileUnit *CU = List.CU;
2045     const MCSymbol *Base = CU->getBaseAddress();
2046     for (const auto &Entry : DebugLocs.getEntries(List)) {
2047       if (Base) {
2048         // Set up the range. This range is relative to the entry point of the
2049         // compile unit. This is a hard coded 0 for low_pc when we're emitting
2050         // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2051         if (IsLocLists) {
2052           Asm->OutStreamer->AddComment("DW_LLE_offset_pair");
2053           Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_offset_pair, 1);
2054           Asm->OutStreamer->AddComment("  starting offset");
2055           Asm->EmitLabelDifferenceAsULEB128(Entry.BeginSym, Base);
2056           Asm->OutStreamer->AddComment("  ending offset");
2057           Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Base);
2058         } else {
2059           Asm->EmitLabelDifference(Entry.BeginSym, Base, Size);
2060           Asm->EmitLabelDifference(Entry.EndSym, Base, Size);
2061         }
2062 
2063         emitDebugLocEntryLocation(Entry);
2064         continue;
2065       }
2066 
2067       // We have no base address.
2068       if (IsLocLists) {
2069         // TODO: Use DW_LLE_base_addressx + DW_LLE_offset_pair, or
2070         // DW_LLE_startx_length in case if there is only a single range.
2071         // That should reduce the size of the debug data emited.
2072         // For now just use the DW_LLE_startx_length for all cases.
2073         Asm->OutStreamer->AddComment("DW_LLE_startx_length");
2074         Asm->emitInt8(dwarf::DW_LLE_startx_length);
2075         Asm->OutStreamer->AddComment("  start idx");
2076         Asm->EmitULEB128(AddrPool.getIndex(Entry.BeginSym));
2077         Asm->OutStreamer->AddComment("  length");
2078         Asm->EmitLabelDifferenceAsULEB128(Entry.EndSym, Entry.BeginSym);
2079       } else {
2080         Asm->OutStreamer->EmitSymbolValue(Entry.BeginSym, Size);
2081         Asm->OutStreamer->EmitSymbolValue(Entry.EndSym, Size);
2082       }
2083 
2084       emitDebugLocEntryLocation(Entry);
2085     }
2086 
2087     if (IsLocLists) {
2088       // .debug_loclists section ends with DW_LLE_end_of_list.
2089       Asm->OutStreamer->AddComment("DW_LLE_end_of_list");
2090       Asm->OutStreamer->EmitIntValue(dwarf::DW_LLE_end_of_list, 1);
2091     } else {
2092       // Terminate the .debug_loc list with two 0 values.
2093       Asm->OutStreamer->EmitIntValue(0, Size);
2094       Asm->OutStreamer->EmitIntValue(0, Size);
2095     }
2096   }
2097 
2098   if (TableEnd)
2099     Asm->OutStreamer->EmitLabel(TableEnd);
2100 }
2101 
2102 void DwarfDebug::emitDebugLocDWO() {
2103   Asm->OutStreamer->SwitchSection(
2104       Asm->getObjFileLowering().getDwarfLocDWOSection());
2105   for (const auto &List : DebugLocs.getLists()) {
2106     Asm->OutStreamer->EmitLabel(List.Label);
2107     for (const auto &Entry : DebugLocs.getEntries(List)) {
2108       // GDB only supports startx_length in pre-standard split-DWARF.
2109       // (in v5 standard loclists, it currently* /only/ supports base_address +
2110       // offset_pair, so the implementations can't really share much since they
2111       // need to use different representations)
2112       // * as of October 2018, at least
2113       // Ideally/in v5, this could use SectionLabels to reuse existing addresses
2114       // in the address pool to minimize object size/relocations.
2115       Asm->emitInt8(dwarf::DW_LLE_startx_length);
2116       unsigned idx = AddrPool.getIndex(Entry.BeginSym);
2117       Asm->EmitULEB128(idx);
2118       Asm->EmitLabelDifference(Entry.EndSym, Entry.BeginSym, 4);
2119 
2120       emitDebugLocEntryLocation(Entry);
2121     }
2122     Asm->emitInt8(dwarf::DW_LLE_end_of_list);
2123   }
2124 }
2125 
2126 struct ArangeSpan {
2127   const MCSymbol *Start, *End;
2128 };
2129 
2130 // Emit a debug aranges section, containing a CU lookup for any
2131 // address we can tie back to a CU.
2132 void DwarfDebug::emitDebugARanges() {
2133   // Provides a unique id per text section.
2134   MapVector<MCSection *, SmallVector<SymbolCU, 8>> SectionMap;
2135 
2136   // Filter labels by section.
2137   for (const SymbolCU &SCU : ArangeLabels) {
2138     if (SCU.Sym->isInSection()) {
2139       // Make a note of this symbol and it's section.
2140       MCSection *Section = &SCU.Sym->getSection();
2141       if (!Section->getKind().isMetadata())
2142         SectionMap[Section].push_back(SCU);
2143     } else {
2144       // Some symbols (e.g. common/bss on mach-o) can have no section but still
2145       // appear in the output. This sucks as we rely on sections to build
2146       // arange spans. We can do it without, but it's icky.
2147       SectionMap[nullptr].push_back(SCU);
2148     }
2149   }
2150 
2151   DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> Spans;
2152 
2153   for (auto &I : SectionMap) {
2154     MCSection *Section = I.first;
2155     SmallVector<SymbolCU, 8> &List = I.second;
2156     if (List.size() < 1)
2157       continue;
2158 
2159     // If we have no section (e.g. common), just write out
2160     // individual spans for each symbol.
2161     if (!Section) {
2162       for (const SymbolCU &Cur : List) {
2163         ArangeSpan Span;
2164         Span.Start = Cur.Sym;
2165         Span.End = nullptr;
2166         assert(Cur.CU);
2167         Spans[Cur.CU].push_back(Span);
2168       }
2169       continue;
2170     }
2171 
2172     // Sort the symbols by offset within the section.
2173     std::stable_sort(
2174         List.begin(), List.end(), [&](const SymbolCU &A, const SymbolCU &B) {
2175           unsigned IA = A.Sym ? Asm->OutStreamer->GetSymbolOrder(A.Sym) : 0;
2176           unsigned IB = B.Sym ? Asm->OutStreamer->GetSymbolOrder(B.Sym) : 0;
2177 
2178           // Symbols with no order assigned should be placed at the end.
2179           // (e.g. section end labels)
2180           if (IA == 0)
2181             return false;
2182           if (IB == 0)
2183             return true;
2184           return IA < IB;
2185         });
2186 
2187     // Insert a final terminator.
2188     List.push_back(SymbolCU(nullptr, Asm->OutStreamer->endSection(Section)));
2189 
2190     // Build spans between each label.
2191     const MCSymbol *StartSym = List[0].Sym;
2192     for (size_t n = 1, e = List.size(); n < e; n++) {
2193       const SymbolCU &Prev = List[n - 1];
2194       const SymbolCU &Cur = List[n];
2195 
2196       // Try and build the longest span we can within the same CU.
2197       if (Cur.CU != Prev.CU) {
2198         ArangeSpan Span;
2199         Span.Start = StartSym;
2200         Span.End = Cur.Sym;
2201         assert(Prev.CU);
2202         Spans[Prev.CU].push_back(Span);
2203         StartSym = Cur.Sym;
2204       }
2205     }
2206   }
2207 
2208   // Start the dwarf aranges section.
2209   Asm->OutStreamer->SwitchSection(
2210       Asm->getObjFileLowering().getDwarfARangesSection());
2211 
2212   unsigned PtrSize = Asm->MAI->getCodePointerSize();
2213 
2214   // Build a list of CUs used.
2215   std::vector<DwarfCompileUnit *> CUs;
2216   for (const auto &it : Spans) {
2217     DwarfCompileUnit *CU = it.first;
2218     CUs.push_back(CU);
2219   }
2220 
2221   // Sort the CU list (again, to ensure consistent output order).
2222   llvm::sort(CUs, [](const DwarfCompileUnit *A, const DwarfCompileUnit *B) {
2223     return A->getUniqueID() < B->getUniqueID();
2224   });
2225 
2226   // Emit an arange table for each CU we used.
2227   for (DwarfCompileUnit *CU : CUs) {
2228     std::vector<ArangeSpan> &List = Spans[CU];
2229 
2230     // Describe the skeleton CU's offset and length, not the dwo file's.
2231     if (auto *Skel = CU->getSkeleton())
2232       CU = Skel;
2233 
2234     // Emit size of content not including length itself.
2235     unsigned ContentSize =
2236         sizeof(int16_t) + // DWARF ARange version number
2237         sizeof(int32_t) + // Offset of CU in the .debug_info section
2238         sizeof(int8_t) +  // Pointer Size (in bytes)
2239         sizeof(int8_t);   // Segment Size (in bytes)
2240 
2241     unsigned TupleSize = PtrSize * 2;
2242 
2243     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2244     unsigned Padding =
2245         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2246 
2247     ContentSize += Padding;
2248     ContentSize += (List.size() + 1) * TupleSize;
2249 
2250     // For each compile unit, write the list of spans it covers.
2251     Asm->OutStreamer->AddComment("Length of ARange Set");
2252     Asm->emitInt32(ContentSize);
2253     Asm->OutStreamer->AddComment("DWARF Arange version number");
2254     Asm->emitInt16(dwarf::DW_ARANGES_VERSION);
2255     Asm->OutStreamer->AddComment("Offset Into Debug Info Section");
2256     emitSectionReference(*CU);
2257     Asm->OutStreamer->AddComment("Address Size (in bytes)");
2258     Asm->emitInt8(PtrSize);
2259     Asm->OutStreamer->AddComment("Segment Size (in bytes)");
2260     Asm->emitInt8(0);
2261 
2262     Asm->OutStreamer->emitFill(Padding, 0xff);
2263 
2264     for (const ArangeSpan &Span : List) {
2265       Asm->EmitLabelReference(Span.Start, PtrSize);
2266 
2267       // Calculate the size as being from the span start to it's end.
2268       if (Span.End) {
2269         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2270       } else {
2271         // For symbols without an end marker (e.g. common), we
2272         // write a single arange entry containing just that one symbol.
2273         uint64_t Size = SymSize[Span.Start];
2274         if (Size == 0)
2275           Size = 1;
2276 
2277         Asm->OutStreamer->EmitIntValue(Size, PtrSize);
2278       }
2279     }
2280 
2281     Asm->OutStreamer->AddComment("ARange terminator");
2282     Asm->OutStreamer->EmitIntValue(0, PtrSize);
2283     Asm->OutStreamer->EmitIntValue(0, PtrSize);
2284   }
2285 }
2286 
2287 /// Emit a single range list. We handle both DWARF v5 and earlier.
2288 static void emitRangeList(DwarfDebug &DD, AsmPrinter *Asm,
2289                           const RangeSpanList &List) {
2290 
2291   auto DwarfVersion = DD.getDwarfVersion();
2292   // Emit our symbol so we can find the beginning of the range.
2293   Asm->OutStreamer->EmitLabel(List.getSym());
2294   // Gather all the ranges that apply to the same section so they can share
2295   // a base address entry.
2296   MapVector<const MCSection *, std::vector<const RangeSpan *>> SectionRanges;
2297   // Size for our labels.
2298   auto Size = Asm->MAI->getCodePointerSize();
2299 
2300   for (const RangeSpan &Range : List.getRanges())
2301     SectionRanges[&Range.getStart()->getSection()].push_back(&Range);
2302 
2303   const DwarfCompileUnit &CU = List.getCU();
2304   const MCSymbol *CUBase = CU.getBaseAddress();
2305   bool BaseIsSet = false;
2306   for (const auto &P : SectionRanges) {
2307     // Don't bother with a base address entry if there's only one range in
2308     // this section in this range list - for example ranges for a CU will
2309     // usually consist of single regions from each of many sections
2310     // (-ffunction-sections, or just C++ inline functions) except under LTO
2311     // or optnone where there may be holes in a single CU's section
2312     // contributions.
2313     auto *Base = CUBase;
2314     if (!Base && (P.second.size() > 1 || DwarfVersion < 5) &&
2315         (CU.getCUNode()->getRangesBaseAddress() || DwarfVersion >= 5)) {
2316       BaseIsSet = true;
2317       // FIXME/use care: This may not be a useful base address if it's not
2318       // the lowest address/range in this object.
2319       Base = P.second.front()->getStart();
2320       if (DwarfVersion >= 5) {
2321         Base = DD.getSectionLabel(&Base->getSection());
2322         Asm->OutStreamer->AddComment("DW_RLE_base_addressx");
2323         Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_base_addressx, 1);
2324         Asm->OutStreamer->AddComment("  base address index");
2325         Asm->EmitULEB128(DD.getAddressPool().getIndex(Base));
2326       } else {
2327         Asm->OutStreamer->EmitIntValue(-1, Size);
2328         Asm->OutStreamer->AddComment("  base address");
2329         Asm->OutStreamer->EmitSymbolValue(Base, Size);
2330       }
2331     } else if (BaseIsSet && DwarfVersion < 5) {
2332       BaseIsSet = false;
2333       assert(!Base);
2334       Asm->OutStreamer->EmitIntValue(-1, Size);
2335       Asm->OutStreamer->EmitIntValue(0, Size);
2336     }
2337 
2338     for (const auto *RS : P.second) {
2339       const MCSymbol *Begin = RS->getStart();
2340       const MCSymbol *End = RS->getEnd();
2341       assert(Begin && "Range without a begin symbol?");
2342       assert(End && "Range without an end symbol?");
2343       if (Base) {
2344         if (DwarfVersion >= 5) {
2345           // Emit DW_RLE_offset_pair when we have a base.
2346           Asm->OutStreamer->AddComment("DW_RLE_offset_pair");
2347           Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_offset_pair, 1);
2348           Asm->OutStreamer->AddComment("  starting offset");
2349           Asm->EmitLabelDifferenceAsULEB128(Begin, Base);
2350           Asm->OutStreamer->AddComment("  ending offset");
2351           Asm->EmitLabelDifferenceAsULEB128(End, Base);
2352         } else {
2353           Asm->EmitLabelDifference(Begin, Base, Size);
2354           Asm->EmitLabelDifference(End, Base, Size);
2355         }
2356       } else if (DwarfVersion >= 5) {
2357         Asm->OutStreamer->AddComment("DW_RLE_startx_length");
2358         Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_startx_length, 1);
2359         Asm->OutStreamer->AddComment("  start index");
2360         Asm->EmitULEB128(DD.getAddressPool().getIndex(Begin));
2361         Asm->OutStreamer->AddComment("  length");
2362         Asm->EmitLabelDifferenceAsULEB128(End, Begin);
2363       } else {
2364         Asm->OutStreamer->EmitSymbolValue(Begin, Size);
2365         Asm->OutStreamer->EmitSymbolValue(End, Size);
2366       }
2367     }
2368   }
2369   if (DwarfVersion >= 5) {
2370     Asm->OutStreamer->AddComment("DW_RLE_end_of_list");
2371     Asm->OutStreamer->EmitIntValue(dwarf::DW_RLE_end_of_list, 1);
2372   } else {
2373     // Terminate the list with two 0 values.
2374     Asm->OutStreamer->EmitIntValue(0, Size);
2375     Asm->OutStreamer->EmitIntValue(0, Size);
2376   }
2377 }
2378 
2379 void emitDebugRangesImpl(DwarfDebug &DD, AsmPrinter *Asm,
2380                          const DwarfFile &Holder, MCSymbol *TableEnd) {
2381   for (const RangeSpanList &List : Holder.getRangeLists())
2382     emitRangeList(DD, Asm, List);
2383 
2384   if (TableEnd)
2385     Asm->OutStreamer->EmitLabel(TableEnd);
2386 }
2387 
2388 /// Emit address ranges into the .debug_ranges section or into the DWARF v5
2389 /// .debug_rnglists section.
2390 void DwarfDebug::emitDebugRanges() {
2391   if (CUMap.empty())
2392     return;
2393 
2394   const auto &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2395 
2396   if (Holder.getRangeLists().empty())
2397     return;
2398 
2399   assert(useRangesSection());
2400   assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2401     return Pair.second->getCUNode()->isDebugDirectivesOnly();
2402   }));
2403 
2404   // Start the dwarf ranges section.
2405   MCSymbol *TableEnd = nullptr;
2406   if (getDwarfVersion() >= 5) {
2407     Asm->OutStreamer->SwitchSection(
2408         Asm->getObjFileLowering().getDwarfRnglistsSection());
2409     TableEnd = emitRnglistsTableHeader(Asm, Holder);
2410   } else
2411     Asm->OutStreamer->SwitchSection(
2412         Asm->getObjFileLowering().getDwarfRangesSection());
2413 
2414   emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2415 }
2416 
2417 void DwarfDebug::emitDebugRangesDWO() {
2418   assert(useSplitDwarf());
2419 
2420   if (CUMap.empty())
2421     return;
2422 
2423   const auto &Holder = InfoHolder;
2424 
2425   if (Holder.getRangeLists().empty())
2426     return;
2427 
2428   assert(getDwarfVersion() >= 5);
2429   assert(useRangesSection());
2430   assert(llvm::none_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2431     return Pair.second->getCUNode()->isDebugDirectivesOnly();
2432   }));
2433 
2434   // Start the dwarf ranges section.
2435   Asm->OutStreamer->SwitchSection(
2436       Asm->getObjFileLowering().getDwarfRnglistsDWOSection());
2437   MCSymbol *TableEnd = emitRnglistsTableHeader(Asm, Holder);
2438 
2439   emitDebugRangesImpl(*this, Asm, Holder, TableEnd);
2440 }
2441 
2442 void DwarfDebug::handleMacroNodes(DIMacroNodeArray Nodes, DwarfCompileUnit &U) {
2443   for (auto *MN : Nodes) {
2444     if (auto *M = dyn_cast<DIMacro>(MN))
2445       emitMacro(*M);
2446     else if (auto *F = dyn_cast<DIMacroFile>(MN))
2447       emitMacroFile(*F, U);
2448     else
2449       llvm_unreachable("Unexpected DI type!");
2450   }
2451 }
2452 
2453 void DwarfDebug::emitMacro(DIMacro &M) {
2454   Asm->EmitULEB128(M.getMacinfoType());
2455   Asm->EmitULEB128(M.getLine());
2456   StringRef Name = M.getName();
2457   StringRef Value = M.getValue();
2458   Asm->OutStreamer->EmitBytes(Name);
2459   if (!Value.empty()) {
2460     // There should be one space between macro name and macro value.
2461     Asm->emitInt8(' ');
2462     Asm->OutStreamer->EmitBytes(Value);
2463   }
2464   Asm->emitInt8('\0');
2465 }
2466 
2467 void DwarfDebug::emitMacroFile(DIMacroFile &F, DwarfCompileUnit &U) {
2468   assert(F.getMacinfoType() == dwarf::DW_MACINFO_start_file);
2469   Asm->EmitULEB128(dwarf::DW_MACINFO_start_file);
2470   Asm->EmitULEB128(F.getLine());
2471   Asm->EmitULEB128(U.getOrCreateSourceID(F.getFile()));
2472   handleMacroNodes(F.getElements(), U);
2473   Asm->EmitULEB128(dwarf::DW_MACINFO_end_file);
2474 }
2475 
2476 /// Emit macros into a debug macinfo section.
2477 void DwarfDebug::emitDebugMacinfo() {
2478   if (CUMap.empty())
2479     return;
2480 
2481   if (llvm::all_of(CUMap, [](const decltype(CUMap)::value_type &Pair) {
2482         return Pair.second->getCUNode()->isDebugDirectivesOnly();
2483       }))
2484     return;
2485 
2486   // Start the dwarf macinfo section.
2487   Asm->OutStreamer->SwitchSection(
2488       Asm->getObjFileLowering().getDwarfMacinfoSection());
2489 
2490   for (const auto &P : CUMap) {
2491     auto &TheCU = *P.second;
2492     if (TheCU.getCUNode()->isDebugDirectivesOnly())
2493       continue;
2494     auto *SkCU = TheCU.getSkeleton();
2495     DwarfCompileUnit &U = SkCU ? *SkCU : TheCU;
2496     auto *CUNode = cast<DICompileUnit>(P.first);
2497     DIMacroNodeArray Macros = CUNode->getMacros();
2498     if (!Macros.empty()) {
2499       Asm->OutStreamer->EmitLabel(U.getMacroLabelBegin());
2500       handleMacroNodes(Macros, U);
2501     }
2502   }
2503   Asm->OutStreamer->AddComment("End Of Macro List Mark");
2504   Asm->emitInt8(0);
2505 }
2506 
2507 // DWARF5 Experimental Separate Dwarf emitters.
2508 
2509 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2510                                   std::unique_ptr<DwarfCompileUnit> NewU) {
2511 
2512   if (!CompilationDir.empty())
2513     NewU->addString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2514 
2515   addGnuPubAttributes(*NewU, Die);
2516 
2517   SkeletonHolder.addUnit(std::move(NewU));
2518 }
2519 
2520 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2521 
2522   auto OwnedUnit = llvm::make_unique<DwarfCompileUnit>(
2523       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2524   DwarfCompileUnit &NewCU = *OwnedUnit;
2525   NewCU.setSection(Asm->getObjFileLowering().getDwarfInfoSection());
2526 
2527   NewCU.initStmtList();
2528 
2529   if (useSegmentedStringOffsetsTable())
2530     NewCU.addStringOffsetsStart();
2531 
2532   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2533 
2534   return NewCU;
2535 }
2536 
2537 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2538 // compile units that would normally be in debug_info.
2539 void DwarfDebug::emitDebugInfoDWO() {
2540   assert(useSplitDwarf() && "No split dwarf debug info?");
2541   // Don't emit relocations into the dwo file.
2542   InfoHolder.emitUnits(/* UseOffsets */ true);
2543 }
2544 
2545 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2546 // abbreviations for the .debug_info.dwo section.
2547 void DwarfDebug::emitDebugAbbrevDWO() {
2548   assert(useSplitDwarf() && "No split dwarf?");
2549   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2550 }
2551 
2552 void DwarfDebug::emitDebugLineDWO() {
2553   assert(useSplitDwarf() && "No split dwarf?");
2554   SplitTypeUnitFileTable.Emit(
2555       *Asm->OutStreamer, MCDwarfLineTableParams(),
2556       Asm->getObjFileLowering().getDwarfLineDWOSection());
2557 }
2558 
2559 void DwarfDebug::emitStringOffsetsTableHeaderDWO() {
2560   assert(useSplitDwarf() && "No split dwarf?");
2561   InfoHolder.getStringPool().emitStringOffsetsTableHeader(
2562       *Asm, Asm->getObjFileLowering().getDwarfStrOffDWOSection(),
2563       InfoHolder.getStringOffsetsStartSym());
2564 }
2565 
2566 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2567 // string section and is identical in format to traditional .debug_str
2568 // sections.
2569 void DwarfDebug::emitDebugStrDWO() {
2570   if (useSegmentedStringOffsetsTable())
2571     emitStringOffsetsTableHeaderDWO();
2572   assert(useSplitDwarf() && "No split dwarf?");
2573   MCSection *OffSec = Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2574   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2575                          OffSec, /* UseRelativeOffsets = */ false);
2576 }
2577 
2578 // Emit address pool.
2579 void DwarfDebug::emitDebugAddr() {
2580   AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
2581 }
2582 
2583 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2584   if (!useSplitDwarf())
2585     return nullptr;
2586   const DICompileUnit *DIUnit = CU.getCUNode();
2587   SplitTypeUnitFileTable.maybeSetRootFile(
2588       DIUnit->getDirectory(), DIUnit->getFilename(),
2589       CU.getMD5AsBytes(DIUnit->getFile()), DIUnit->getSource());
2590   return &SplitTypeUnitFileTable;
2591 }
2592 
2593 uint64_t DwarfDebug::makeTypeSignature(StringRef Identifier) {
2594   MD5 Hash;
2595   Hash.update(Identifier);
2596   // ... take the least significant 8 bytes and return those. Our MD5
2597   // implementation always returns its results in little endian, so we actually
2598   // need the "high" word.
2599   MD5::MD5Result Result;
2600   Hash.final(Result);
2601   return Result.high();
2602 }
2603 
2604 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2605                                       StringRef Identifier, DIE &RefDie,
2606                                       const DICompositeType *CTy) {
2607   // Fast path if we're building some type units and one has already used the
2608   // address pool we know we're going to throw away all this work anyway, so
2609   // don't bother building dependent types.
2610   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2611     return;
2612 
2613   auto Ins = TypeSignatures.insert(std::make_pair(CTy, 0));
2614   if (!Ins.second) {
2615     CU.addDIETypeSignature(RefDie, Ins.first->second);
2616     return;
2617   }
2618 
2619   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2620   AddrPool.resetUsedFlag();
2621 
2622   auto OwnedUnit = llvm::make_unique<DwarfTypeUnit>(CU, Asm, this, &InfoHolder,
2623                                                     getDwoLineTable(CU));
2624   DwarfTypeUnit &NewTU = *OwnedUnit;
2625   DIE &UnitDie = NewTU.getUnitDie();
2626   TypeUnitsUnderConstruction.emplace_back(std::move(OwnedUnit), CTy);
2627 
2628   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2629                 CU.getLanguage());
2630 
2631   uint64_t Signature = makeTypeSignature(Identifier);
2632   NewTU.setTypeSignature(Signature);
2633   Ins.first->second = Signature;
2634 
2635   if (useSplitDwarf()) {
2636     MCSection *Section =
2637         getDwarfVersion() <= 4
2638             ? Asm->getObjFileLowering().getDwarfTypesDWOSection()
2639             : Asm->getObjFileLowering().getDwarfInfoDWOSection();
2640     NewTU.setSection(Section);
2641   } else {
2642     MCSection *Section =
2643         getDwarfVersion() <= 4
2644             ? Asm->getObjFileLowering().getDwarfTypesSection(Signature)
2645             : Asm->getObjFileLowering().getDwarfInfoSection(Signature);
2646     NewTU.setSection(Section);
2647     // Non-split type units reuse the compile unit's line table.
2648     CU.applyStmtList(UnitDie);
2649   }
2650 
2651   // Add DW_AT_str_offsets_base to the type unit DIE, but not for split type
2652   // units.
2653   if (useSegmentedStringOffsetsTable() && !useSplitDwarf())
2654     NewTU.addStringOffsetsStart();
2655 
2656   NewTU.setType(NewTU.createTypeDIE(CTy));
2657 
2658   if (TopLevelType) {
2659     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2660     TypeUnitsUnderConstruction.clear();
2661 
2662     // Types referencing entries in the address table cannot be placed in type
2663     // units.
2664     if (AddrPool.hasBeenUsed()) {
2665 
2666       // Remove all the types built while building this type.
2667       // This is pessimistic as some of these types might not be dependent on
2668       // the type that used an address.
2669       for (const auto &TU : TypeUnitsToAdd)
2670         TypeSignatures.erase(TU.second);
2671 
2672       // Construct this type in the CU directly.
2673       // This is inefficient because all the dependent types will be rebuilt
2674       // from scratch, including building them in type units, discovering that
2675       // they depend on addresses, throwing them out and rebuilding them.
2676       CU.constructTypeDIE(RefDie, cast<DICompositeType>(CTy));
2677       return;
2678     }
2679 
2680     // If the type wasn't dependent on fission addresses, finish adding the type
2681     // and all its dependent types.
2682     for (auto &TU : TypeUnitsToAdd) {
2683       InfoHolder.computeSizeAndOffsetsForUnit(TU.first.get());
2684       InfoHolder.emitUnit(TU.first.get(), useSplitDwarf());
2685     }
2686   }
2687   CU.addDIETypeSignature(RefDie, Signature);
2688 }
2689 
2690 // Add the Name along with its companion DIE to the appropriate accelerator
2691 // table (for AccelTableKind::Dwarf it's always AccelDebugNames, for
2692 // AccelTableKind::Apple, we use the table we got as an argument). If
2693 // accelerator tables are disabled, this function does nothing.
2694 template <typename DataT>
2695 void DwarfDebug::addAccelNameImpl(const DICompileUnit &CU,
2696                                   AccelTable<DataT> &AppleAccel, StringRef Name,
2697                                   const DIE &Die) {
2698   if (getAccelTableKind() == AccelTableKind::None)
2699     return;
2700 
2701   if (getAccelTableKind() != AccelTableKind::Apple &&
2702       CU.getNameTableKind() == DICompileUnit::DebugNameTableKind::None)
2703     return;
2704 
2705   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2706   DwarfStringPoolEntryRef Ref = Holder.getStringPool().getEntry(*Asm, Name);
2707 
2708   switch (getAccelTableKind()) {
2709   case AccelTableKind::Apple:
2710     AppleAccel.addName(Ref, Die);
2711     break;
2712   case AccelTableKind::Dwarf:
2713     AccelDebugNames.addName(Ref, Die);
2714     break;
2715   case AccelTableKind::Default:
2716     llvm_unreachable("Default should have already been resolved.");
2717   case AccelTableKind::None:
2718     llvm_unreachable("None handled above");
2719   }
2720 }
2721 
2722 void DwarfDebug::addAccelName(const DICompileUnit &CU, StringRef Name,
2723                               const DIE &Die) {
2724   addAccelNameImpl(CU, AccelNames, Name, Die);
2725 }
2726 
2727 void DwarfDebug::addAccelObjC(const DICompileUnit &CU, StringRef Name,
2728                               const DIE &Die) {
2729   // ObjC names go only into the Apple accelerator tables.
2730   if (getAccelTableKind() == AccelTableKind::Apple)
2731     addAccelNameImpl(CU, AccelObjC, Name, Die);
2732 }
2733 
2734 void DwarfDebug::addAccelNamespace(const DICompileUnit &CU, StringRef Name,
2735                                    const DIE &Die) {
2736   addAccelNameImpl(CU, AccelNamespace, Name, Die);
2737 }
2738 
2739 void DwarfDebug::addAccelType(const DICompileUnit &CU, StringRef Name,
2740                               const DIE &Die, char Flags) {
2741   addAccelNameImpl(CU, AccelTypes, Name, Die);
2742 }
2743 
2744 uint16_t DwarfDebug::getDwarfVersion() const {
2745   return Asm->OutStreamer->getContext().getDwarfVersion();
2746 }
2747 
2748 void DwarfDebug::addSectionLabel(const MCSymbol *Sym) {
2749   SectionLabels.insert(std::make_pair(&Sym->getSection(), Sym));
2750 }
2751 
2752 const MCSymbol *DwarfDebug::getSectionLabel(const MCSection *S) {
2753   return SectionLabels.find(S)->second;
2754 }
2755