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