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