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