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