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