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