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