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