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