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