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