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