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