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