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