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