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