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