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