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