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