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