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