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