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