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