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