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