If we see that we're emitting code for a function that doesn't have
[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     UsedNonDefaultText = true;
1467     return;
1468   }
1469
1470   assert(UserVariables.empty() && DbgValues.empty() && "Maps weren't cleaned");
1471
1472   // Make sure that each lexical scope will have a begin/end label.
1473   identifyScopeMarkers();
1474
1475   // Set DwarfDwarfCompileUnitID in MCContext to the Compile Unit this function
1476   // belongs to so that we add to the correct per-cu line table in the
1477   // non-asm case.
1478   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1479   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1480   assert(TheCU && "Unable to find compile unit!");
1481   if (Asm->OutStreamer.hasRawTextSupport())
1482     // Use a single line table if we are generating assembly.
1483     Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1484   else
1485     Asm->OutStreamer.getContext().setDwarfCompileUnitID(TheCU->getUniqueID());
1486
1487   // Check the current section against the standard text section. If different
1488   // keep track so that we will know when we're emitting functions into multiple
1489   // sections.
1490   if (Asm->getObjFileLowering().getTextSection() != Asm->getCurrentSection())
1491     UsedNonDefaultText = true;
1492
1493   // Emit a label for the function so that we have a beginning address.
1494   FunctionBeginSym = Asm->GetTempSymbol("func_begin", Asm->getFunctionNumber());
1495   // Assumes in correct section after the entry point.
1496   Asm->OutStreamer.EmitLabel(FunctionBeginSym);
1497
1498   const TargetRegisterInfo *TRI = Asm->TM.getRegisterInfo();
1499   // LiveUserVar - Map physreg numbers to the MDNode they contain.
1500   std::vector<const MDNode *> LiveUserVar(TRI->getNumRegs());
1501
1502   for (MachineFunction::const_iterator I = MF->begin(), E = MF->end(); I != E;
1503        ++I) {
1504     bool AtBlockEntry = true;
1505     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
1506          II != IE; ++II) {
1507       const MachineInstr *MI = II;
1508
1509       if (MI->isDebugValue()) {
1510         assert(MI->getNumOperands() > 1 && "Invalid machine instruction!");
1511
1512         // Keep track of user variables.
1513         const MDNode *Var =
1514             MI->getOperand(MI->getNumOperands() - 1).getMetadata();
1515
1516         // Variable is in a register, we need to check for clobbers.
1517         if (isDbgValueInDefinedReg(MI))
1518           LiveUserVar[MI->getOperand(0).getReg()] = Var;
1519
1520         // Check the history of this variable.
1521         SmallVectorImpl<const MachineInstr *> &History = DbgValues[Var];
1522         if (History.empty()) {
1523           UserVariables.push_back(Var);
1524           // The first mention of a function argument gets the FunctionBeginSym
1525           // label, so arguments are visible when breaking at function entry.
1526           DIVariable DV(Var);
1527           if (DV.isVariable() && DV.getTag() == dwarf::DW_TAG_arg_variable &&
1528               getDISubprogram(DV.getContext()).describes(MF->getFunction()))
1529             LabelsBeforeInsn[MI] = FunctionBeginSym;
1530         } else {
1531           // We have seen this variable before. Try to coalesce DBG_VALUEs.
1532           const MachineInstr *Prev = History.back();
1533           if (Prev->isDebugValue()) {
1534             // Coalesce identical entries at the end of History.
1535             if (History.size() >= 2 &&
1536                 Prev->isIdenticalTo(History[History.size() - 2])) {
1537               DEBUG(dbgs() << "Coalescing identical DBG_VALUE entries:\n"
1538                            << "\t" << *Prev << "\t"
1539                            << *History[History.size() - 2] << "\n");
1540               History.pop_back();
1541             }
1542
1543             // Terminate old register assignments that don't reach MI;
1544             MachineFunction::const_iterator PrevMBB = Prev->getParent();
1545             if (PrevMBB != I && (!AtBlockEntry || std::next(PrevMBB) != I) &&
1546                 isDbgValueInDefinedReg(Prev)) {
1547               // Previous register assignment needs to terminate at the end of
1548               // its basic block.
1549               MachineBasicBlock::const_iterator LastMI =
1550                   PrevMBB->getLastNonDebugInstr();
1551               if (LastMI == PrevMBB->end()) {
1552                 // Drop DBG_VALUE for empty range.
1553                 DEBUG(dbgs() << "Dropping DBG_VALUE for empty range:\n"
1554                              << "\t" << *Prev << "\n");
1555                 History.pop_back();
1556               } else if (std::next(PrevMBB) != PrevMBB->getParent()->end())
1557                 // Terminate after LastMI.
1558                 History.push_back(LastMI);
1559             }
1560           }
1561         }
1562         History.push_back(MI);
1563       } else {
1564         // Not a DBG_VALUE instruction.
1565         if (!MI->isPosition())
1566           AtBlockEntry = false;
1567
1568         // First known non-DBG_VALUE and non-frame setup location marks
1569         // the beginning of the function body.
1570         if (!MI->getFlag(MachineInstr::FrameSetup) &&
1571             (PrologEndLoc.isUnknown() && !MI->getDebugLoc().isUnknown()))
1572           PrologEndLoc = MI->getDebugLoc();
1573
1574         // Check if the instruction clobbers any registers with debug vars.
1575         for (const MachineOperand &MO : MI->operands()) {
1576           if (!MO.isReg() || !MO.isDef() || !MO.getReg())
1577             continue;
1578           for (MCRegAliasIterator AI(MO.getReg(), TRI, true); AI.isValid();
1579                ++AI) {
1580             unsigned Reg = *AI;
1581             const MDNode *Var = LiveUserVar[Reg];
1582             if (!Var)
1583               continue;
1584             // Reg is now clobbered.
1585             LiveUserVar[Reg] = 0;
1586
1587             // Was MD last defined by a DBG_VALUE referring to Reg?
1588             DbgValueHistoryMap::iterator HistI = DbgValues.find(Var);
1589             if (HistI == DbgValues.end())
1590               continue;
1591             SmallVectorImpl<const MachineInstr *> &History = HistI->second;
1592             if (History.empty())
1593               continue;
1594             const MachineInstr *Prev = History.back();
1595             // Sanity-check: Register assignments are terminated at the end of
1596             // their block.
1597             if (!Prev->isDebugValue() || Prev->getParent() != MI->getParent())
1598               continue;
1599             // Is the variable still in Reg?
1600             if (!isDbgValueInDefinedReg(Prev) ||
1601                 Prev->getOperand(0).getReg() != Reg)
1602               continue;
1603             // Var is clobbered. Make sure the next instruction gets a label.
1604             History.push_back(MI);
1605           }
1606         }
1607       }
1608     }
1609   }
1610
1611   for (auto &I : DbgValues) {
1612     SmallVectorImpl<const MachineInstr *> &History = I.second;
1613     if (History.empty())
1614       continue;
1615
1616     // Make sure the final register assignments are terminated.
1617     const MachineInstr *Prev = History.back();
1618     if (Prev->isDebugValue() && isDbgValueInDefinedReg(Prev)) {
1619       const MachineBasicBlock *PrevMBB = Prev->getParent();
1620       MachineBasicBlock::const_iterator LastMI =
1621           PrevMBB->getLastNonDebugInstr();
1622       if (LastMI == PrevMBB->end())
1623         // Drop DBG_VALUE for empty range.
1624         History.pop_back();
1625       else if (PrevMBB != &PrevMBB->getParent()->back()) {
1626         // Terminate after LastMI.
1627         History.push_back(LastMI);
1628       }
1629     }
1630     // Request labels for the full history.
1631     for (const MachineInstr *MI : History) {
1632       if (MI->isDebugValue())
1633         requestLabelBeforeInsn(MI);
1634       else
1635         requestLabelAfterInsn(MI);
1636     }
1637   }
1638
1639   PrevInstLoc = DebugLoc();
1640   PrevLabel = FunctionBeginSym;
1641
1642   // Record beginning of function.
1643   if (!PrologEndLoc.isUnknown()) {
1644     DebugLoc FnStartDL =
1645         PrologEndLoc.getFnDebugLoc(MF->getFunction()->getContext());
1646     recordSourceLine(
1647         FnStartDL.getLine(), FnStartDL.getCol(),
1648         FnStartDL.getScope(MF->getFunction()->getContext()),
1649         // We'd like to list the prologue as "not statements" but GDB behaves
1650         // poorly if we do that. Revisit this with caution/GDB (7.5+) testing.
1651         DWARF2_FLAG_IS_STMT);
1652   }
1653 }
1654
1655 void DwarfDebug::addScopeVariable(LexicalScope *LS, DbgVariable *Var) {
1656   SmallVectorImpl<DbgVariable *> &Vars = ScopeVariables[LS];
1657   DIVariable DV = Var->getVariable();
1658   // Variables with positive arg numbers are parameters.
1659   if (unsigned ArgNum = DV.getArgNumber()) {
1660     // Keep all parameters in order at the start of the variable list to ensure
1661     // function types are correct (no out-of-order parameters)
1662     //
1663     // This could be improved by only doing it for optimized builds (unoptimized
1664     // builds have the right order to begin with), searching from the back (this
1665     // would catch the unoptimized case quickly), or doing a binary search
1666     // rather than linear search.
1667     SmallVectorImpl<DbgVariable *>::iterator I = Vars.begin();
1668     while (I != Vars.end()) {
1669       unsigned CurNum = (*I)->getVariable().getArgNumber();
1670       // A local (non-parameter) variable has been found, insert immediately
1671       // before it.
1672       if (CurNum == 0)
1673         break;
1674       // A later indexed parameter has been found, insert immediately before it.
1675       if (CurNum > ArgNum)
1676         break;
1677       ++I;
1678     }
1679     Vars.insert(I, Var);
1680     return;
1681   }
1682
1683   Vars.push_back(Var);
1684 }
1685
1686 // Gather and emit post-function debug information.
1687 void DwarfDebug::endFunction(const MachineFunction *MF) {
1688   // Every beginFunction(MF) call should be followed by an endFunction(MF) call,
1689   // though the beginFunction may not be called at all.
1690   // We should handle both cases.
1691   if (CurFn == 0)
1692     CurFn = MF;
1693   else
1694     assert(CurFn == MF);
1695   assert(CurFn != 0);
1696
1697   if (!MMI->hasDebugInfo() || LScopes.empty()) {
1698     CurFn = 0;
1699     return;
1700   }
1701
1702   // Define end label for subprogram.
1703   FunctionEndSym = Asm->GetTempSymbol("func_end", Asm->getFunctionNumber());
1704   // Assumes in correct section after the entry point.
1705   Asm->OutStreamer.EmitLabel(FunctionEndSym);
1706
1707   // Set DwarfDwarfCompileUnitID in MCContext to default value.
1708   Asm->OutStreamer.getContext().setDwarfCompileUnitID(0);
1709
1710   SmallPtrSet<const MDNode *, 16> ProcessedVars;
1711   collectVariableInfo(ProcessedVars);
1712
1713   LexicalScope *FnScope = LScopes.getCurrentFunctionScope();
1714   DwarfCompileUnit *TheCU = SPMap.lookup(FnScope->getScopeNode());
1715   assert(TheCU && "Unable to find compile unit!");
1716
1717   // Construct abstract scopes.
1718   for (LexicalScope *AScope : LScopes.getAbstractScopesList()) {
1719     DISubprogram SP(AScope->getScopeNode());
1720     if (SP.isSubprogram()) {
1721       // Collect info for variables that were optimized out.
1722       DIArray Variables = SP.getVariables();
1723       for (unsigned i = 0, e = Variables.getNumElements(); i != e; ++i) {
1724         DIVariable DV(Variables.getElement(i));
1725         if (!DV || !DV.isVariable() || !ProcessedVars.insert(DV))
1726           continue;
1727         // Check that DbgVariable for DV wasn't created earlier, when
1728         // findAbstractVariable() was called for inlined instance of DV.
1729         LLVMContext &Ctx = DV->getContext();
1730         DIVariable CleanDV = cleanseInlinedVariable(DV, Ctx);
1731         if (AbstractVariables.lookup(CleanDV))
1732           continue;
1733         if (LexicalScope *Scope = LScopes.findAbstractScope(DV.getContext()))
1734           addScopeVariable(Scope, new DbgVariable(DV, NULL, this));
1735       }
1736     }
1737     if (ProcessedSPNodes.count(AScope->getScopeNode()) == 0)
1738       constructScopeDIE(TheCU, AScope);
1739   }
1740
1741   DIE *CurFnDIE = constructScopeDIE(TheCU, FnScope);
1742   if (!CurFn->getTarget().Options.DisableFramePointerElim(*CurFn))
1743     TheCU->addFlag(CurFnDIE, dwarf::DW_AT_APPLE_omit_frame_ptr);
1744
1745   // Add the range of this function to the list of ranges for the CU.
1746   RangeSpan Span(FunctionBeginSym, FunctionEndSym);
1747   TheCU->addRange(std::move(Span));
1748
1749   // Clear debug info
1750   for (auto &I : ScopeVariables)
1751     DeleteContainerPointers(I.second);
1752   ScopeVariables.clear();
1753   DeleteContainerPointers(CurrentFnArguments);
1754   UserVariables.clear();
1755   DbgValues.clear();
1756   AbstractVariables.clear();
1757   LabelsBeforeInsn.clear();
1758   LabelsAfterInsn.clear();
1759   PrevLabel = NULL;
1760   CurFn = 0;
1761 }
1762
1763 // Register a source line with debug info. Returns the  unique label that was
1764 // emitted and which provides correspondence to the source line list.
1765 void DwarfDebug::recordSourceLine(unsigned Line, unsigned Col, const MDNode *S,
1766                                   unsigned Flags) {
1767   StringRef Fn;
1768   StringRef Dir;
1769   unsigned Src = 1;
1770   unsigned Discriminator = 0;
1771   if (S) {
1772     DIDescriptor Scope(S);
1773
1774     if (Scope.isCompileUnit()) {
1775       DICompileUnit CU(S);
1776       Fn = CU.getFilename();
1777       Dir = CU.getDirectory();
1778     } else if (Scope.isFile()) {
1779       DIFile F(S);
1780       Fn = F.getFilename();
1781       Dir = F.getDirectory();
1782     } else if (Scope.isSubprogram()) {
1783       DISubprogram SP(S);
1784       Fn = SP.getFilename();
1785       Dir = SP.getDirectory();
1786     } else if (Scope.isLexicalBlockFile()) {
1787       DILexicalBlockFile DBF(S);
1788       Fn = DBF.getFilename();
1789       Dir = DBF.getDirectory();
1790     } else if (Scope.isLexicalBlock()) {
1791       DILexicalBlock DB(S);
1792       Fn = DB.getFilename();
1793       Dir = DB.getDirectory();
1794       Discriminator = DB.getDiscriminator();
1795     } else
1796       llvm_unreachable("Unexpected scope info");
1797
1798     Src = getOrCreateSourceID(
1799         Fn, Dir, Asm->OutStreamer.getContext().getDwarfCompileUnitID());
1800   }
1801   Asm->OutStreamer.EmitDwarfLocDirective(Src, Line, Col, Flags, 0,
1802                                          Discriminator, Fn);
1803 }
1804
1805 //===----------------------------------------------------------------------===//
1806 // Emit Methods
1807 //===----------------------------------------------------------------------===//
1808
1809 // Compute the size and offset of a DIE. The offset is relative to start of the
1810 // CU. It returns the offset after laying out the DIE.
1811 unsigned DwarfFile::computeSizeAndOffset(DIE *Die, unsigned Offset) {
1812   // Record the abbreviation.
1813   assignAbbrevNumber(Die->getAbbrev());
1814
1815   // Get the abbreviation for this DIE.
1816   const DIEAbbrev &Abbrev = Die->getAbbrev();
1817
1818   // Set DIE offset
1819   Die->setOffset(Offset);
1820
1821   // Start the size with the size of abbreviation code.
1822   Offset += getULEB128Size(Die->getAbbrevNumber());
1823
1824   const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1825   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1826
1827   // Size the DIE attribute values.
1828   for (unsigned i = 0, N = Values.size(); i < N; ++i)
1829     // Size attribute value.
1830     Offset += Values[i]->SizeOf(Asm, AbbrevData[i].getForm());
1831
1832   // Get the children.
1833   const std::vector<DIE *> &Children = Die->getChildren();
1834
1835   // Size the DIE children if any.
1836   if (!Children.empty()) {
1837     assert(Abbrev.hasChildren() && "Children flag not set");
1838
1839     for (DIE *Child : Children)
1840       Offset = computeSizeAndOffset(Child, Offset);
1841
1842     // End of children marker.
1843     Offset += sizeof(int8_t);
1844   }
1845
1846   Die->setSize(Offset - Die->getOffset());
1847   return Offset;
1848 }
1849
1850 // Compute the size and offset for each DIE.
1851 void DwarfFile::computeSizeAndOffsets() {
1852   // Offset from the first CU in the debug info section is 0 initially.
1853   unsigned SecOffset = 0;
1854
1855   // Iterate over each compile unit and set the size and offsets for each
1856   // DIE within each compile unit. All offsets are CU relative.
1857   for (DwarfUnit *TheU : CUs) {
1858     TheU->setDebugInfoOffset(SecOffset);
1859
1860     // CU-relative offset is reset to 0 here.
1861     unsigned Offset = sizeof(int32_t) +      // Length of Unit Info
1862                       TheU->getHeaderSize(); // Unit-specific headers
1863
1864     // EndOffset here is CU-relative, after laying out
1865     // all of the CU DIE.
1866     unsigned EndOffset = computeSizeAndOffset(TheU->getUnitDie(), Offset);
1867     SecOffset += EndOffset;
1868   }
1869 }
1870
1871 // Emit initial Dwarf sections with a label at the start of each one.
1872 void DwarfDebug::emitSectionLabels() {
1873   const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering();
1874
1875   // Dwarf sections base addresses.
1876   DwarfInfoSectionSym =
1877       emitSectionSym(Asm, TLOF.getDwarfInfoSection(), "section_info");
1878   if (useSplitDwarf())
1879     DwarfInfoDWOSectionSym =
1880         emitSectionSym(Asm, TLOF.getDwarfInfoDWOSection(), "section_info_dwo");
1881   DwarfAbbrevSectionSym =
1882       emitSectionSym(Asm, TLOF.getDwarfAbbrevSection(), "section_abbrev");
1883   if (useSplitDwarf())
1884     DwarfAbbrevDWOSectionSym = emitSectionSym(
1885         Asm, TLOF.getDwarfAbbrevDWOSection(), "section_abbrev_dwo");
1886   if (GenerateARangeSection)
1887     emitSectionSym(Asm, TLOF.getDwarfARangesSection());
1888
1889   DwarfLineSectionSym =
1890       emitSectionSym(Asm, TLOF.getDwarfLineSection(), "section_line");
1891   emitSectionSym(Asm, TLOF.getDwarfLocSection());
1892   if (GenerateGnuPubSections) {
1893     DwarfGnuPubNamesSectionSym =
1894         emitSectionSym(Asm, TLOF.getDwarfGnuPubNamesSection());
1895     DwarfGnuPubTypesSectionSym =
1896         emitSectionSym(Asm, TLOF.getDwarfGnuPubTypesSection());
1897   } else if (HasDwarfPubSections) {
1898     emitSectionSym(Asm, TLOF.getDwarfPubNamesSection());
1899     emitSectionSym(Asm, TLOF.getDwarfPubTypesSection());
1900   }
1901
1902   DwarfStrSectionSym =
1903       emitSectionSym(Asm, TLOF.getDwarfStrSection(), "info_string");
1904   if (useSplitDwarf()) {
1905     DwarfStrDWOSectionSym =
1906         emitSectionSym(Asm, TLOF.getDwarfStrDWOSection(), "skel_string");
1907     DwarfAddrSectionSym =
1908         emitSectionSym(Asm, TLOF.getDwarfAddrSection(), "addr_sec");
1909   }
1910   DwarfDebugRangeSectionSym =
1911       emitSectionSym(Asm, TLOF.getDwarfRangesSection(), "debug_range");
1912
1913   DwarfDebugLocSectionSym =
1914       emitSectionSym(Asm, TLOF.getDwarfLocSection(), "section_debug_loc");
1915 }
1916
1917 // Recursively emits a debug information entry.
1918 void DwarfDebug::emitDIE(DIE *Die) {
1919   // Get the abbreviation for this DIE.
1920   const DIEAbbrev &Abbrev = Die->getAbbrev();
1921
1922   // Emit the code (index) for the abbreviation.
1923   if (Asm->isVerbose())
1924     Asm->OutStreamer.AddComment("Abbrev [" + Twine(Abbrev.getNumber()) +
1925                                 "] 0x" + Twine::utohexstr(Die->getOffset()) +
1926                                 ":0x" + Twine::utohexstr(Die->getSize()) + " " +
1927                                 dwarf::TagString(Abbrev.getTag()));
1928   Asm->EmitULEB128(Abbrev.getNumber());
1929
1930   const SmallVectorImpl<DIEValue *> &Values = Die->getValues();
1931   const SmallVectorImpl<DIEAbbrevData> &AbbrevData = Abbrev.getData();
1932
1933   // Emit the DIE attribute values.
1934   for (unsigned i = 0, N = Values.size(); i < N; ++i) {
1935     dwarf::Attribute Attr = AbbrevData[i].getAttribute();
1936     dwarf::Form Form = AbbrevData[i].getForm();
1937     assert(Form && "Too many attributes for DIE (check abbreviation)");
1938
1939     if (Asm->isVerbose()) {
1940       Asm->OutStreamer.AddComment(dwarf::AttributeString(Attr));
1941       if (Attr == dwarf::DW_AT_accessibility)
1942         Asm->OutStreamer.AddComment(dwarf::AccessibilityString(
1943             cast<DIEInteger>(Values[i])->getValue()));
1944     }
1945
1946     // Emit an attribute using the defined form.
1947     Values[i]->EmitValue(Asm, Form);
1948   }
1949
1950   // Emit the DIE children if any.
1951   if (Abbrev.hasChildren()) {
1952     const std::vector<DIE *> &Children = Die->getChildren();
1953
1954     for (DIE *Child : Children)
1955       emitDIE(Child);
1956
1957     Asm->OutStreamer.AddComment("End Of Children Mark");
1958     Asm->EmitInt8(0);
1959   }
1960 }
1961
1962 // Emit the various dwarf units to the unit section USection with
1963 // the abbreviations going into ASection.
1964 void DwarfFile::emitUnits(DwarfDebug *DD, const MCSection *ASection,
1965                           const MCSymbol *ASectionSym) {
1966   for (DwarfUnit *TheU : CUs) {
1967     DIE *Die = TheU->getUnitDie();
1968     const MCSection *USection = TheU->getSection();
1969     Asm->OutStreamer.SwitchSection(USection);
1970
1971     // Emit the compile units header.
1972     Asm->OutStreamer.EmitLabel(TheU->getLabelBegin());
1973
1974     // Emit size of content not including length itself
1975     Asm->OutStreamer.AddComment("Length of Unit");
1976     Asm->EmitInt32(TheU->getHeaderSize() + Die->getSize());
1977
1978     TheU->emitHeader(ASection, ASectionSym);
1979
1980     DD->emitDIE(Die);
1981     Asm->OutStreamer.EmitLabel(TheU->getLabelEnd());
1982   }
1983 }
1984
1985 // Emit the debug info section.
1986 void DwarfDebug::emitDebugInfo() {
1987   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1988
1989   Holder.emitUnits(this, Asm->getObjFileLowering().getDwarfAbbrevSection(),
1990                    DwarfAbbrevSectionSym);
1991 }
1992
1993 // Emit the abbreviation section.
1994 void DwarfDebug::emitAbbreviations() {
1995   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
1996
1997   Holder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevSection());
1998 }
1999
2000 void DwarfFile::emitAbbrevs(const MCSection *Section) {
2001   // Check to see if it is worth the effort.
2002   if (!Abbreviations.empty()) {
2003     // Start the debug abbrev section.
2004     Asm->OutStreamer.SwitchSection(Section);
2005
2006     // For each abbrevation.
2007     for (const DIEAbbrev *Abbrev : Abbreviations) {
2008       // Emit the abbrevations code (base 1 index.)
2009       Asm->EmitULEB128(Abbrev->getNumber(), "Abbreviation Code");
2010
2011       // Emit the abbreviations data.
2012       Abbrev->Emit(Asm);
2013     }
2014
2015     // Mark end of abbreviations.
2016     Asm->EmitULEB128(0, "EOM(3)");
2017   }
2018 }
2019
2020 // Emit the last address of the section and the end of the line matrix.
2021 void DwarfDebug::emitEndOfLineMatrix(unsigned SectionEnd) {
2022   // Define last address of section.
2023   Asm->OutStreamer.AddComment("Extended Op");
2024   Asm->EmitInt8(0);
2025
2026   Asm->OutStreamer.AddComment("Op size");
2027   Asm->EmitInt8(Asm->getDataLayout().getPointerSize() + 1);
2028   Asm->OutStreamer.AddComment("DW_LNE_set_address");
2029   Asm->EmitInt8(dwarf::DW_LNE_set_address);
2030
2031   Asm->OutStreamer.AddComment("Section end label");
2032
2033   Asm->OutStreamer.EmitSymbolValue(
2034       Asm->GetTempSymbol("section_end", SectionEnd),
2035       Asm->getDataLayout().getPointerSize());
2036
2037   // Mark end of matrix.
2038   Asm->OutStreamer.AddComment("DW_LNE_end_sequence");
2039   Asm->EmitInt8(0);
2040   Asm->EmitInt8(1);
2041   Asm->EmitInt8(1);
2042 }
2043
2044 // Emit visible names into a hashed accelerator table section.
2045 void DwarfDebug::emitAccelNames() {
2046   DwarfAccelTable AT(
2047       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2048   for (DwarfUnit *TheU : getUnits()) {
2049     for (const auto &GI : TheU->getAccelNames()) {
2050       StringRef Name = GI.getKey();
2051       for (const DIE *D : GI.second)
2052         AT.AddName(Name, D);
2053     }
2054   }
2055
2056   AT.FinalizeTable(Asm, "Names");
2057   Asm->OutStreamer.SwitchSection(
2058       Asm->getObjFileLowering().getDwarfAccelNamesSection());
2059   MCSymbol *SectionBegin = Asm->GetTempSymbol("names_begin");
2060   Asm->OutStreamer.EmitLabel(SectionBegin);
2061
2062   // Emit the full data.
2063   AT.Emit(Asm, SectionBegin, &InfoHolder);
2064 }
2065
2066 // Emit objective C classes and categories into a hashed accelerator table
2067 // section.
2068 void DwarfDebug::emitAccelObjC() {
2069   DwarfAccelTable AT(
2070       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2071   for (DwarfUnit *TheU : getUnits()) {
2072     for (const auto &GI : TheU->getAccelObjC()) {
2073       StringRef Name = GI.getKey();
2074       for (const DIE *D : GI.second)
2075         AT.AddName(Name, D);
2076     }
2077   }
2078
2079   AT.FinalizeTable(Asm, "ObjC");
2080   Asm->OutStreamer.SwitchSection(
2081       Asm->getObjFileLowering().getDwarfAccelObjCSection());
2082   MCSymbol *SectionBegin = Asm->GetTempSymbol("objc_begin");
2083   Asm->OutStreamer.EmitLabel(SectionBegin);
2084
2085   // Emit the full data.
2086   AT.Emit(Asm, SectionBegin, &InfoHolder);
2087 }
2088
2089 // Emit namespace dies into a hashed accelerator table.
2090 void DwarfDebug::emitAccelNamespaces() {
2091   DwarfAccelTable AT(
2092       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2093   for (DwarfUnit *TheU : getUnits()) {
2094     for (const auto &GI : TheU->getAccelNamespace()) {
2095       StringRef Name = GI.getKey();
2096       for (const DIE *D : GI.second)
2097         AT.AddName(Name, D);
2098     }
2099   }
2100
2101   AT.FinalizeTable(Asm, "namespac");
2102   Asm->OutStreamer.SwitchSection(
2103       Asm->getObjFileLowering().getDwarfAccelNamespaceSection());
2104   MCSymbol *SectionBegin = Asm->GetTempSymbol("namespac_begin");
2105   Asm->OutStreamer.EmitLabel(SectionBegin);
2106
2107   // Emit the full data.
2108   AT.Emit(Asm, SectionBegin, &InfoHolder);
2109 }
2110
2111 // Emit type dies into a hashed accelerator table.
2112 void DwarfDebug::emitAccelTypes() {
2113   std::vector<DwarfAccelTable::Atom> Atoms;
2114   Atoms.push_back(
2115       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_offset, dwarf::DW_FORM_data4));
2116   Atoms.push_back(
2117       DwarfAccelTable::Atom(dwarf::DW_ATOM_die_tag, dwarf::DW_FORM_data2));
2118   Atoms.push_back(
2119       DwarfAccelTable::Atom(dwarf::DW_ATOM_type_flags, dwarf::DW_FORM_data1));
2120   DwarfAccelTable AT(Atoms);
2121   for (DwarfUnit *TheU : getUnits()) {
2122     for (const auto &GI : TheU->getAccelTypes()) {
2123       StringRef Name = GI.getKey();
2124       for (const auto &DI : GI.second)
2125         AT.AddName(Name, DI.first, DI.second);
2126     }
2127   }
2128
2129   AT.FinalizeTable(Asm, "types");
2130   Asm->OutStreamer.SwitchSection(
2131       Asm->getObjFileLowering().getDwarfAccelTypesSection());
2132   MCSymbol *SectionBegin = Asm->GetTempSymbol("types_begin");
2133   Asm->OutStreamer.EmitLabel(SectionBegin);
2134
2135   // Emit the full data.
2136   AT.Emit(Asm, SectionBegin, &InfoHolder);
2137 }
2138
2139 // Public name handling.
2140 // The format for the various pubnames:
2141 //
2142 // dwarf pubnames - offset/name pairs where the offset is the offset into the CU
2143 // for the DIE that is named.
2144 //
2145 // gnu pubnames - offset/index value/name tuples where the offset is the offset
2146 // into the CU and the index value is computed according to the type of value
2147 // for the DIE that is named.
2148 //
2149 // For type units the offset is the offset of the skeleton DIE. For split dwarf
2150 // it's the offset within the debug_info/debug_types dwo section, however, the
2151 // reference in the pubname header doesn't change.
2152
2153 /// computeIndexValue - Compute the gdb index value for the DIE and CU.
2154 static dwarf::PubIndexEntryDescriptor computeIndexValue(DwarfUnit *CU,
2155                                                         const DIE *Die) {
2156   dwarf::GDBIndexEntryLinkage Linkage = dwarf::GIEL_STATIC;
2157
2158   // We could have a specification DIE that has our most of our knowledge,
2159   // look for that now.
2160   DIEValue *SpecVal = Die->findAttribute(dwarf::DW_AT_specification);
2161   if (SpecVal) {
2162     DIE *SpecDIE = cast<DIEEntry>(SpecVal)->getEntry();
2163     if (SpecDIE->findAttribute(dwarf::DW_AT_external))
2164       Linkage = dwarf::GIEL_EXTERNAL;
2165   } else if (Die->findAttribute(dwarf::DW_AT_external))
2166     Linkage = dwarf::GIEL_EXTERNAL;
2167
2168   switch (Die->getTag()) {
2169   case dwarf::DW_TAG_class_type:
2170   case dwarf::DW_TAG_structure_type:
2171   case dwarf::DW_TAG_union_type:
2172   case dwarf::DW_TAG_enumeration_type:
2173     return dwarf::PubIndexEntryDescriptor(
2174         dwarf::GIEK_TYPE, CU->getLanguage() != dwarf::DW_LANG_C_plus_plus
2175                               ? dwarf::GIEL_STATIC
2176                               : dwarf::GIEL_EXTERNAL);
2177   case dwarf::DW_TAG_typedef:
2178   case dwarf::DW_TAG_base_type:
2179   case dwarf::DW_TAG_subrange_type:
2180     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_TYPE, dwarf::GIEL_STATIC);
2181   case dwarf::DW_TAG_namespace:
2182     return dwarf::GIEK_TYPE;
2183   case dwarf::DW_TAG_subprogram:
2184     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_FUNCTION, Linkage);
2185   case dwarf::DW_TAG_constant:
2186   case dwarf::DW_TAG_variable:
2187     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE, Linkage);
2188   case dwarf::DW_TAG_enumerator:
2189     return dwarf::PubIndexEntryDescriptor(dwarf::GIEK_VARIABLE,
2190                                           dwarf::GIEL_STATIC);
2191   default:
2192     return dwarf::GIEK_NONE;
2193   }
2194 }
2195
2196 /// emitDebugPubNames - Emit visible names into a debug pubnames section.
2197 ///
2198 void DwarfDebug::emitDebugPubNames(bool GnuStyle) {
2199   const MCSection *PSec =
2200       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubNamesSection()
2201                : Asm->getObjFileLowering().getDwarfPubNamesSection();
2202
2203   emitDebugPubSection(GnuStyle, PSec, "Names", &DwarfUnit::getGlobalNames);
2204 }
2205
2206 void DwarfDebug::emitDebugPubSection(
2207     bool GnuStyle, const MCSection *PSec, StringRef Name,
2208     const StringMap<const DIE *> &(DwarfUnit::*Accessor)() const) {
2209   for (const auto &NU : CUMap) {
2210     DwarfCompileUnit *TheU = NU.second;
2211
2212     const auto &Globals = (TheU->*Accessor)();
2213
2214     if (Globals.empty())
2215       continue;
2216
2217     if (auto Skeleton = static_cast<DwarfCompileUnit *>(TheU->getSkeleton()))
2218       TheU = Skeleton;
2219     unsigned ID = TheU->getUniqueID();
2220
2221     // Start the dwarf pubnames section.
2222     Asm->OutStreamer.SwitchSection(PSec);
2223
2224     // Emit the header.
2225     Asm->OutStreamer.AddComment("Length of Public " + Name + " Info");
2226     MCSymbol *BeginLabel = Asm->GetTempSymbol("pub" + Name + "_begin", ID);
2227     MCSymbol *EndLabel = Asm->GetTempSymbol("pub" + Name + "_end", ID);
2228     Asm->EmitLabelDifference(EndLabel, BeginLabel, 4);
2229
2230     Asm->OutStreamer.EmitLabel(BeginLabel);
2231
2232     Asm->OutStreamer.AddComment("DWARF Version");
2233     Asm->EmitInt16(dwarf::DW_PUBNAMES_VERSION);
2234
2235     Asm->OutStreamer.AddComment("Offset of Compilation Unit Info");
2236     Asm->EmitSectionOffset(TheU->getLabelBegin(), TheU->getSectionSym());
2237
2238     Asm->OutStreamer.AddComment("Compilation Unit Length");
2239     Asm->EmitLabelDifference(TheU->getLabelEnd(), TheU->getLabelBegin(), 4);
2240
2241     // Emit the pubnames for this compilation unit.
2242     for (const auto &GI : Globals) {
2243       const char *Name = GI.getKeyData();
2244       const DIE *Entity = GI.second;
2245
2246       Asm->OutStreamer.AddComment("DIE offset");
2247       Asm->EmitInt32(Entity->getOffset());
2248
2249       if (GnuStyle) {
2250         dwarf::PubIndexEntryDescriptor Desc = computeIndexValue(TheU, Entity);
2251         Asm->OutStreamer.AddComment(
2252             Twine("Kind: ") + dwarf::GDBIndexEntryKindString(Desc.Kind) + ", " +
2253             dwarf::GDBIndexEntryLinkageString(Desc.Linkage));
2254         Asm->EmitInt8(Desc.toBits());
2255       }
2256
2257       Asm->OutStreamer.AddComment("External Name");
2258       Asm->OutStreamer.EmitBytes(StringRef(Name, GI.getKeyLength() + 1));
2259     }
2260
2261     Asm->OutStreamer.AddComment("End Mark");
2262     Asm->EmitInt32(0);
2263     Asm->OutStreamer.EmitLabel(EndLabel);
2264   }
2265 }
2266
2267 void DwarfDebug::emitDebugPubTypes(bool GnuStyle) {
2268   const MCSection *PSec =
2269       GnuStyle ? Asm->getObjFileLowering().getDwarfGnuPubTypesSection()
2270                : Asm->getObjFileLowering().getDwarfPubTypesSection();
2271
2272   emitDebugPubSection(GnuStyle, PSec, "Types", &DwarfUnit::getGlobalTypes);
2273 }
2274
2275 // Emit strings into a string section.
2276 void DwarfFile::emitStrings(const MCSection *StrSection,
2277                             const MCSection *OffsetSection = NULL,
2278                             const MCSymbol *StrSecSym = NULL) {
2279
2280   if (StringPool.empty())
2281     return;
2282
2283   // Start the dwarf str section.
2284   Asm->OutStreamer.SwitchSection(StrSection);
2285
2286   // Get all of the string pool entries and put them in an array by their ID so
2287   // we can sort them.
2288   SmallVector<std::pair<unsigned, const StrPool::value_type *>, 64 > Entries;
2289
2290   for (const auto &I : StringPool)
2291     Entries.push_back(std::make_pair(I.second.second, &I));
2292
2293   array_pod_sort(Entries.begin(), Entries.end());
2294
2295   for (const auto &Entry : Entries) {
2296     // Emit a label for reference from debug information entries.
2297     Asm->OutStreamer.EmitLabel(Entry.second->getValue().first);
2298
2299     // Emit the string itself with a terminating null byte.
2300     Asm->OutStreamer.EmitBytes(StringRef(Entry.second->getKeyData(),
2301                                          Entry.second->getKeyLength() + 1));
2302   }
2303
2304   // If we've got an offset section go ahead and emit that now as well.
2305   if (OffsetSection) {
2306     Asm->OutStreamer.SwitchSection(OffsetSection);
2307     unsigned offset = 0;
2308     unsigned size = 4; // FIXME: DWARF64 is 8.
2309     for (const auto &Entry : Entries) {
2310       Asm->OutStreamer.EmitIntValue(offset, size);
2311       offset += Entry.second->getKeyLength() + 1;
2312     }
2313   }
2314 }
2315
2316 // Emit addresses into the section given.
2317 void DwarfFile::emitAddresses(const MCSection *AddrSection) {
2318
2319   if (AddressPool.empty())
2320     return;
2321
2322   // Start the dwarf addr section.
2323   Asm->OutStreamer.SwitchSection(AddrSection);
2324
2325   // Order the address pool entries by ID
2326   SmallVector<const MCExpr *, 64> Entries(AddressPool.size());
2327
2328   for (const auto &I : AddressPool)
2329     Entries[I.second.Number] =
2330         I.second.TLS
2331             ? Asm->getObjFileLowering().getDebugThreadLocalSymbol(I.first)
2332             : MCSymbolRefExpr::Create(I.first, Asm->OutContext);
2333
2334   for (const MCExpr *Entry : Entries)
2335     Asm->OutStreamer.EmitValue(Entry, Asm->getDataLayout().getPointerSize());
2336 }
2337
2338 // Emit visible names into a debug str section.
2339 void DwarfDebug::emitDebugStr() {
2340   DwarfFile &Holder = useSplitDwarf() ? SkeletonHolder : InfoHolder;
2341   Holder.emitStrings(Asm->getObjFileLowering().getDwarfStrSection());
2342 }
2343
2344 void DwarfDebug::emitDebugLocEntry(ByteStreamer &Streamer,
2345                                    const DotDebugLocEntry &Entry) {
2346   DIVariable DV(Entry.getVariable());
2347   if (Entry.isInt()) {
2348     DIBasicType BTy(DV.getType());
2349     if (BTy.Verify() && (BTy.getEncoding() == dwarf::DW_ATE_signed ||
2350                          BTy.getEncoding() == dwarf::DW_ATE_signed_char)) {
2351       Streamer.EmitInt8(dwarf::DW_OP_consts, "DW_OP_consts");
2352       Streamer.EmitSLEB128(Entry.getInt());
2353     } else {
2354       Streamer.EmitInt8(dwarf::DW_OP_constu, "DW_OP_constu");
2355       Streamer.EmitULEB128(Entry.getInt());
2356     }
2357   } else if (Entry.isLocation()) {
2358     MachineLocation Loc = Entry.getLoc();
2359     if (!DV.hasComplexAddress())
2360       // Regular entry.
2361       Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2362     else {
2363       // Complex address entry.
2364       unsigned N = DV.getNumAddrElements();
2365       unsigned i = 0;
2366       if (N >= 2 && DV.getAddrElement(0) == DIBuilder::OpPlus) {
2367         if (Loc.getOffset()) {
2368           i = 2;
2369           Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2370           Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2371           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2372           Streamer.EmitSLEB128(DV.getAddrElement(1));
2373         } else {
2374           // If first address element is OpPlus then emit
2375           // DW_OP_breg + Offset instead of DW_OP_reg + Offset.
2376           MachineLocation TLoc(Loc.getReg(), DV.getAddrElement(1));
2377           Asm->EmitDwarfRegOp(Streamer, TLoc, DV.isIndirect());
2378           i = 2;
2379         }
2380       } else {
2381         Asm->EmitDwarfRegOp(Streamer, Loc, DV.isIndirect());
2382       }
2383
2384       // Emit remaining complex address elements.
2385       for (; i < N; ++i) {
2386         uint64_t Element = DV.getAddrElement(i);
2387         if (Element == DIBuilder::OpPlus) {
2388           Streamer.EmitInt8(dwarf::DW_OP_plus_uconst, "DW_OP_plus_uconst");
2389           Streamer.EmitULEB128(DV.getAddrElement(++i));
2390         } else if (Element == DIBuilder::OpDeref) {
2391           if (!Loc.isReg())
2392             Streamer.EmitInt8(dwarf::DW_OP_deref, "DW_OP_deref");
2393         } else
2394           llvm_unreachable("unknown Opcode found in complex address");
2395       }
2396     }
2397   }
2398   // else ... ignore constant fp. There is not any good way to
2399   // to represent them here in dwarf.
2400   // FIXME: ^
2401 }
2402
2403 // Emit locations into the debug loc section.
2404 void DwarfDebug::emitDebugLoc() {
2405   if (DotDebugLocEntries.empty())
2406     return;
2407
2408   for (SmallVectorImpl<DotDebugLocEntry>::iterator
2409            I = DotDebugLocEntries.begin(),
2410            E = DotDebugLocEntries.end();
2411        I != E; ++I) {
2412     DotDebugLocEntry &Entry = *I;
2413     if (I + 1 != DotDebugLocEntries.end())
2414       Entry.Merge(I + 1);
2415   }
2416
2417   // Start the dwarf loc section.
2418   Asm->OutStreamer.SwitchSection(
2419       Asm->getObjFileLowering().getDwarfLocSection());
2420   unsigned char Size = Asm->getDataLayout().getPointerSize();
2421   Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", 0));
2422   unsigned index = 1;
2423   for (SmallVectorImpl<DotDebugLocEntry>::const_iterator
2424            I = DotDebugLocEntries.begin(),
2425            E = DotDebugLocEntries.end();
2426        I != E; ++I, ++index) {
2427     const DotDebugLocEntry &Entry = *I;
2428     if (Entry.isMerged())
2429       continue;
2430
2431     if (Entry.isEmpty()) {
2432       Asm->OutStreamer.EmitIntValue(0, Size);
2433       Asm->OutStreamer.EmitIntValue(0, Size);
2434       Asm->OutStreamer.EmitLabel(Asm->GetTempSymbol("debug_loc", index));
2435     } else {
2436       // Set up the range.
2437       Asm->OutStreamer.EmitSymbolValue(Entry.getBeginSym(), Size);
2438       Asm->OutStreamer.EmitSymbolValue(Entry.getEndSym(), Size);
2439       Asm->OutStreamer.AddComment("Loc expr size");
2440       MCSymbol *begin = Asm->OutStreamer.getContext().CreateTempSymbol();
2441       MCSymbol *end = Asm->OutStreamer.getContext().CreateTempSymbol();
2442       Asm->EmitLabelDifference(end, begin, 2);
2443       Asm->OutStreamer.EmitLabel(begin);
2444       // Emit the entry.
2445       APByteStreamer Streamer(*Asm);
2446       emitDebugLocEntry(Streamer, Entry);
2447       // Close the range.
2448       Asm->OutStreamer.EmitLabel(end);
2449     }
2450   }
2451 }
2452
2453 struct ArangeSpan {
2454   const MCSymbol *Start, *End;
2455 };
2456
2457 // Emit a debug aranges section, containing a CU lookup for any
2458 // address we can tie back to a CU.
2459 void DwarfDebug::emitDebugARanges() {
2460   // Start the dwarf aranges section.
2461   Asm->OutStreamer.SwitchSection(
2462       Asm->getObjFileLowering().getDwarfARangesSection());
2463
2464   typedef DenseMap<DwarfCompileUnit *, std::vector<ArangeSpan> > SpansType;
2465
2466   SpansType Spans;
2467
2468   // Build a list of sections used.
2469   std::vector<const MCSection *> Sections;
2470   for (const auto &it : SectionMap) {
2471     const MCSection *Section = it.first;
2472     Sections.push_back(Section);
2473   }
2474
2475   // Sort the sections into order.
2476   // This is only done to ensure consistent output order across different runs.
2477   std::sort(Sections.begin(), Sections.end(), SectionSort);
2478
2479   // Build a set of address spans, sorted by CU.
2480   for (const MCSection *Section : Sections) {
2481     SmallVector<SymbolCU, 8> &List = SectionMap[Section];
2482     if (List.size() < 2)
2483       continue;
2484
2485     // Sort the symbols by offset within the section.
2486     std::sort(List.begin(), List.end(),
2487               [&](const SymbolCU &A, const SymbolCU &B) {
2488       unsigned IA = A.Sym ? Asm->OutStreamer.GetSymbolOrder(A.Sym) : 0;
2489       unsigned IB = B.Sym ? Asm->OutStreamer.GetSymbolOrder(B.Sym) : 0;
2490
2491       // Symbols with no order assigned should be placed at the end.
2492       // (e.g. section end labels)
2493       if (IA == 0)
2494         return false;
2495       if (IB == 0)
2496         return true;
2497       return IA < IB;
2498     });
2499
2500     // If we have no section (e.g. common), just write out
2501     // individual spans for each symbol.
2502     if (Section == NULL) {
2503       for (const SymbolCU &Cur : List) {
2504         ArangeSpan Span;
2505         Span.Start = Cur.Sym;
2506         Span.End = NULL;
2507         if (Cur.CU)
2508           Spans[Cur.CU].push_back(Span);
2509       }
2510     } else {
2511       // Build spans between each label.
2512       const MCSymbol *StartSym = List[0].Sym;
2513       for (size_t n = 1, e = List.size(); n < e; n++) {
2514         const SymbolCU &Prev = List[n - 1];
2515         const SymbolCU &Cur = List[n];
2516
2517         // Try and build the longest span we can within the same CU.
2518         if (Cur.CU != Prev.CU) {
2519           ArangeSpan Span;
2520           Span.Start = StartSym;
2521           Span.End = Cur.Sym;
2522           Spans[Prev.CU].push_back(Span);
2523           StartSym = Cur.Sym;
2524         }
2525       }
2526     }
2527   }
2528
2529   unsigned PtrSize = Asm->getDataLayout().getPointerSize();
2530
2531   // Build a list of CUs used.
2532   std::vector<DwarfCompileUnit *> CUs;
2533   for (const auto &it : Spans) {
2534     DwarfCompileUnit *CU = it.first;
2535     CUs.push_back(CU);
2536   }
2537
2538   // Sort the CU list (again, to ensure consistent output order).
2539   std::sort(CUs.begin(), CUs.end(), [](const DwarfUnit *A, const DwarfUnit *B) {
2540     return A->getUniqueID() < B->getUniqueID();
2541   });
2542
2543   // Emit an arange table for each CU we used.
2544   for (DwarfCompileUnit *CU : CUs) {
2545     std::vector<ArangeSpan> &List = Spans[CU];
2546
2547     // Emit size of content not including length itself.
2548     unsigned ContentSize =
2549         sizeof(int16_t) + // DWARF ARange version number
2550         sizeof(int32_t) + // Offset of CU in the .debug_info section
2551         sizeof(int8_t) +  // Pointer Size (in bytes)
2552         sizeof(int8_t);   // Segment Size (in bytes)
2553
2554     unsigned TupleSize = PtrSize * 2;
2555
2556     // 7.20 in the Dwarf specs requires the table to be aligned to a tuple.
2557     unsigned Padding =
2558         OffsetToAlignment(sizeof(int32_t) + ContentSize, TupleSize);
2559
2560     ContentSize += Padding;
2561     ContentSize += (List.size() + 1) * TupleSize;
2562
2563     // For each compile unit, write the list of spans it covers.
2564     Asm->OutStreamer.AddComment("Length of ARange Set");
2565     Asm->EmitInt32(ContentSize);
2566     Asm->OutStreamer.AddComment("DWARF Arange version number");
2567     Asm->EmitInt16(dwarf::DW_ARANGES_VERSION);
2568     Asm->OutStreamer.AddComment("Offset Into Debug Info Section");
2569     Asm->EmitSectionOffset(CU->getLocalLabelBegin(), CU->getLocalSectionSym());
2570     Asm->OutStreamer.AddComment("Address Size (in bytes)");
2571     Asm->EmitInt8(PtrSize);
2572     Asm->OutStreamer.AddComment("Segment Size (in bytes)");
2573     Asm->EmitInt8(0);
2574
2575     Asm->OutStreamer.EmitFill(Padding, 0xff);
2576
2577     for (const ArangeSpan &Span : List) {
2578       Asm->EmitLabelReference(Span.Start, PtrSize);
2579
2580       // Calculate the size as being from the span start to it's end.
2581       if (Span.End) {
2582         Asm->EmitLabelDifference(Span.End, Span.Start, PtrSize);
2583       } else {
2584         // For symbols without an end marker (e.g. common), we
2585         // write a single arange entry containing just that one symbol.
2586         uint64_t Size = SymSize[Span.Start];
2587         if (Size == 0)
2588           Size = 1;
2589
2590         Asm->OutStreamer.EmitIntValue(Size, PtrSize);
2591       }
2592     }
2593
2594     Asm->OutStreamer.AddComment("ARange terminator");
2595     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2596     Asm->OutStreamer.EmitIntValue(0, PtrSize);
2597   }
2598 }
2599
2600 // Emit visible names into a debug ranges section.
2601 void DwarfDebug::emitDebugRanges() {
2602   // Start the dwarf ranges section.
2603   Asm->OutStreamer.SwitchSection(
2604       Asm->getObjFileLowering().getDwarfRangesSection());
2605
2606   // Size for our labels.
2607   unsigned char Size = Asm->getDataLayout().getPointerSize();
2608
2609   // Grab the specific ranges for the compile units in the module.
2610   for (const auto &I : CUMap) {
2611     DwarfCompileUnit *TheCU = I.second;
2612
2613     // Emit a symbol so we can find the beginning of our ranges.
2614     Asm->OutStreamer.EmitLabel(TheCU->getLabelRange());
2615
2616     // Iterate over the misc ranges for the compile units in the module.
2617     for (const RangeSpanList &List : TheCU->getRangeLists()) {
2618       // Emit our symbol so we can find the beginning of the range.
2619       Asm->OutStreamer.EmitLabel(List.getSym());
2620
2621       for (const RangeSpan &Range : List.getRanges()) {
2622         const MCSymbol *Begin = Range.getStart();
2623         const MCSymbol *End = Range.getEnd();
2624         assert(Begin && "Range without a begin symbol?");
2625         assert(End && "Range without an end symbol?");
2626         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2627         Asm->OutStreamer.EmitSymbolValue(End, Size);
2628       }
2629
2630       // And terminate the list with two 0 values.
2631       Asm->OutStreamer.EmitIntValue(0, Size);
2632       Asm->OutStreamer.EmitIntValue(0, Size);
2633     }
2634
2635     // Now emit a range for the CU itself.
2636     if (useCURanges() && TheCU->getRanges().size()) {
2637       Asm->OutStreamer.EmitLabel(
2638           Asm->GetTempSymbol("cu_ranges", TheCU->getUniqueID()));
2639       for (const RangeSpan &Range : TheCU->getRanges()) {
2640         const MCSymbol *Begin = Range.getStart();
2641         const MCSymbol *End = Range.getEnd();
2642         assert(Begin && "Range without a begin symbol?");
2643         assert(End && "Range without an end symbol?");
2644         Asm->OutStreamer.EmitSymbolValue(Begin, Size);
2645         Asm->OutStreamer.EmitSymbolValue(End, Size);
2646       }
2647       // And terminate the list with two 0 values.
2648       Asm->OutStreamer.EmitIntValue(0, Size);
2649       Asm->OutStreamer.EmitIntValue(0, Size);
2650     }
2651   }
2652 }
2653
2654 // DWARF5 Experimental Separate Dwarf emitters.
2655
2656 void DwarfDebug::initSkeletonUnit(const DwarfUnit *U, DIE *Die,
2657                                   DwarfUnit *NewU) {
2658   NewU->addLocalString(Die, dwarf::DW_AT_GNU_dwo_name,
2659                        U->getCUNode().getSplitDebugFilename());
2660
2661   // Relocate to the beginning of the addr_base section, else 0 for the
2662   // beginning of the one for this compile unit.
2663   if (Asm->MAI->doesDwarfUseRelocationsAcrossSections())
2664     NewU->addSectionLabel(Die, dwarf::DW_AT_GNU_addr_base, DwarfAddrSectionSym);
2665   else
2666     NewU->addSectionOffset(Die, dwarf::DW_AT_GNU_addr_base, 0);
2667
2668   if (!CompilationDir.empty())
2669     NewU->addLocalString(Die, dwarf::DW_AT_comp_dir, CompilationDir);
2670
2671   addGnuPubAttributes(NewU, Die);
2672
2673   SkeletonHolder.addUnit(NewU);
2674 }
2675
2676 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_stmt_list,
2677 // DW_AT_low_pc, DW_AT_high_pc, DW_AT_ranges, DW_AT_dwo_name, DW_AT_dwo_id,
2678 // DW_AT_ranges_base, DW_AT_addr_base.
2679 // TODO: Implement DW_AT_ranges_base.
2680 DwarfCompileUnit *DwarfDebug::constructSkeletonCU(const DwarfCompileUnit *CU) {
2681
2682   DIE *Die = new DIE(dwarf::DW_TAG_compile_unit);
2683   DwarfCompileUnit *NewCU = new DwarfCompileUnit(
2684       CU->getUniqueID(), Die, CU->getCUNode(), Asm, this, &SkeletonHolder);
2685   NewCU->initSection(Asm->getObjFileLowering().getDwarfInfoSection(),
2686                      DwarfInfoSectionSym);
2687
2688   NewCU->initStmtList(DwarfLineSectionSym);
2689
2690   initSkeletonUnit(CU, Die, NewCU);
2691
2692   return NewCU;
2693 }
2694
2695 // This DIE has the following attributes: DW_AT_comp_dir, DW_AT_dwo_name,
2696 // DW_AT_addr_base.
2697 DwarfTypeUnit *DwarfDebug::constructSkeletonTU(DwarfTypeUnit *TU) {
2698   DwarfCompileUnit &CU = static_cast<DwarfCompileUnit &>(
2699       *SkeletonHolder.getUnits()[TU->getCU().getUniqueID()]);
2700
2701   DIE *Die = new DIE(dwarf::DW_TAG_type_unit);
2702   DwarfTypeUnit *NewTU =
2703       new DwarfTypeUnit(TU->getUniqueID(), Die, CU, Asm, this, &SkeletonHolder);
2704   NewTU->setTypeSignature(TU->getTypeSignature());
2705   NewTU->setType(NULL);
2706   NewTU->initSection(
2707       Asm->getObjFileLowering().getDwarfTypesSection(TU->getTypeSignature()));
2708   CU.applyStmtList(*Die);
2709
2710   initSkeletonUnit(TU, Die, NewTU);
2711   return NewTU;
2712 }
2713
2714 // Emit the .debug_info.dwo section for separated dwarf. This contains the
2715 // compile units that would normally be in debug_info.
2716 void DwarfDebug::emitDebugInfoDWO() {
2717   assert(useSplitDwarf() && "No split dwarf debug info?");
2718   InfoHolder.emitUnits(this,
2719                        Asm->getObjFileLowering().getDwarfAbbrevDWOSection(),
2720                        DwarfAbbrevDWOSectionSym);
2721 }
2722
2723 // Emit the .debug_abbrev.dwo section for separated dwarf. This contains the
2724 // abbreviations for the .debug_info.dwo section.
2725 void DwarfDebug::emitDebugAbbrevDWO() {
2726   assert(useSplitDwarf() && "No split dwarf?");
2727   InfoHolder.emitAbbrevs(Asm->getObjFileLowering().getDwarfAbbrevDWOSection());
2728 }
2729
2730 // Emit the .debug_str.dwo section for separated dwarf. This contains the
2731 // string section and is identical in format to traditional .debug_str
2732 // sections.
2733 void DwarfDebug::emitDebugStrDWO() {
2734   assert(useSplitDwarf() && "No split dwarf?");
2735   const MCSection *OffSec =
2736       Asm->getObjFileLowering().getDwarfStrOffDWOSection();
2737   const MCSymbol *StrSym = DwarfStrSectionSym;
2738   InfoHolder.emitStrings(Asm->getObjFileLowering().getDwarfStrDWOSection(),
2739                          OffSec, StrSym);
2740 }
2741
2742 void DwarfDebug::addDwarfTypeUnitType(DwarfCompileUnit &CU,
2743                                       StringRef Identifier, DIE *RefDie,
2744                                       DICompositeType CTy) {
2745   // Flag the type unit reference as a declaration so that if it contains
2746   // members (implicit special members, static data member definitions, member
2747   // declarations for definitions in this CU, etc) consumers don't get confused
2748   // and think this is a full definition.
2749   CU.addFlag(RefDie, dwarf::DW_AT_declaration);
2750
2751   const DwarfTypeUnit *&TU = DwarfTypeUnits[CTy];
2752   if (TU) {
2753     CU.addDIETypeSignature(RefDie, *TU);
2754     return;
2755   }
2756
2757   DIE *UnitDie = new DIE(dwarf::DW_TAG_type_unit);
2758   DwarfTypeUnit *NewTU = new DwarfTypeUnit(InfoHolder.getUnits().size(),
2759                                            UnitDie, CU, Asm, this, &InfoHolder);
2760   TU = NewTU;
2761   InfoHolder.addUnit(NewTU);
2762
2763   NewTU->addUInt(UnitDie, dwarf::DW_AT_language, dwarf::DW_FORM_data2,
2764                  CU.getLanguage());
2765
2766   MD5 Hash;
2767   Hash.update(Identifier);
2768   // ... take the least significant 8 bytes and return those. Our MD5
2769   // implementation always returns its results in little endian, swap bytes
2770   // appropriately.
2771   MD5::MD5Result Result;
2772   Hash.final(Result);
2773   uint64_t Signature = *reinterpret_cast<support::ulittle64_t *>(Result + 8);
2774   NewTU->setTypeSignature(Signature);
2775   if (useSplitDwarf())
2776     NewTU->setSkeleton(constructSkeletonTU(NewTU));
2777   else
2778     CU.applyStmtList(*UnitDie);
2779
2780   NewTU->setType(NewTU->createTypeDIE(CTy));
2781
2782   NewTU->initSection(
2783       useSplitDwarf()
2784           ? Asm->getObjFileLowering().getDwarfTypesDWOSection(Signature)
2785           : Asm->getObjFileLowering().getDwarfTypesSection(Signature));
2786
2787   CU.addDIETypeSignature(RefDie, *NewTU);
2788 }
2789
2790 void DwarfDebug::attachLowHighPC(DwarfCompileUnit *Unit, DIE *D,
2791                                  MCSymbol *Begin, MCSymbol *End) {
2792   Unit->addLabelAddress(D, dwarf::DW_AT_low_pc, Begin);
2793   if (DwarfVersion < 4)
2794     Unit->addLabelAddress(D, dwarf::DW_AT_high_pc, End);
2795   else
2796     Unit->addLabelDelta(D, dwarf::DW_AT_high_pc, End, Begin);
2797 }