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