28ea3104f004748c99d09186d05ee3d068a9b2b3
[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           TheCU.constructImportedEntityDIE(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(TheCU.constructImportedEntityDIE(Module));
694 }
695
696 // Emit all Dwarf sections that should come prior to the content. Create
697 // global DIEs and emit initial debug info sections. This is invoked by
698 // the target AsmPrinter.
699 void DwarfDebug::beginModule() {
700   if (DisableDebugInfoPrinting)
701     return;
702
703   const Module *M = MMI->getModule();
704
705   FunctionDIs = makeSubprogramMap(*M);
706
707   // If module has named metadata anchors then use them, otherwise scan the
708   // module using debug info finder to collect debug info.
709   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
710   if (!CU_Nodes)
711     return;
712   TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
713
714   // Emit initial sections so we can reference labels later.
715   emitSectionLabels();
716
717   SingleCU = CU_Nodes->getNumOperands() == 1;
718
719   for (MDNode *N : CU_Nodes->operands()) {
720     DICompileUnit CUNode(N);
721     DwarfCompileUnit &CU = constructDwarfCompileUnit(CUNode);
722     DIArray ImportedEntities = CUNode.getImportedEntities();
723     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
724       ScopesWithImportedEntities.push_back(std::make_pair(
725           DIImportedEntity(ImportedEntities.getElement(i)).getContext(),
726           ImportedEntities.getElement(i)));
727     std::sort(ScopesWithImportedEntities.begin(),
728               ScopesWithImportedEntities.end(), less_first());
729     DIArray GVs = CUNode.getGlobalVariables();
730     for (unsigned i = 0, e = GVs.getNumElements(); i != e; ++i)
731       CU.getOrCreateGlobalVariableDIE(DIGlobalVariable(GVs.getElement(i)));
732     DIArray SPs = CUNode.getSubprograms();
733     for (unsigned i = 0, e = SPs.getNumElements(); i != e; ++i)
734       SPMap.insert(std::make_pair(SPs.getElement(i), &CU));
735     DIArray EnumTypes = CUNode.getEnumTypes();
736     for (unsigned i = 0, e = EnumTypes.getNumElements(); i != e; ++i) {
737       DIType Ty(EnumTypes.getElement(i));
738       // The enum types array by design contains pointers to
739       // MDNodes rather than DIRefs. Unique them here.
740       DIType UniqueTy(resolve(Ty.getRef()));
741       CU.getOrCreateTypeDIE(UniqueTy);
742     }
743     DIArray RetainedTypes = CUNode.getRetainedTypes();
744     for (unsigned i = 0, e = RetainedTypes.getNumElements(); i != e; ++i) {
745       DIType Ty(RetainedTypes.getElement(i));
746       // The retained types array by design contains pointers to
747       // MDNodes rather than DIRefs. Unique them here.
748       DIType UniqueTy(resolve(Ty.getRef()));
749       CU.getOrCreateTypeDIE(UniqueTy);
750     }
751     // Emit imported_modules last so that the relevant context is already
752     // available.
753     for (unsigned i = 0, e = ImportedEntities.getNumElements(); i != e; ++i)
754       constructAndAddImportedEntityDIE(CU, ImportedEntities.getElement(i));
755   }
756
757   // Tell MMI that we have debug info.
758   MMI->setDebugInfoAvailability(true);
759
760   // Prime section data.
761   SectionMap[Asm->getObjFileLowering().getTextSection()];
762 }
763
764 void DwarfDebug::finishVariableDefinitions() {
765   for (const auto &Var : ConcreteVariables) {
766     DIE *VariableDie = Var->getDIE();
767     assert(VariableDie);
768     // FIXME: Consider the time-space tradeoff of just storing the unit pointer
769     // in the ConcreteVariables list, rather than looking it up again here.
770     // DIE::getUnit isn't simple - it walks parent pointers, etc.
771     DwarfCompileUnit *Unit = lookupUnit(VariableDie->getUnit());
772     assert(Unit);
773     DbgVariable *AbsVar = getExistingAbstractVariable(Var->getVariable());
774     if (AbsVar && AbsVar->getDIE()) {
775       Unit->addDIEEntry(*VariableDie, dwarf::DW_AT_abstract_origin,
776                         *AbsVar->getDIE());
777     } else
778       Unit->applyVariableAttributes(*Var, *VariableDie);
779   }
780 }
781
782 void DwarfDebug::finishSubprogramDefinitions() {
783   const Module *M = MMI->getModule();
784
785   NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu");
786   for (MDNode *N : CU_Nodes->operands()) {
787     DICompileUnit TheCU(N);
788     // Construct subprogram DIE and add variables DIEs.
789     DwarfCompileUnit *SPCU =
790         static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
791     DIArray Subprograms = TheCU.getSubprograms();
792     for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
793       DISubprogram SP(Subprograms.getElement(i));
794       // Perhaps the subprogram is in another CU (such as due to comdat
795       // folding, etc), in which case ignore it here.
796       if (SPMap[SP] != SPCU)
797         continue;
798       DIE *D = SPCU->getDIE(SP);
799       if (DIE *AbsSPDIE = AbstractSPDies.lookup(SP)) {
800         if (D)
801           // If this subprogram has an abstract definition, reference that
802           SPCU->addDIEEntry(*D, dwarf::DW_AT_abstract_origin, *AbsSPDIE);
803       } else {
804         if (!D && TheCU.getEmissionKind() != DIBuilder::LineTablesOnly)
805           // Lazily construct the subprogram if we didn't see either concrete or
806           // inlined versions during codegen. (except in -gmlt ^ where we want
807           // to omit these entirely)
808           D = SPCU->getOrCreateSubprogramDIE(SP);
809         if (D)
810           // And attach the attributes
811           SPCU->applySubprogramAttributesToDefinition(SP, *D);
812       }
813     }
814   }
815 }
816
817
818 // Collect info for variables that were optimized out.
819 void DwarfDebug::collectDeadVariables() {
820   const Module *M = MMI->getModule();
821
822   if (NamedMDNode *CU_Nodes = M->getNamedMetadata("llvm.dbg.cu")) {
823     for (MDNode *N : CU_Nodes->operands()) {
824       DICompileUnit TheCU(N);
825       // Construct subprogram DIE and add variables DIEs.
826       DwarfCompileUnit *SPCU =
827           static_cast<DwarfCompileUnit *>(CUMap.lookup(TheCU));
828       assert(SPCU && "Unable to find Compile Unit!");
829       DIArray Subprograms = TheCU.getSubprograms();
830       for (unsigned i = 0, e = Subprograms.getNumElements(); i != e; ++i) {
831         DISubprogram SP(Subprograms.getElement(i));
832         if (ProcessedSPNodes.count(SP) != 0)
833           continue;
834         assert(SP.isSubprogram() &&
835                "CU's subprogram list contains a non-subprogram");
836         assert(SP.isDefinition() &&
837                "CU's subprogram list contains a subprogram declaration");
838         DIArray Variables = SP.getVariables();
839         if (Variables.getNumElements() == 0)
840           continue;
841
842         DIE *SPDIE = AbstractSPDies.lookup(SP);
843         if (!SPDIE)
844           SPDIE = SPCU->getDIE(SP);
845         assert(SPDIE);
846         for (unsigned vi = 0, ve = Variables.getNumElements(); vi != ve; ++vi) {
847           DIVariable DV(Variables.getElement(vi));
848           assert(DV.isVariable());
849           DbgVariable NewVar(DV, DIExpression(nullptr), this);
850           auto VariableDie = SPCU->constructVariableDIE(NewVar);
851           SPCU->applyVariableAttributes(NewVar, *VariableDie);
852           SPDIE->addChild(std::move(VariableDie));
853         }
854       }
855     }
856   }
857 }
858
859 void DwarfDebug::finalizeModuleInfo() {
860   finishSubprogramDefinitions();
861
862   finishVariableDefinitions();
863
864   // Collect info for variables that were optimized out.
865   collectDeadVariables();
866
867   // Handle anything that needs to be done on a per-unit basis after
868   // all other generation.
869   for (const auto &TheU : getUnits()) {
870     // Emit DW_AT_containing_type attribute to connect types with their
871     // vtable holding type.
872     TheU->constructContainingTypeDIEs();
873
874     // Add CU specific attributes if we need to add any.
875     if (TheU->getUnitDie().getTag() == dwarf::DW_TAG_compile_unit) {
876       // If we're splitting the dwarf out now that we've got the entire
877       // CU then add the dwo id to it.
878       DwarfCompileUnit *SkCU =
879           static_cast<DwarfCompileUnit *>(TheU->getSkeleton());
880       if (useSplitDwarf()) {
881         // Emit a unique identifier for this CU.
882         uint64_t ID = DIEHash(Asm).computeCUSignature(TheU->getUnitDie());
883         TheU->addUInt(TheU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
884                       dwarf::DW_FORM_data8, ID);
885         SkCU->addUInt(SkCU->getUnitDie(), dwarf::DW_AT_GNU_dwo_id,
886                       dwarf::DW_FORM_data8, ID);
887
888         // We don't keep track of which addresses are used in which CU so this
889         // is a bit pessimistic under LTO.
890         if (!AddrPool.isEmpty())
891           addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
892                           dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym,
893                           DwarfAddrSectionSym);
894         if (!TheU->getRangeLists().empty())
895           addSectionLabel(*Asm, *SkCU, SkCU->getUnitDie(),
896                           dwarf::DW_AT_GNU_ranges_base,
897                           DwarfDebugRangeSectionSym, DwarfDebugRangeSectionSym);
898       }
899
900       // If we have code split among multiple sections or non-contiguous
901       // ranges of code then emit a DW_AT_ranges attribute on the unit that will
902       // remain in the .o file, otherwise add a DW_AT_low_pc.
903       // FIXME: We should use ranges allow reordering of code ala
904       // .subsections_via_symbols in mach-o. This would mean turning on
905       // ranges for all subprogram DIEs for mach-o.
906       DwarfCompileUnit &U =
907           SkCU ? *SkCU : static_cast<DwarfCompileUnit &>(*TheU);
908       unsigned NumRanges = TheU->getRanges().size();
909       if (NumRanges) {
910         if (NumRanges > 1) {
911           addSectionLabel(*Asm, U, U.getUnitDie(), dwarf::DW_AT_ranges,
912                           Asm->GetTempSymbol("cu_ranges", U.getUniqueID()),
913                           DwarfDebugRangeSectionSym);
914
915           // A DW_AT_low_pc attribute may also be specified in combination with
916           // DW_AT_ranges to specify the default base address for use in
917           // location lists (see Section 2.6.2) and range lists (see Section
918           // 2.17.3).
919           U.addUInt(U.getUnitDie(), dwarf::DW_AT_low_pc, dwarf::DW_FORM_addr,
920                     0);
921         } else {
922           RangeSpan &Range = TheU->getRanges().back();
923           U.attachLowHighPC(U.getUnitDie(), Range.getStart(), Range.getEnd());
924         }
925       }
926     }
927   }
928
929   // Compute DIE offsets and sizes.
930   InfoHolder.computeSizeAndOffsets();
931   if (useSplitDwarf())
932     SkeletonHolder.computeSizeAndOffsets();
933 }
934
935 void DwarfDebug::endSections() {
936   // Filter labels by section.
937   for (const SymbolCU &SCU : ArangeLabels) {
938     if (SCU.Sym->isInSection()) {
939       // Make a note of this symbol and it's section.
940       const MCSection *Section = &SCU.Sym->getSection();
941       if (!Section->getKind().isMetadata())
942         SectionMap[Section].push_back(SCU);
943     } else {
944       // Some symbols (e.g. common/bss on mach-o) can have no section but still
945       // appear in the output. This sucks as we rely on sections to build
946       // arange spans. We can do it without, but it's icky.
947       SectionMap[nullptr].push_back(SCU);
948     }
949   }
950
951   // Build a list of sections used.
952   std::vector<const MCSection *> Sections;
953   for (const auto &it : SectionMap) {
954     const MCSection *Section = it.first;
955     Sections.push_back(Section);
956   }
957
958   // Sort the sections into order.
959   // This is only done to ensure consistent output order across different runs.
960   std::sort(Sections.begin(), Sections.end(), SectionSort);
961
962   // Add terminating symbols for each section.
963   for (unsigned ID = 0, E = Sections.size(); ID != E; ID++) {
964     const MCSection *Section = Sections[ID];
965     MCSymbol *Sym = nullptr;
966
967     if (Section) {
968       // We can't call MCSection::getLabelEndName, as it's only safe to do so
969       // if we know the section name up-front. For user-created sections, the
970       // resulting label may not be valid to use as a label. (section names can
971       // use a greater set of characters on some systems)
972       Sym = Asm->GetTempSymbol("debug_end", ID);
973       Asm->OutStreamer.SwitchSection(Section);
974       Asm->OutStreamer.EmitLabel(Sym);
975     }
976
977     // Insert a final terminator.
978     SectionMap[Section].push_back(SymbolCU(nullptr, Sym));
979   }
980 }
981
982 // Emit all Dwarf sections that should come after the content.
983 void DwarfDebug::endModule() {
984   assert(CurFn == nullptr);
985   assert(CurMI == nullptr);
986
987   if (!FirstCU)
988     return;
989
990   // End any existing sections.
991   // TODO: Does this need to happen?
992   endSections();
993
994   // Finalize the debug info for the module.
995   finalizeModuleInfo();
996
997   emitDebugStr();
998
999   // Emit all the DIEs into a debug info section.
1000   emitDebugInfo();
1001
1002   // Corresponding abbreviations into a abbrev section.
1003   emitAbbreviations();
1004
1005   // Emit info into a debug aranges section.
1006   if (GenerateARangeSection)
1007     emitDebugARanges();
1008
1009   // Emit info into a debug ranges section.
1010   emitDebugRanges();
1011
1012   if (useSplitDwarf()) {
1013     emitDebugStrDWO();
1014     emitDebugInfoDWO();
1015     emitDebugAbbrevDWO();
1016     emitDebugLineDWO();
1017     emitDebugLocDWO();
1018     // Emit DWO addresses.
1019     AddrPool.emit(*Asm, Asm->getObjFileLowering().getDwarfAddrSection());
1020   } else
1021     // Emit info into a debug loc section.
1022     emitDebugLoc();
1023
1024   // Emit info into the dwarf accelerator table sections.
1025   if (useDwarfAccelTables()) {
1026     emitAccelNames();
1027     emitAccelObjC();
1028     emitAccelNamespaces();
1029     emitAccelTypes();
1030   }
1031
1032   // Emit the pubnames and pubtypes sections if requested.
1033   if (HasDwarfPubSections) {
1034     emitDebugPubNames(GenerateGnuPubSections);
1035     emitDebugPubTypes(GenerateGnuPubSections);
1036   }
1037
1038   // clean up.
1039   SPMap.clear();
1040   AbstractVariables.clear();
1041
1042   // Reset these for the next Module if we have one.
1043   FirstCU = nullptr;
1044 }
1045
1046 // Find abstract variable, if any, associated with Var.
1047 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV,
1048                                                      DIVariable &Cleansed) {
1049   LLVMContext &Ctx = DV->getContext();
1050   // More then one inlined variable corresponds to one abstract variable.
1051   // FIXME: This duplication of variables when inlining should probably be
1052   // removed. It's done to allow each DIVariable to describe its location
1053   // because the DebugLoc on the dbg.value/declare isn't accurate. We should
1054   // make it accurate then remove this duplication/cleansing stuff.
1055   Cleansed = cleanseInlinedVariable(DV, Ctx);
1056   auto I = AbstractVariables.find(Cleansed);
1057   if (I != AbstractVariables.end())
1058     return I->second.get();
1059   return nullptr;
1060 }
1061
1062 DbgVariable *DwarfDebug::getExistingAbstractVariable(const DIVariable &DV) {
1063   DIVariable Cleansed;
1064   return getExistingAbstractVariable(DV, Cleansed);
1065 }
1066
1067 void DwarfDebug::createAbstractVariable(const DIVariable &Var,
1068                                         LexicalScope *Scope) {
1069   auto AbsDbgVariable = make_unique<DbgVariable>(Var, DIExpression(), this);
1070   addScopeVariable(Scope, AbsDbgVariable.get());
1071   AbstractVariables[Var] = std::move(AbsDbgVariable);
1072 }
1073
1074 void DwarfDebug::ensureAbstractVariableIsCreated(const DIVariable &DV,
1075                                                  const MDNode *ScopeNode) {
1076   DIVariable Cleansed = DV;
1077   if (getExistingAbstractVariable(DV, Cleansed))
1078     return;
1079
1080   createAbstractVariable(Cleansed, LScopes.getOrCreateAbstractScope(ScopeNode));
1081 }
1082
1083 void
1084 DwarfDebug::ensureAbstractVariableIsCreatedIfScoped(const DIVariable &DV,
1085                                                     const MDNode *ScopeNode) {
1086   DIVariable Cleansed = DV;
1087   if (getExistingAbstractVariable(DV, Cleansed))
1088     return;
1089
1090   if (LexicalScope *Scope = LScopes.findAbstractScope(ScopeNode))
1091     createAbstractVariable(Cleansed, Scope);
1092 }
1093
1094 // If Var is a current function argument then add it to CurrentFnArguments list.
1095 bool DwarfDebug::addCurrentFnArgument(DbgVariable *Var, LexicalScope *Scope) {
1096   if (!LScopes.isCurrentFunctionScope(Scope))
1097     return false;
1098   DIVariable DV = Var->getVariable();
1099   if (DV.getTag() != dwarf::DW_TAG_arg_variable)
1100     return false;
1101   unsigned ArgNo = DV.getArgNumber();
1102   if (ArgNo == 0)
1103     return false;
1104
1105   size_t Size = CurrentFnArguments.size();
1106   if (Size == 0)
1107     CurrentFnArguments.resize(CurFn->getFunction()->arg_size());
1108   // llvm::Function argument size is not good indicator of how many
1109   // arguments does the function have at source level.
1110   if (ArgNo > Size)
1111     CurrentFnArguments.resize(ArgNo * 2);
1112   assert(!CurrentFnArguments[ArgNo - 1]);
1113   CurrentFnArguments[ArgNo - 1] = Var;
1114   return true;
1115 }
1116
1117 // Collect variable information from side table maintained by MMI.
1118 void DwarfDebug::collectVariableInfoFromMMITable(
1119     SmallPtrSetImpl<const MDNode *> &Processed) {
1120   for (const auto &VI : MMI->getVariableDbgInfo()) {
1121     if (!VI.Var)
1122       continue;
1123     Processed.insert(VI.Var);
1124     DIVariable DV(VI.Var);
1125     DIExpression Expr(VI.Expr);
1126     LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc);
1127
1128     // If variable scope is not found then skip this variable.
1129     if (!Scope)
1130       continue;
1131
1132     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1133     ConcreteVariables.push_back(make_unique<DbgVariable>(DV, Expr, this));
1134     DbgVariable *RegVar = ConcreteVariables.back().get();
1135     RegVar->setFrameIndex(VI.Slot);
1136     addScopeVariable(Scope, RegVar);
1137   }
1138 }
1139
1140 // Get .debug_loc entry for the instruction range starting at MI.
1141 static DebugLocEntry::Value getDebugLocValue(const MachineInstr *MI) {
1142   const MDNode *Expr = MI->getDebugExpression();
1143   const MDNode *Var = MI->getDebugVariable();
1144
1145   assert(MI->getNumOperands() == 4);
1146   if (MI->getOperand(0).isReg()) {
1147     MachineLocation MLoc;
1148     // If the second operand is an immediate, this is a
1149     // register-indirect address.
1150     if (!MI->getOperand(1).isImm())
1151       MLoc.set(MI->getOperand(0).getReg());
1152     else
1153       MLoc.set(MI->getOperand(0).getReg(), MI->getOperand(1).getImm());
1154     return DebugLocEntry::Value(Var, Expr, MLoc);
1155   }
1156   if (MI->getOperand(0).isImm())
1157     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getImm());
1158   if (MI->getOperand(0).isFPImm())
1159     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getFPImm());
1160   if (MI->getOperand(0).isCImm())
1161     return DebugLocEntry::Value(Var, Expr, MI->getOperand(0).getCImm());
1162
1163   llvm_unreachable("Unexpected 4-operand DBG_VALUE instruction!");
1164 }
1165
1166 /// Determine whether two variable pieces overlap.
1167 static bool piecesOverlap(DIExpression P1, DIExpression P2) {
1168   if (!P1.isVariablePiece() || !P2.isVariablePiece())
1169     return true;
1170   unsigned l1 = P1.getPieceOffset();
1171   unsigned l2 = P2.getPieceOffset();
1172   unsigned r1 = l1 + P1.getPieceSize();
1173   unsigned r2 = l2 + P2.getPieceSize();
1174   // True where [l1,r1[ and [r1,r2[ overlap.
1175   return (l1 < r2) && (l2 < r1);
1176 }
1177
1178 /// Build the location list for all DBG_VALUEs in the function that
1179 /// describe the same variable.  If the ranges of several independent
1180 /// pieces of the same variable overlap partially, split them up and
1181 /// combine the ranges. The resulting DebugLocEntries are will have
1182 /// strict monotonically increasing begin addresses and will never
1183 /// overlap.
1184 //
1185 // Input:
1186 //
1187 //   Ranges History [var, loc, piece ofs size]
1188 // 0 |      [x, (reg0, piece 0, 32)]
1189 // 1 | |    [x, (reg1, piece 32, 32)] <- IsPieceOfPrevEntry
1190 // 2 | |    ...
1191 // 3   |    [clobber reg0]
1192 // 4        [x, (mem, piece 0, 64)] <- overlapping with both previous pieces of x.
1193 //
1194 // Output:
1195 //
1196 // [0-1]    [x, (reg0, piece  0, 32)]
1197 // [1-3]    [x, (reg0, piece  0, 32), (reg1, piece 32, 32)]
1198 // [3-4]    [x, (reg1, piece 32, 32)]
1199 // [4- ]    [x, (mem,  piece  0, 64)]
1200 void
1201 DwarfDebug::buildLocationList(SmallVectorImpl<DebugLocEntry> &DebugLoc,
1202                               const DbgValueHistoryMap::InstrRanges &Ranges) {
1203   SmallVector<DebugLocEntry::Value, 4> OpenRanges;
1204
1205   for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
1206     const MachineInstr *Begin = I->first;
1207     const MachineInstr *End = I->second;
1208     assert(Begin->isDebugValue() && "Invalid History entry");
1209
1210     // Check if a variable is inaccessible in this range.
1211     if (Begin->getNumOperands() > 1 &&
1212         Begin->getOperand(0).isReg() && !Begin->getOperand(0).getReg()) {
1213       OpenRanges.clear();
1214       continue;
1215     }
1216
1217     // If this piece overlaps with any open ranges, truncate them.
1218     DIExpression DIExpr = Begin->getDebugExpression();
1219     auto Last = std::remove_if(OpenRanges.begin(), OpenRanges.end(),
1220                                [&](DebugLocEntry::Value R) {
1221       return piecesOverlap(DIExpr, R.getExpression());
1222     });
1223     OpenRanges.erase(Last, OpenRanges.end());
1224
1225     const MCSymbol *StartLabel = getLabelBeforeInsn(Begin);
1226     assert(StartLabel && "Forgot label before DBG_VALUE starting a range!");
1227
1228     const MCSymbol *EndLabel;
1229     if (End != nullptr)
1230       EndLabel = getLabelAfterInsn(End);
1231     else if (std::next(I) == Ranges.end())
1232       EndLabel = FunctionEndSym;
1233     else
1234       EndLabel = getLabelBeforeInsn(std::next(I)->first);
1235     assert(EndLabel && "Forgot label after instruction ending a range!");
1236
1237     DEBUG(dbgs() << "DotDebugLoc: " << *Begin << "\n");
1238
1239     auto Value = getDebugLocValue(Begin);
1240     DebugLocEntry Loc(StartLabel, EndLabel, Value);
1241     bool couldMerge = false;
1242
1243     // If this is a piece, it may belong to the current DebugLocEntry.
1244     if (DIExpr.isVariablePiece()) {
1245       // Add this value to the list of open ranges.
1246       OpenRanges.push_back(Value);
1247
1248       // Attempt to add the piece to the last entry.
1249       if (!DebugLoc.empty())
1250         if (DebugLoc.back().MergeValues(Loc))
1251           couldMerge = true;
1252     }
1253
1254     if (!couldMerge) {
1255       // Need to add a new DebugLocEntry. Add all values from still
1256       // valid non-overlapping pieces.
1257       if (OpenRanges.size())
1258         Loc.addValues(OpenRanges);
1259
1260       DebugLoc.push_back(std::move(Loc));
1261     }
1262
1263     // Attempt to coalesce the ranges of two otherwise identical
1264     // DebugLocEntries.
1265     auto CurEntry = DebugLoc.rbegin();
1266     auto PrevEntry = std::next(CurEntry);
1267     if (PrevEntry != DebugLoc.rend() && PrevEntry->MergeRanges(*CurEntry))
1268       DebugLoc.pop_back();
1269
1270     DEBUG({
1271       dbgs() << CurEntry->getValues().size() << " Values:\n";
1272       for (auto Value : CurEntry->getValues()) {
1273         Value.getVariable()->dump();
1274         Value.getExpression()->dump();
1275       }
1276       dbgs() << "-----\n";
1277     });
1278   }
1279 }
1280
1281
1282 // Find variables for each lexical scope.
1283 void
1284 DwarfDebug::collectVariableInfo(SmallPtrSetImpl<const MDNode *> &Processed) {
1285   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1286   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1287
1288   // Grab the variable info that was squirreled away in the MMI side-table.
1289   collectVariableInfoFromMMITable(Processed);
1290
1291   for (const auto &I : DbgValues) {
1292     DIVariable DV(I.first);
1293     if (Processed.count(DV))
1294       continue;
1295
1296     // Instruction ranges, specifying where DV is accessible.
1297     const auto &Ranges = I.second;
1298     if (Ranges.empty())
1299       continue;
1300
1301     LexicalScope *Scope = nullptr;
1302     if (MDNode *IA = DV.getInlinedAt()) {
1303       DebugLoc DL = DebugLoc::getFromDILocation(IA);
1304       Scope = LScopes.findInlinedScope(DebugLoc::get(
1305           DL.getLine(), DL.getCol(), DV.getContext(), IA));
1306     } else
1307       Scope = LScopes.findLexicalScope(DV.getContext());
1308     // If variable scope is not found then skip this variable.
1309     if (!Scope)
1310       continue;
1311
1312     Processed.insert(DV);
1313     const MachineInstr *MInsn = Ranges.front().first;
1314     assert(MInsn->isDebugValue() && "History must begin with debug value");
1315     ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1316     ConcreteVariables.push_back(make_unique<DbgVariable>(MInsn, this));
1317     DbgVariable *RegVar = ConcreteVariables.back().get();
1318     addScopeVariable(Scope, RegVar);
1319
1320     // Check if the first DBG_VALUE is valid for the rest of the function.
1321     if (Ranges.size() == 1 && Ranges.front().second == nullptr)
1322       continue;
1323
1324     // Handle multiple DBG_VALUE instructions describing one variable.
1325     RegVar->setDotDebugLocOffset(DotDebugLocEntries.size());
1326
1327     DotDebugLocEntries.resize(DotDebugLocEntries.size() + 1);
1328     DebugLocList &LocList = DotDebugLocEntries.back();
1329     LocList.CU = TheCU;
1330     LocList.Label =
1331         Asm->GetTempSymbol("debug_loc", DotDebugLocEntries.size() - 1);
1332
1333     // Build the location list for this variable.
1334     buildLocationList(LocList.List, Ranges);
1335   }
1336
1337   // Collect info for variables that were optimized out.
1338   DIArray Variables = DISubprogram(FnScope->getScopeNode()).getVariables();
1339   for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1340     DIVariable DV(Variables.getElement(i));
1341     assert(DV.isVariable());
1342     if (!Processed.insert(DV))
1343       continue;
1344     if (LexicalScope *Scope = LScopes.findLexicalScope(DV.getContext())) {
1345       ensureAbstractVariableIsCreatedIfScoped(DV, Scope->getScopeNode());
1346       DIExpression NoExpr;
1347       ConcreteVariables.push_back(make_unique<DbgVariable>(DV, NoExpr, this));
1348       addScopeVariable(Scope, ConcreteVariables.back().get());
1349     }
1350   }
1351 }
1352
1353 // Return Label preceding the instruction.
1354 MCSymbol *DwarfDebug::getLabelBeforeInsn(const MachineInstr *MI) {
1355   MCSymbol *Label = LabelsBeforeInsn.lookup(MI);
1356   assert(Label && "Didn't insert label before instruction");
1357   return Label;
1358 }
1359
1360 // Return Label immediately following the instruction.
1361 MCSymbol *DwarfDebug::getLabelAfterInsn(const MachineInstr *MI) {
1362   return LabelsAfterInsn.lookup(MI);
1363 }
1364
1365 // Process beginning of an instruction.
1366 void DwarfDebug::beginInstruction(const MachineInstr *MI) {
1367   assert(CurMI == nullptr);
1368   CurMI = MI;
1369   // Check if source location changes, but ignore DBG_VALUE locations.
1370   if (!MI->isDebugValue()) {
1371     DebugLoc DL = MI->getDebugLoc();
1372     if (DL != PrevInstLoc && (!DL.isUnknown() || UnknownLocations)) {
1373       unsigned Flags = 0;
1374       PrevInstLoc = DL;
1375       if (DL == PrologEndLoc) {
1376         Flags |= DWARF2_FLAG_PROLOGUE_END;
1377         PrologEndLoc = DebugLoc();
1378       }
1379       if (PrologEndLoc.isUnknown())
1380         Flags |= DWARF2_FLAG_IS_STMT;
1381
1382       if (!DL.isUnknown()) {
1383         const MDNode *Scope = DL.getScope(Asm->MF->getFunction()->getContext());
1384         recordSourceLine(DL.getLine(), DL.getCol(), Scope, Flags);
1385       } else
1386         recordSourceLine(0, 0, nullptr, 0);
1387     }
1388   }
1389
1390   // Insert labels where requested.
1391   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1392       LabelsBeforeInsn.find(MI);
1393
1394   // No label needed.
1395   if (I == LabelsBeforeInsn.end())
1396     return;
1397
1398   // Label already assigned.
1399   if (I->second)
1400     return;
1401
1402   if (!PrevLabel) {
1403     PrevLabel = MMI->getContext().CreateTempSymbol();
1404     Asm->OutStreamer.EmitLabel(PrevLabel);
1405   }
1406   I->second = PrevLabel;
1407 }
1408
1409 // Process end of an instruction.
1410 void DwarfDebug::endInstruction() {
1411   assert(CurMI != nullptr);
1412   // Don't create a new label after DBG_VALUE instructions.
1413   // They don't generate code.
1414   if (!CurMI->isDebugValue())
1415     PrevLabel = nullptr;
1416
1417   DenseMap<const MachineInstr *, MCSymbol *>::iterator I =
1418       LabelsAfterInsn.find(CurMI);
1419   CurMI = nullptr;
1420
1421   // No label needed.
1422   if (I == LabelsAfterInsn.end())
1423     return;
1424
1425   // Label already assigned.
1426   if (I->second)
1427     return;
1428
1429   // We need a label after this instruction.
1430   if (!PrevLabel) {
1431     PrevLabel = MMI->getContext().CreateTempSymbol();
1432     Asm->OutStreamer.EmitLabel(PrevLabel);
1433   }
1434   I->second = PrevLabel;
1435 }
1436
1437 // Each LexicalScope has first instruction and last instruction to mark
1438 // beginning and end of a scope respectively. Create an inverse map that list
1439 // scopes starts (and ends) with an instruction. One instruction may start (or
1440 // end) multiple scopes. Ignore scopes that are not reachable.
1441 void DwarfDebug::identifyScopeMarkers() {
1442   SmallVector<LexicalScope *, 4> WorkList;
1443   WorkList.push_back(LScopes.getCurrentFunctionScope());
1444   while (!WorkList.empty()) {
1445     LexicalScope *S = WorkList.pop_back_val();
1446
1447     const SmallVectorImpl<LexicalScope *> &Children = S->getChildren();
1448     if (!Children.empty())
1449       WorkList.append(Children.begin(), Children.end());
1450
1451     if (S->isAbstractScope())
1452       continue;
1453
1454     for (const InsnRange &R : S->getRanges()) {
1455       assert(R.first && "InsnRange does not have first instruction!");
1456       assert(R.second && "InsnRange does not have second instruction!");
1457       requestLabelBeforeInsn(R.first);
1458       requestLabelAfterInsn(R.second);
1459     }
1460   }
1461 }
1462
1463 static DebugLoc findPrologueEndLoc(const MachineFunction *MF) {
1464   // First known non-DBG_VALUE and non-frame setup location marks
1465   // the beginning of the function body.
1466   for (const auto &MBB : *MF)
1467     for (const auto &MI : MBB)
1468       if (!MI.isDebugValue() && !MI.getFlag(MachineInstr::FrameSetup) &&
1469           !MI.getDebugLoc().isUnknown())
1470         return MI.getDebugLoc();
1471   return DebugLoc();
1472 }
1473
1474 // Gather pre-function debug information.  Assumes being called immediately
1475 // after the function entry point has been emitted.
1476 void DwarfDebug::beginFunction(const MachineFunction *MF) {
1477   CurFn = MF;
1478
1479   // If there's no debug info for the function we're not going to do anything.
1480   if (!MMI->hasDebugInfo())
1481     return;
1482
1483   auto DI = FunctionDIs.find(MF->getFunction());
1484   if (DI == FunctionDIs.end())
1485     return;
1486
1487   // Grab the lexical scopes for the function, if we don't have any of those
1488   // then we're not going to be able to do anything.
1489   LScopes.initialize(*MF);
1490   if (LScopes.empty())
1491     return;
1492
1493   assert(DbgValues.empty() && "DbgValues map wasn't cleaned!");
1494
1495   // Make sure that each lexical scope will have a begin/end label.
1496   identifyScopeMarkers();
1497
1498   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1499   // belongs to so that we add to the correct per-cu line table in the
1500   // non-asm case.
1501   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1502   // FnScope->getScopeNode() and DI->second should represent the same function,
1503   // though they may not be the same MDNode due to inline functions merged in
1504   // LTO where the debug info metadata still differs (either due to distinct
1505   // written differences - two versions of a linkonce_odr function
1506   // written/copied into two separate files, or some sub-optimal metadata that
1507   // isn't structurally identical (see: file path/name info from clang, which
1508   // includes the directory of the cpp file being built, even when the file name
1509   // is absolute (such as an <> lookup header)))
1510   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1511   assert(TheCU && "Unable to find compile unit!");
1512   if (Asm->OutStreamer.hasRawTextSupport())
1513     // Use a single line table if we are generating assembly.
1514     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1515   else
1516     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1517
1518   // Emit a label for the function so that we have a beginning address.
1519   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1520   // Assumes in correct section after the entry point.
1521   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1522
1523   // Calculate history for local variables.
1524   calculateDbgValueHistory(MF, Asm->TM.getSubtargetImpl()->getRegisterInfo(),
1525                            DbgValues);
1526
1527   // Request labels for the full history.
1528   for (const auto &I : DbgValues) {
1529     const auto &Ranges = I.second;
1530     if (Ranges.empty())
1531       continue;
1532
1533     // The first mention of a function argument gets the FunctionBeginSym
1534     // label, so arguments are visible when breaking at function entry.
1535     DIVariable DIVar(Ranges.front().first->getDebugVariable());
1536     if (DIVar.isVariable() && DIVar.getTag() == dwarf::DW_TAG_arg_variable &&
1537         getDISubprogram(DIVar.getContext()).describes(MF->getFunction())) {
1538       LabelsBeforeInsn[Ranges.front().first] = FunctionBeginSym;
1539       if (Ranges.front().first->getDebugExpression().isVariablePiece()) {
1540         // Mark all non-overlapping initial pieces.
1541         for (auto I = Ranges.begin(); I != Ranges.end(); ++I) {
1542           DIExpression Piece = I->first->getDebugExpression();
1543           if (std::all_of(Ranges.begin(), I,
1544                           [&](DbgValueHistoryMap::InstrRange Pred) {
1545                 return !piecesOverlap(Piece, Pred.first->getDebugExpression());
1546               }))
1547             LabelsBeforeInsn[I->first] = FunctionBeginSym;
1548           else
1549             break;
1550         }
1551       }
1552     }
1553
1554     for (const auto &Range : Ranges) {
1555       requestLabelBeforeInsn(Range.first);
1556       if (Range.second)
1557         requestLabelAfterInsn(Range.second);
1558     }
1559   }
1560
1561   PrevInstLoc = DebugLoc();
1562   PrevLabel = FunctionBeginSym;
1563
1564   // Record beginning of function.
1565   PrologEndLoc = findPrologueEndLoc(MF);
1566   if (!PrologEndLoc.isUnknown()) {
1567     DebugLoc FnStartDL =
1568         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1569     recordSourceLine(
1570         FnStartDL.getLine(), FnStartDL.getCol(),
1571         FnStartDL.getScope(MF->getFunction()->getContext()),
1572         // We'd like to list the prologue as "not statements" but GDB behaves
1573         // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1574         DWARF2_FLAG_IS_STMT);
1575   }
1576 }
1577
1578 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1579   if (addCurrentFnArgument(Var, LS))
1580     return;
1581   SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1582   DIVariable DV = Var->getVariable();
1583   // Variables with positive arg numbers are parameters.
1584   if (unsigned ArgNum = DV.getArgNumber()) {
1585     // Keep all parameters in order at the start of the variable list to ensure
1586     // function types are correct (no out-of-order parameters)
1587     //
1588     // This could be improved by only doing it for optimized builds (unoptimized
1589     // builds have the right order to begin with), searching from the back (this
1590     // would catch the unoptimized case quickly), or doing a binary search
1591     // rather than linear search.
1592     SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1593     while (I != Vars.end()) {
1594       unsigned CurNum = (*I)->getVariable().getArgNumber();
1595       // A local (non-parameter) variable has been found, insert immediately
1596       // before it.
1597       if (CurNum == 0)
1598         break;
1599       // A later indexed parameter has been found, insert immediately before it.
1600       if (CurNum > ArgNum)
1601         break;
1602       ++I;
1603     }
1604     Vars.insert(I, Var);
1605     return;
1606   }
1607
1608   Vars.push_back(Var);
1609 }
1610
1611 // Gather and emit post-function debug information.
1612 void DwarfDebug::endFunction(const MachineFunction *MF) {
1613   // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1614   // though the beginFunction may not be called at all.
1615   // We should handle both cases.
1616   if (!CurFn)
1617     CurFn = MF;
1618   else
1619     assert(CurFn == MF);
1620   assert(CurFn != nullptr);
1621
1622   if (!MMI->hasDebugInfo() || LScopes.empty() ||
1623       !FunctionDIs.count(MF->getFunction())) {
1624     // If we don't have a lexical scope for this function then there will
1625     // be a hole in the range information. Keep note of this by setting the
1626     // previously used section to nullptr.
1627     PrevCU = nullptr;
1628     CurFn = nullptr;
1629     return;
1630   }
1631
1632   // Define end label for subprogram.
1633   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1634   // Assumes in correct section after the entry point.
1635   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1636
1637   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1638   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1639
1640   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1641   collectVariableInfo(ProcessedVars);
1642
1643   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1644   DwarfCompileUnit &TheCU = *SPMap.lookup(FnScope->getScopeNode());
1645
1646   // Add the range of this function to the list of ranges for the CU.
1647   TheCU.addRange(RangeSpan(FunctionBeginSym, FunctionEndSym));
1648
1649   // Under -gmlt, skip building the subprogram if there are no inlined
1650   // subroutines inside it.
1651   if (TheCU.getCUNode().getEmissionKind() == DIBuilder::LineTablesOnly &&
1652       LScopes.getAbstractScopesList().empty() && !IsDarwin) {
1653     assert(ScopeVariables.empty());
1654     assert(CurrentFnArguments.empty());
1655     assert(DbgValues.empty());
1656     assert(AbstractVariables.empty());
1657     LabelsBeforeInsn.clear();
1658     LabelsAfterInsn.clear();
1659     PrevLabel = nullptr;
1660     CurFn = nullptr;
1661     return;
1662   }
1663
1664   // Construct abstract scopes.
1665   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1666     DISubprogram SP(AScope->getScopeNode());
1667     assert(SP.isSubprogram());
1668     // Collect info for variables that were optimized out.
1669     DIArray Variables = SP.getVariables();
1670     for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1671       DIVariable DV(Variables.getElement(i));
1672       assert(DV && DV.isVariable());
1673       if (!ProcessedVars.insert(DV))
1674         continue;
1675       ensureAbstractVariableIsCreated(DV, DV.getContext());
1676     }
1677     constructAbstractSubprogramScopeDIE(TheCU, AScope);
1678   }
1679
1680   constructSubprogramScopeDIE(TheCU, FnScope);
1681
1682   // Clear debug info
1683   // Ownership of DbgVariables is a bit subtle - ScopeVariables owns all the
1684   // DbgVariables except those that are also in AbstractVariables (since they
1685   // can be used cross-function)
1686   ScopeVariables.clear();
1687   CurrentFnArguments.clear();
1688   DbgValues.clear();
1689   LabelsBeforeInsn.clear();
1690   LabelsAfterInsn.clear();
1691   PrevLabel = nullptr;
1692   CurFn = nullptr;
1693 }
1694
1695 // Register a source line with debug info. Returns the  unique label that was
1696 // emitted and which provides correspondence to the source line list.
1697 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1698                                   unsigned Flags) {
1699   StringRef Fn;
1700   StringRef Dir;
1701   unsigned Src = 1;
1702   unsigned Discriminator = 0;
1703   if (DIScope Scope = DIScope(S)) {
1704     assert(Scope.isScope());
1705     Fn = Scope.getFilename();
1706     Dir = Scope.getDirectory();
1707     if (Scope.isLexicalBlockFile())
1708       Discriminator = DILexicalBlockFile(S).getDiscriminator();
1709
1710     unsigned CUID = Asm->OutStreamer.getContext().getDwarfCompileUnitID();
1711     Src = static_cast<DwarfCompileUnit &>(*InfoHolder.getUnits()[CUID])
1712               .getOrCreateSourceID(Fn, Dir);
1713   }
1714   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1715                                          Discriminator, Fn);
1716 }
1717
1718 //===----------------------------------------------------------------------===//
1719 // Emit Methods
1720 //===----------------------------------------------------------------------===//
1721
1722 // Emit initial Dwarf sections with a label at the start of each one.
1723 void DwarfDebug::emitSectionLabels() {
1724   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1725
1726   // Dwarf sections base addresses.
1727   DwarfInfoSectionSym =
1728       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1729   if (useSplitDwarf()) {
1730     DwarfInfoDWOSectionSym =
1731         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1732     DwarfTypesDWOSectionSym =
1733         emitSectionSym(Asm, TLOF.getDwarfTypesDWOSection(), "section_types_dwo");
1734   }
1735   DwarfAbbrevSectionSym =
1736       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1737   if (useSplitDwarf())
1738     DwarfAbbrevDWOSectionSym = emitSectionSym(
1739         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1740   if (GenerateARangeSection)
1741     emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1742
1743   DwarfLineSectionSym =
1744       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1745   if (GenerateGnuPubSections) {
1746     DwarfGnuPubNamesSectionSym =
1747         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1748     DwarfGnuPubTypesSectionSym =
1749         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1750   } else if (HasDwarfPubSections) {
1751     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1752     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1753   }
1754
1755   DwarfStrSectionSym =
1756       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1757   if (useSplitDwarf()) {
1758     DwarfStrDWOSectionSym =
1759         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1760     DwarfAddrSectionSym =
1761         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1762     DwarfDebugLocSectionSym =
1763         emitSectionSym(Asm, TLOF.getDwarfLocDWOSection(), "skel_loc");
1764   } else
1765     DwarfDebugLocSectionSym =
1766         emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1767   DwarfDebugRangeSectionSym =
1768       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1769 }
1770
1771 // Recursively emits a debug information entry.
1772 void DwarfDebug::emitDIE(DIE &Die) {
1773   // Get the abbreviation for this DIE.
1774   const DIEAbbrev &Abbrev = Die.getAbbrev();
1775
1776   // Emit the code (index) for the abbreviation.
1777   if (Asm->isVerbose())
1778     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1779                                 "] 0x" + Twine::utohexstr(Die.getOffset()) +
1780                                 ":0x" + Twine::utohexstr(Die.getSize()) + " " +
1781                                 dwarf::TagString(Abbrev.getTag()));
1782   Asm->EmitULEB128(Abbrev.getNumber());
1783
1784   const SmallVectorImpl<DIEValue *> &Values = Die.getValues();
1785   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1786
1787   // Emit the DIE attribute values.
1788   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1789     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1790     dwarf::Form Form = AbbrevData[i].getForm();
1791     assert(Form && "Too many attributes for DIE (check abbreviation)");
1792
1793     if (Asm->isVerbose()) {
1794       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1795       if (Attr == dwarf::DW_AT_accessibility)
1796         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1797             cast<DIEInteger>(Values[i])->getValue()));
1798     }
1799
1800     // Emit an attribute using the defined form.
1801     Values[i]->EmitValue(Asm, Form);
1802   }
1803
1804   // Emit the DIE children if any.
1805   if (Abbrev.hasChildren()) {
1806     for (auto &Child : Die.getChildren())
1807       emitDIE(*Child);
1808
1809     Asm->OutStreamer.AddComment("End Of Children Mark");
1810     Asm->EmitInt8(0);
1811   }
1812 }
1813
1814 // Emit the debug info section.
1815 void DwarfDebug::emitDebugInfo() {
1816   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1817
1818   Holder.emitUnits(this, DwarfAbbrevSectionSym);
1819 }
1820
1821 // Emit the abbreviation section.
1822 void DwarfDebug::emitAbbreviations() {
1823   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1824
1825   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1826 }
1827
1828 // Emit the last address of the section and the end of the line matrix.
1829 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
1830   // Define last address of section.
1831   Asm->OutStreamer.AddComment("Extended Op");
1832   Asm->EmitInt8(0);
1833
1834   Asm->OutStreamer.AddComment("Op size");
1835   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
1836   Asm->OutStreamer.AddComment("DW_LNE_set_address");
1837   Asm->EmitInt8(dwarf::DW_LNE_set_address);
1838
1839   Asm->OutStreamer.AddComment("Section end label");
1840
1841   Asm->OutStreamer.EmitSymbolValue(
1842       Asm->GetTempSymbol("section_end", SectionEnd),
1843       Asm->getDataLayout().getPointerSize());
1844
1845   // Mark end of matrix.
1846   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
1847   Asm->EmitInt8(0);
1848   Asm->EmitInt8(1);
1849   Asm->EmitInt8(1);
1850 }
1851
1852 void DwarfDebug::emitAccel(DwarfAccelTable &Accel, const MCSection *Section,
1853                            StringRef TableName, StringRef SymName) {
1854   Accel.FinalizeTable(Asm, TableName);
1855   Asm->OutStreamer.SwitchSection(Section);
1856   auto *SectionBegin = Asm->GetTempSymbol(SymName);
1857   Asm->OutStreamer.EmitLabel(SectionBegin);
1858
1859   // Emit the full data.
1860   Accel.Emit(Asm, SectionBegin, &InfoHolder, DwarfStrSectionSym);
1861 }
1862
1863 // Emit visible names into a hashed accelerator table section.
1864 void DwarfDebug::emitAccelNames() {
1865   emitAccel(AccelNames, Asm->getObjFileLowering().getDwarfAccelNamesSection(),
1866             "Names", "names_begin");
1867 }
1868
1869 // Emit objective C classes and categories into a hashed accelerator table
1870 // section.
1871 void DwarfDebug::emitAccelObjC() {
1872   emitAccel(AccelObjC, Asm->getObjFileLowering().getDwarfAccelObjCSection(),
1873             "ObjC", "objc_begin");
1874 }
1875
1876 // Emit namespace dies into a hashed accelerator table.
1877 void DwarfDebug::emitAccelNamespaces() {
1878   emitAccel(AccelNamespace,
1879             Asm->getObjFileLowering().getDwarfAccelNamespaceSection(),
1880             "namespac", "namespac_begin");
1881 }
1882
1883 // Emit type dies into a hashed accelerator table.
1884 void DwarfDebug::emitAccelTypes() {
1885   emitAccel(AccelTypes, Asm->getObjFileLowering().getDwarfAccelTypesSection(),
1886             "types", "types_begin");
1887 }
1888
1889 // Public name handling.
1890 // The format for the various pubnames:
1891 //
1892 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
1893 // for the DIE that is named.
1894 //
1895 // gnu pubnames - offset/index value/name tuples where the offset is the offset
1896 // into the CU and the index value is computed according to the type of value
1897 // for the DIE that is named.
1898 //
1899 // For type units the offset is the offset of the skeleton DIE. For split dwarf
1900 // it's the offset within the debug_info/debug_types dwo section, however, the
1901 // reference in the pubname header doesn't change.
1902
1903 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
1904 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
1905                                                         const DIE *Die) {
1906   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
1907
1908   // We could have a specification DIE that has our most of our knowledge,
1909   // look for that now.
1910   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
1911   if (SpecVal) {
1912     DIE &SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
1913     if (SpecDIE.findAttribute(dwarf::DW_AT_external))
1914       Linkage = dwarf::GIEL_EXTERNAL;
1915   } else if (Die->findAttribute(dwarf::DW_AT_external))
1916     Linkage = dwarf::GIEL_EXTERNAL;
1917
1918   switch (Die->getTag()) {
1919   case dwarf::DW_TAG_class_type:
1920   case dwarf::DW_TAG_structure_type:
1921   case dwarf::DW_TAG_union_type:
1922   case dwarf::DW_TAG_enumeration_type:
1923     return dwarf::PubIndexEntryDescriptor(
1924         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
1925                               ? dwarf::GIEL_STATIC
1926                               : dwarf::GIEL_EXTERNAL);
1927   case dwarf::DW_TAG_typedef:
1928   case dwarf::DW_TAG_base_type:
1929   case dwarf::DW_TAG_subrange_type:
1930     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
1931   case dwarf::DW_TAG_namespace:
1932     return dwarf::GIEK_TYPE;
1933   case dwarf::DW_TAG_subprogram:
1934     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
1935   case dwarf::DW_TAG_constant:
1936   case dwarf::DW_TAG_variable:
1937     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
1938   case dwarf::DW_TAG_enumerator:
1939     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
1940                                           dwarf::GIEL_STATIC);
1941   default:
1942     return dwarf::GIEK_NONE;
1943   }
1944 }
1945
1946 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
1947 ///
1948 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
1949   const MCSection *PSec =
1950       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
1951                : Asm->getObjFileLowering().getDwarfPubNamesSection();
1952
1953   emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
1954 }
1955
1956 void DwarfDebug::emitDebugPubSection(
1957     bool GnuStyle, const MCSection *PSec, StringRef Name,
1958     const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
1959   for (const auto &NU : CUMap) {
1960     DwarfCompileUnit *TheU = NU.second;
1961
1962     const auto &Globals = (TheU->*Accessor)();
1963
1964     if (Globals.empty())
1965       continue;
1966
1967     if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
1968       TheU = Skeleton;
1969     unsigned ID = TheU->getUniqueID();
1970
1971     // Start the dwarf pubnames section.
1972     Asm->OutStreamer.SwitchSection(PSec);
1973
1974     // Emit the header.
1975     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
1976     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
1977     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
1978     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
1979
1980     Asm->OutStreamer.EmitLabel(BeginLabel);
1981
1982     Asm->OutStreamer.AddComment("DWARF Version");
1983     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
1984
1985     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
1986     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
1987
1988     Asm->OutStreamer.AddComment("Compilation Unit Length");
1989     Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
1990
1991     // Emit the pubnames for this compilation unit.
1992     for (const auto &GI : Globals) {
1993       const char *Name = GI.getKeyData();
1994       const DIE *Entity = GI.second;
1995
1996       Asm->OutStreamer.AddComment("DIE offset");
1997       Asm->EmitInt32(Entity->getOffset());
1998
1999       if (GnuStyle) {
2000         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2001         Asm->OutStreamer.AddComment(
2002             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2003             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2004         Asm->EmitInt8(Desc.toBits());
2005       }
2006
2007       Asm->OutStreamer.AddComment("External Name");
2008       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2009     }
2010
2011     Asm->OutStreamer.AddComment("End Mark");
2012     Asm->EmitInt32(0);
2013     Asm->OutStreamer.EmitLabel(EndLabel);
2014   }
2015 }
2016
2017 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2018   const MCSection *PSec =
2019       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2020                : Asm->getObjFileLowering().getDwarfPubTypesSection();
2021
2022   emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2023 }
2024
2025 // Emit visible names into a debug str section.
2026 void DwarfDebug::emitDebugStr() {
2027   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2028   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2029 }
2030
2031 /// Emits an optimal (=sorted) sequence of DW_OP_pieces.
2032 void DwarfDebug::emitLocPieces(ByteStreamer &Streamer,
2033                                const DITypeIdentifierMap &Map,
2034                                ArrayRef<DebugLocEntry::Value> Values) {
2035   assert(std::all_of(Values.begin(), Values.end(), [](DebugLocEntry::Value P) {
2036         return P.isVariablePiece();
2037       }) && "all values are expected to be pieces");
2038   assert(std::is_sorted(Values.begin(), Values.end()) &&
2039          "pieces are expected to be sorted");
2040
2041   unsigned Offset = 0;
2042   for (auto Piece : Values) {
2043     DIExpression Expr = Piece.getExpression();
2044     unsigned PieceOffset = Expr.getPieceOffset();
2045     unsigned PieceSize = Expr.getPieceSize();
2046     assert(Offset <= PieceOffset && "overlapping or duplicate pieces");
2047     if (Offset < PieceOffset) {
2048       // The DWARF spec seriously mandates pieces with no locations for gaps.
2049       Asm->EmitDwarfOpPiece(Streamer, (PieceOffset-Offset)*8);
2050       Offset += PieceOffset-Offset;
2051     }
2052
2053     Offset += PieceSize;
2054
2055     const unsigned SizeOfByte = 8;
2056 #ifndef NDEBUG
2057     DIVariable Var = Piece.getVariable();
2058     assert(!Var.isIndirect() && "indirect address for piece");
2059     unsigned VarSize = Var.getSizeInBits(Map);
2060     assert(PieceSize+PieceOffset <= VarSize/SizeOfByte
2061            && "piece is larger than or outside of variable");
2062     assert(PieceSize*SizeOfByte != VarSize
2063            && "piece covers entire variable");
2064 #endif
2065     if (Piece.isLocation() && Piece.getLoc().isReg())
2066       Asm->EmitDwarfRegOpPiece(Streamer,
2067                                Piece.getLoc(),
2068                                PieceSize*SizeOfByte);
2069     else {
2070       emitDebugLocValue(Streamer, Piece);
2071       Asm->EmitDwarfOpPiece(Streamer, PieceSize*SizeOfByte);
2072     }
2073   }
2074 }
2075
2076
2077 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2078                                    const DebugLocEntry &Entry) {
2079   const DebugLocEntry::Value Value = Entry.getValues()[0];
2080   if (Value.isVariablePiece())
2081     // Emit all pieces that belong to the same variable and range.
2082     return emitLocPieces(Streamer, TypeIdentifierMap, Entry.getValues());
2083
2084   assert(Entry.getValues().size() == 1 && "only pieces may have >1 value");
2085   emitDebugLocValue(Streamer, Value);
2086 }
2087
2088 void DwarfDebug::emitDebugLocValue(ByteStreamer &Streamer,
2089                                    const DebugLocEntry::Value &Value) {
2090   DIVariable DV = Value.getVariable();
2091   // Regular entry.
2092   if (Value.isInt()) {
2093     DIBasicType BTy(resolve(DV.getType()));
2094     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2095                          BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2096       Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2097       Streamer.EmitSLEB128(Value.getInt());
2098     } else {
2099       Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2100       Streamer.EmitULEB128(Value.getInt());
2101     }
2102   } else if (Value.isLocation()) {
2103     MachineLocation Loc = Value.getLoc();
2104     DIExpression Expr = Value.getExpression();
2105     if (!Expr)
2106       // Regular entry.
2107       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2108     else {
2109       // Complex address entry.
2110       unsigned N = Expr.getNumElements();
2111       unsigned i = 0;
2112       if (N >= 2 && Expr.getElement(0) == dwarf::DW_OP_plus) {
2113         if (Loc.getOffset()) {
2114           i = 2;
2115           Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2116           Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2117           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2118           Streamer.EmitSLEB128(Expr.getElement(1));
2119         } else {
2120           // If first address element is OpPlus then emit
2121           // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2122           MachineLocation TLoc(Loc.getReg(), Expr.getElement(1));
2123           Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2124           i = 2;
2125         }
2126       } else {
2127         Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2128       }
2129
2130       // Emit remaining complex address elements.
2131       for (; i < N; ++i) {
2132         uint64_t Element = Expr.getElement(i);
2133         if (Element == dwarf::DW_OP_plus) {
2134           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2135           Streamer.EmitULEB128(Expr.getElement(++i));
2136         } else if (Element == dwarf::DW_OP_deref) {
2137           if (!Loc.isReg())
2138             Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2139         } else if (Element == dwarf::DW_OP_piece) {
2140           i += 3;
2141           // handled in emitDebugLocEntry.
2142         } else
2143           llvm_unreachable("unknown Opcode found in complex address");
2144       }
2145     }
2146   }
2147   // else ... ignore constant fp. There is not any good way to
2148   // to represent them here in dwarf.
2149   // FIXME: ^
2150 }
2151
2152 void DwarfDebug::emitDebugLocEntryLocation(const DebugLocEntry &Entry) {
2153   Asm->OutStreamer.AddComment("Loc expr size");
2154   MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2155   MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2156   Asm->EmitLabelDifference(end, begin, 2);
2157   Asm->OutStreamer.EmitLabel(begin);
2158   // Emit the entry.
2159   APByteStreamer Streamer(*Asm);
2160   emitDebugLocEntry(Streamer, Entry);
2161   // Close the range.
2162   Asm->OutStreamer.EmitLabel(end);
2163 }
2164
2165 // Emit locations into the debug loc section.
2166 void DwarfDebug::emitDebugLoc() {
2167   // Start the dwarf loc section.
2168   Asm->OutStreamer.SwitchSection(
2169       Asm->getObjFileLowering().getDwarfLocSection());
2170   unsigned char Size = Asm->getDataLayout().getPointerSize();
2171   for (const auto &DebugLoc : DotDebugLocEntries) {
2172     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2173     const DwarfCompileUnit *CU = DebugLoc.CU;
2174     assert(!CU->getRanges().empty());
2175     for (const auto &Entry : DebugLoc.List) {
2176       // Set up the range. This range is relative to the entry point of the
2177       // compile unit. This is a hard coded 0 for low_pc when we're emitting
2178       // ranges, or the DW_AT_low_pc on the compile unit otherwise.
2179       if (CU->getRanges().size() == 1) {
2180         // Grab the begin symbol from the first range as our base.
2181         const MCSymbol *Base = CU->getRanges()[0].getStart();
2182         Asm->EmitLabelDifference(Entry.getBeginSym(), Base, Size);
2183         Asm->EmitLabelDifference(Entry.getEndSym(), Base, Size);
2184       } else {
2185         Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2186         Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2187       }
2188
2189       emitDebugLocEntryLocation(Entry);
2190     }
2191     Asm->OutStreamer.EmitIntValue(0, Size);
2192     Asm->OutStreamer.EmitIntValue(0, Size);
2193   }
2194 }
2195
2196 void DwarfDebug::emitDebugLocDWO() {
2197   Asm->OutStreamer.SwitchSection(
2198       Asm->getObjFileLowering().getDwarfLocDWOSection());
2199   for (const auto &DebugLoc : DotDebugLocEntries) {
2200     Asm->OutStreamer.EmitLabel(DebugLoc.Label);
2201     for (const auto &Entry : DebugLoc.List) {
2202       // Just always use start_length for now - at least that's one address
2203       // rather than two. We could get fancier and try to, say, reuse an
2204       // address we know we've emitted elsewhere (the start of the function?
2205       // The start of the CU or CU subrange that encloses this range?)
2206       Asm->EmitInt8(dwarf::DW_LLE_start_length_entry);
2207       unsigned idx = AddrPool.getIndex(Entry.getBeginSym());
2208       Asm->EmitULEB128(idx);
2209       Asm->EmitLabelDifference(Entry.getEndSym(), Entry.getBeginSym(), 4);
2210
2211       emitDebugLocEntryLocation(Entry);
2212     }
2213     Asm->EmitInt8(dwarf::DW_LLE_end_of_list_entry);
2214   }
2215 }
2216
2217 struct ArangeSpan {
2218   const MCSymbol *Start, *End;
2219 };
2220
2221 // Emit a debug aranges section, containing a CU lookup for any
2222 // address we can tie back to a CU.
2223 void DwarfDebug::emitDebugARanges() {
2224   // Start the dwarf aranges section.
2225   Asm->OutStreamer.SwitchSection(
2226       Asm->getObjFileLowering().getDwarfARangesSection());
2227
2228   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan>> SpansType;
2229
2230   SpansType Spans;
2231
2232   // Build a list of sections used.
2233   std::vector<const MCSection *> Sections;
2234   for (const auto &it : SectionMap) {
2235     const MCSection *Section = it.first;
2236     Sections.push_back(Section);
2237   }
2238
2239   // Sort the sections into order.
2240   // This is only done to ensure consistent output order across different runs.
2241   std::sort(Sections.begin(), Sections.end(), SectionSort);
2242
2243   // Build a set of address spans, sorted by CU.
2244   for (const MCSection *Section : Sections) {
2245     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2246     if (List.size() < 2)
2247       continue;
2248
2249     // Sort the symbols by offset within the section.
2250     std::sort(List.begin(), List.end(),
2251               [&](const SymbolCU &A, const SymbolCU &B) {
2252       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2253       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2254
2255       // Symbols with no order assigned should be placed at the end.
2256       // (e.g. section end labels)
2257       if (IA == 0)
2258         return false;
2259       if (IB == 0)
2260         return true;
2261       return IA < IB;
2262     });
2263
2264     // If we have no section (e.g. common), just write out
2265     // individual spans for each symbol.
2266     if (!Section) {
2267       for (const SymbolCU &Cur : List) {
2268         ArangeSpan Span;
2269         Span.Start = Cur.Sym;
2270         Span.End = nullptr;
2271         if (Cur.CU)
2272           Spans[Cur.CU].push_back(Span);
2273       }
2274     } else {
2275       // Build spans between each label.
2276       const MCSymbol *StartSym = List[0].Sym;
2277       for (size_t n = 1, e = List.size(); n < e; n++) {
2278         const SymbolCU &Prev = List[n - 1];
2279         const SymbolCU &Cur = List[n];
2280
2281         // Try and build the longest span we can within the same CU.
2282         if (Cur.CU != Prev.CU) {
2283           ArangeSpan Span;
2284           Span.Start = StartSym;
2285           Span.End = Cur.Sym;
2286           Spans[Prev.CU].push_back(Span);
2287           StartSym = Cur.Sym;
2288         }
2289       }
2290     }
2291   }
2292
2293   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2294
2295   // Build a list of CUs used.
2296   std::vector<DwarfCompileUnit *> CUs;
2297   for (const auto &it : Spans) {
2298     DwarfCompileUnit *CU = it.first;
2299     CUs.push_back(CU);
2300   }
2301
2302   // Sort the CU list (again, to ensure consistent output order).
2303   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2304     return A->getUniqueID() < B->getUniqueID();
2305   });
2306
2307   // Emit an arange table for each CU we used.
2308   for (DwarfCompileUnit *CU : CUs) {
2309     std::vector<ArangeSpan> &List = Spans[CU];
2310
2311     // Emit size of content not including length itself.
2312     unsigned ContentSize =
2313         sizeof(int16_t) + // DWARF ARange version number
2314         sizeof(int32_t) + // Offset of CU in the .debug_info section
2315         sizeof(int8_t) +  // Pointer Size (in bytes)
2316         sizeof(int8_t);   // Segment Size (in bytes)
2317
2318     unsigned TupleSize = PtrSize * 2;
2319
2320     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2321     unsigned Padding =
2322         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2323
2324     ContentSize += Padding;
2325     ContentSize += (List.size() + 1) * TupleSize;
2326
2327     // For each compile unit, write the list of spans it covers.
2328     Asm->OutStreamer.AddComment("Length of ARange Set");
2329     Asm->EmitInt32(ContentSize);
2330     Asm->OutStreamer.AddComment("DWARF Arange version number");
2331     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2332     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2333     Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2334     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2335     Asm->EmitInt8(PtrSize);
2336     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2337     Asm->EmitInt8(0);
2338
2339     Asm->OutStreamer.EmitFill(Padding, 0xff);
2340
2341     for (const ArangeSpan &Span : List) {
2342       Asm->EmitLabelReference(Span.Start, PtrSize);
2343
2344       // Calculate the size as being from the span start to it's end.
2345       if (Span.End) {
2346         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2347       } else {
2348         // For symbols without an end marker (e.g. common), we
2349         // write a single arange entry containing just that one symbol.
2350         uint64_t Size = SymSize[Span.Start];
2351         if (Size == 0)
2352           Size = 1;
2353
2354         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2355       }
2356     }
2357
2358     Asm->OutStreamer.AddComment("ARange terminator");
2359     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2360     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2361   }
2362 }
2363
2364 // Emit visible names into a debug ranges section.
2365 void DwarfDebug::emitDebugRanges() {
2366   // Start the dwarf ranges section.
2367   Asm->OutStreamer.SwitchSection(
2368       Asm->getObjFileLowering().getDwarfRangesSection());
2369
2370   // Size for our labels.
2371   unsigned char Size = Asm->getDataLayout().getPointerSize();
2372
2373   // Grab the specific ranges for the compile units in the module.
2374   for (const auto &I : CUMap) {
2375     DwarfCompileUnit *TheCU = I.second;
2376
2377     // Iterate over the misc ranges for the compile units in the module.
2378     for (const RangeSpanList &List : TheCU->getRangeLists()) {
2379       // Emit our symbol so we can find the beginning of the range.
2380       Asm->OutStreamer.EmitLabel(List.getSym());
2381
2382       for (const RangeSpan &Range : List.getRanges()) {
2383         const MCSymbol *Begin = Range.getStart();
2384         const MCSymbol *End = Range.getEnd();
2385         assert(Begin && "Range without a begin symbol?");
2386         assert(End && "Range without an end symbol?");
2387         if (TheCU->getRanges().size() == 1) {
2388           // Grab the begin symbol from the first range as our base.
2389           const MCSymbol *Base = TheCU->getRanges()[0].getStart();
2390           Asm->EmitLabelDifference(Begin, Base, Size);
2391           Asm->EmitLabelDifference(End, Base, Size);
2392         } else {
2393           Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2394           Asm->OutStreamer.EmitSymbolValue(End, Size);
2395         }
2396       }
2397
2398       // And terminate the list with two 0 values.
2399       Asm->OutStreamer.EmitIntValue(0, Size);
2400       Asm->OutStreamer.EmitIntValue(0, Size);
2401     }
2402
2403     // Now emit a range for the CU itself.
2404     if (TheCU->getRanges().size() > 1) {
2405       Asm->OutStreamer.EmitLabel(
2406           Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2407       for (const RangeSpan &Range : TheCU->getRanges()) {
2408         const MCSymbol *Begin = Range.getStart();
2409         const MCSymbol *End = Range.getEnd();
2410         assert(Begin && "Range without a begin symbol?");
2411         assert(End && "Range without an end symbol?");
2412         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2413         Asm->OutStreamer.EmitSymbolValue(End, Size);
2414       }
2415       // And terminate the list with two 0 values.
2416       Asm->OutStreamer.EmitIntValue(0, Size);
2417       Asm->OutStreamer.EmitIntValue(0, Size);
2418     }
2419   }
2420 }
2421
2422 // DWARF5 Experimental Separate Dwarf emitters.
2423
2424 void DwarfDebug::initSkeletonUnit(const DwarfUnit &U, DIE &Die,
2425                                   std::unique_ptr<DwarfUnit> NewU) {
2426   NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2427                        U.getCUNode().getSplitDebugFilename());
2428
2429   if (!CompilationDir.empty())
2430     NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2431
2432   addGnuPubAttributes(*NewU, Die);
2433
2434   SkeletonHolder.addUnit(std::move(NewU));
2435 }
2436
2437 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2438 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2439 // DW_AT_addr_base, DW_AT_ranges_base.
2440 DwarfCompileUnit &DwarfDebug::constructSkeletonCU(const DwarfCompileUnit &CU) {
2441
2442   auto OwnedUnit = make_unique<DwarfCompileUnit>(
2443       CU.getUniqueID(), CU.getCUNode(), Asm, this, &SkeletonHolder);
2444   DwarfCompileUnit &NewCU = *OwnedUnit;
2445   NewCU.initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2446                     DwarfInfoSectionSym);
2447
2448   NewCU.initStmtList(DwarfLineSectionSym);
2449
2450   initSkeletonUnit(CU, NewCU.getUnitDie(), std::move(OwnedUnit));
2451
2452   return NewCU;
2453 }
2454
2455 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2456 // compile units that would normally be in debug_info.
2457 void DwarfDebug::emitDebugInfoDWO() {
2458   assert(useSplitDwarf() && "No split dwarf debug info?");
2459   // Don't pass an abbrev symbol, using a constant zero instead so as not to
2460   // emit relocations into the dwo file.
2461   InfoHolder.emitUnits(this, /* AbbrevSymbol */ nullptr);
2462 }
2463
2464 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2465 // abbreviations for the .debug_info.dwo section.
2466 void DwarfDebug::emitDebugAbbrevDWO() {
2467   assert(useSplitDwarf() && "No split dwarf?");
2468   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2469 }
2470
2471 void DwarfDebug::emitDebugLineDWO() {
2472   assert(useSplitDwarf() && "No split dwarf?");
2473   Asm->OutStreamer.SwitchSection(
2474       Asm->getObjFileLowering().getDwarfLineDWOSection());
2475   SplitTypeUnitFileTable.Emit(Asm->OutStreamer);
2476 }
2477
2478 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2479 // string section and is identical in format to traditional .debug_str
2480 // sections.
2481 void DwarfDebug::emitDebugStrDWO() {
2482   assert(useSplitDwarf() && "No split dwarf?");
2483   const MCSection *OffSec =
2484       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2485   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2486                          OffSec);
2487 }
2488
2489 MCDwarfDwoLineTable *DwarfDebug::getDwoLineTable(const DwarfCompileUnit &CU) {
2490   if (!useSplitDwarf())
2491     return nullptr;
2492   if (SingleCU)
2493     SplitTypeUnitFileTable.setCompilationDir(CU.getCUNode().getDirectory());
2494   return &SplitTypeUnitFileTable;
2495 }
2496
2497 static uint64_t makeTypeSignature(StringRef Identifier) {
2498   MD5 Hash;
2499   Hash.update(Identifier);
2500   // ... take the least significant 8 bytes and return those. Our MD5
2501   // implementation always returns its results in little endian, swap bytes
2502   // appropriately.
2503   MD5::MD5Result Result;
2504   Hash.final(Result);
2505   return *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2506 }
2507
2508 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2509                                       StringRef Identifier, DIE &RefDie,
2510                                       DICompositeType CTy) {
2511   // Fast path if we're building some type units and one has already used the
2512   // address pool we know we're going to throw away all this work anyway, so
2513   // don't bother building dependent types.
2514   if (!TypeUnitsUnderConstruction.empty() && AddrPool.hasBeenUsed())
2515     return;
2516
2517   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2518   if (TU) {
2519     CU.addDIETypeSignature(RefDie, *TU);
2520     return;
2521   }
2522
2523   bool TopLevelType = TypeUnitsUnderConstruction.empty();
2524   AddrPool.resetUsedFlag();
2525
2526   auto OwnedUnit = make_unique<DwarfTypeUnit>(
2527       InfoHolder.getUnits().size() + TypeUnitsUnderConstruction.size(), CU, Asm,
2528       this, &InfoHolder, getDwoLineTable(CU));
2529   DwarfTypeUnit &NewTU = *OwnedUnit;
2530   DIE &UnitDie = NewTU.getUnitDie();
2531   TU = &NewTU;
2532   TypeUnitsUnderConstruction.push_back(
2533       std::make_pair(std::move(OwnedUnit), CTy));
2534
2535   NewTU.addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2536                 CU.getLanguage());
2537
2538   uint64_t Signature = makeTypeSignature(Identifier);
2539   NewTU.setTypeSignature(Signature);
2540
2541   if (useSplitDwarf())
2542     NewTU.initSection(Asm->getObjFileLowering().getDwarfTypesDWOSection(),
2543                       DwarfTypesDWOSectionSym);
2544   else {
2545     CU.applyStmtList(UnitDie);
2546     NewTU.initSection(
2547         Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2548   }
2549
2550   NewTU.setType(NewTU.createTypeDIE(CTy));
2551
2552   if (TopLevelType) {
2553     auto TypeUnitsToAdd = std::move(TypeUnitsUnderConstruction);
2554     TypeUnitsUnderConstruction.clear();
2555
2556     // Types referencing entries in the address table cannot be placed in type
2557     // units.
2558     if (AddrPool.hasBeenUsed()) {
2559
2560       // Remove all the types built while building this type.
2561       // This is pessimistic as some of these types might not be dependent on
2562       // the type that used an address.
2563       for (const auto &TU : TypeUnitsToAdd)
2564         DwarfTypeUnits.erase(TU.second);
2565
2566       // Construct this type in the CU directly.
2567       // This is inefficient because all the dependent types will be rebuilt
2568       // from scratch, including building them in type units, discovering that
2569       // they depend on addresses, throwing them out and rebuilding them.
2570       CU.constructTypeDIE(RefDie, CTy);
2571       return;
2572     }
2573
2574     // If the type wasn't dependent on fission addresses, finish adding the type
2575     // and all its dependent types.
2576     for (auto &TU : TypeUnitsToAdd)
2577       InfoHolder.addUnit(std::move(TU.first));
2578   }
2579   CU.addDIETypeSignature(RefDie, NewTU);
2580 }
2581
2582 // Accelerator table mutators - add each name along with its companion
2583 // DIE to the proper table while ensuring that the name that we're going
2584 // to reference is in the string table. We do this since the names we
2585 // add may not only be identical to the names in the DIE.
2586 void DwarfDebug::addAccelName(StringRef Name, const DIE &Die) {
2587   if (!useDwarfAccelTables())
2588     return;
2589   AccelNames.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2590                      &Die);
2591 }
2592
2593 void DwarfDebug::addAccelObjC(StringRef Name, const DIE &Die) {
2594   if (!useDwarfAccelTables())
2595     return;
2596   AccelObjC.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2597                     &Die);
2598 }
2599
2600 void DwarfDebug::addAccelNamespace(StringRef Name, const DIE &Die) {
2601   if (!useDwarfAccelTables())
2602     return;
2603   AccelNamespace.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2604                          &Die);
2605 }
2606
2607 void DwarfDebug::addAccelType(StringRef Name, const DIE &Die, char Flags) {
2608   if (!useDwarfAccelTables())
2609     return;
2610   AccelTypes.AddName(Name, InfoHolder.getStringPool().getSymbol(*Asm, Name),
2611                      &Die);
2612 }